How to use Requsts to send arguments in url, POST data, JSON data or file to Flask
This code will display different data from requests
to show how flask
get them.
from flask import Flask, request
app = Flask(__name__)
@app.route("/", methods=['GET', 'POST'])
def index():
print('args:', request.args)
print('form:', request.form)
print('json:', request.json)
print('data:', request.data)
return ''
if __name__ == '__main__':
app.run()
Send as args in url - params=
import requests
data = {'text': 'Hello', 'value': 100}
r = requests.get('http://localhost:5000/', params=data)
#r = requests.post('http://localhost:5000/', params=data)
Result:
args: ImmutableMultiDict([('text', 'Hello'), ('value', '100')])
form: ImmutableMultiDict([])
json: None
data: b''
files: ImmutableMultiDict([])
params=
is used mostly with get()
but it can be used also in post()
Send as form data - data=
import requests
data = {'text': 'Hello', 'value': 100}
#r = requests.get('http://localhost:5000/', data=data)
r = requests.post('http://localhost:5000/', data=data)
Result:
args: ImmutableMultiDict([])
form: ImmutableMultiDict([('text', 'Hello'), ('value', '100')])
json: None
data: b''
files: ImmutableMultiDict([])
data=
is used mostly with post()
but it can be used also in get()
Send as JSON data - json=
import requests
data = {'text': 'Hello', 'value': 100}
#r = requests.get('http://localhost:5000/', json=data)
r = requests.post('http://localhost:5000/', json=data)
Result:
args: ImmutableMultiDict([])
form: ImmutableMultiDict([])
json: {'text': 'Hello', 'value': 100}
data: b'{"text": "Hello", "value": 100}'
files: ImmutableMultiDict([])
json=
is used mostly with post()
but it can be used also in get()
Send as files data - files=
import requests
data = {'text': 'Hello', 'value': 100}
#r = requests.get('http://localhost:5000/', files=data)
r = requests.post('http://localhost:5000/', files=data)
Result:
args: ImmutableMultiDict([])
form: ImmutableMultiDict([])
json: None
data: b''
files: ImmutableMultiDict([('text', <FileStorage: 'text' (None)>), ('value', <FileStorage: 'value' (None)>)])
files=
is used mostly with post()
but it can be used also in get()
You can see data also if you display request's body
import requests
data = {'text': 'Hello', 'value': 100}
r = requests.post('https://httpbin.org/post', data=data)
print('form:', r.request.body)
r = requests.post('https://httpbin.org/post', json=data)
print('json:', r.request.body)
r = requests.post('https://httpbin.org/post', files=data)
print('file:', r.request.body)
Result:
form: text=Hello&value=100
json: b'{"text": "Hello", "value": 100}'
file: b'--2a0f189d55cfce27736cb0ce44d8621b\r\nContent-Disposition: form-data; name="text"; filename="text"\r\n\r\nHello\r\n--2a0f189d55cfce27736cb0ce44d8621b\r\nContent-Disposition: form-data; name="value"; filename="value"\r\n\r\n100\r\n--2a0f189d55cfce27736cb0ce44d8621b--\r\n'
If you like it
Buy a Coffee
