Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask request.form.to_dict() [duplicate]

Tags:

python

flask

I'm facing a problem. I developed an API in Flask. I use python-requests to send POST requests (with dictionaries) to my API. Below, an example of how I sent requests.

import requests

data=dict()
data['a'] = "foo"
data['b'] = "bar"
data['ninja'] = {"Name": "John doe"}

r = requests.post("https://my_own_url.io/", data=data, headers={"content-type" : 'application/x-www-form-urlencoded'}, verify=False)

On the back-end of my flask application, I can received the request :

from flask import Flask, request

@app.route("/", methods=['POST'])
def home():
    content = request.form.to_dict()

if __name__ == "__main__":
    app.run()

Here is my problem, I send a python dictionary :

{'a' : "foo", 'b' : "bar", 'ninja':{'Name': "John Doe"}}

But I can only recover :

{'a' : "foo", 'b' : "bar", 'ninja':'Name'} Here ninja haven't the right value.

Do you know the right way to aim this ? :)

like image 434
PicxyB Avatar asked Sep 18 '25 06:09

PicxyB


1 Answers

You have to get the data on the server side (Flask app) as json, so you can use request.get_json() or request.json:

from flask import Flask, request

app = Flask(__name__)

@app.route("/", methods=['POST'])
def home():
    content = request.get_json()

if __name__ == "__main__":
    app.run()

Send it on the client side as:

import requests

data = dict()
data['a'] = "foo"
data['b'] = "bar"
data['ninja'] = { "Name": "John doe" }

r = requests.post("https://my_own_url.io/", json=data, verify=False)
like image 163
Carlo Zanocco Avatar answered Sep 20 '25 21:09

Carlo Zanocco