0

I have been asked to understand and maintain code like the following code block.

@app.route("/api/v1/users/register/", methods=["POST"])
def register():
    data = {
        "lat": request.data.get("lat", ""),
        "lon": request.data.get("lon", ""),
        "is_bl_allowed": request.data.get("is_bl_allowed", 1),
        "is_loc_allowed": request.data.get("is_loc_allowed", 1),
        "is_bl_on": request.data.get("is_bl_on", 1),
        "is_loc_on": request.data.get("is_loc_on", 1)
    }

Imports are

from flask import make_response
from flask import request, jsonify
import requests

I thought flask request used get_json or form.get to retrive POST request data. I am not sure what is being retrieved in this code block. I do not have access to the code that is calling this API. If anyone can explain what the request.data.get does, what its return value would be and why it takes 2 parameters, that would be awesome.

Thanks in advance.

searcot jabali
  • 438
  • 6
  • 16

2 Answers2

2

For a post request like this, the request.data attribute is like a dictionary. If you have a dictionary in python you can use get to specify a key you want the value for in the dictionary, for example:

example = {"key": "value"}
example.get("key")  # gives you "value"

The difference between using get and simply doing example["key"] is that you won't get and error of the key is missing:

example = {"key": "value"}
example.get("other")  # gives you None
example["other"]  # raises KeyError

You can also (as in your example) give a default value for a missing key:

example = {"key": "value"}
example.get("key")  # gives you "value"
example.get("other", "different value")  # gives you "different value"

So, for your end point the code is trying to get a series of data points from the post request using data.get and is using default values (empty string or 1) for missing values.

PirateNinjas
  • 1,908
  • 1
  • 16
  • 21
  • Thank you Does that mean **"request.user.get("xxxxxx")** is also pre defined? I assumed there was some form of function overloading going on here. But I am not sure now. – searcot jabali Jul 06 '20 at 11:11
  • you example doesn't contain anything related to user, so I can't be 100% sure, but most likely it's similar: a dictionary-like behaviour which can be accessed with get. – PirateNinjas Jul 06 '20 at 11:24
1

Flask sets request.data or request.form for POST requests, not both.

  • request.form is populated if Flask understood the POST request.
  • request.data is populated if Flask couldn't understand the request enough to put the values in request.form. This could be a Flask issue or possibly due to a missing or unsatisfactory Content-type header.

Therefore you cannot refactor this code to use .form because it will be empty.

Both are dictionaries so you can use the optional .get() way of access and provide a default value as the second argument.

MrCode
  • 63,975
  • 10
  • 90
  • 112