简体   繁体   中英

How to send data from python client to Django web server?

I'd like python3 program to send JSON data to Django web server and print them on web page. This is what I have in Views.py:

def receive_json(request):
    if request.method == 'POST':
        received_data = json.loads(request.body.decode("utf-8"))
        return StreamingHttpResponse('it was post request: ' + str(received_data))
    return StreamingHttpResponse('it was get request')

And the python code:

import requests
import json
url = "http://127.0.0.1:8000/"
data = {"data": [{'key1':'val1'}, {'key2':'val2'}]}
headers = {'content-type':'application/json'}
r = requests.post(url, data=json.dumps(data), headers=headers)
r.text

However, it shows this message:

Forbidden (CSRF cookie not set.): /
[28/May/2021 16:51:31] "POST / HTTP/1.1" 403 2864
import requests
import json
url = "http://127.0.0.1:8000/"
data = {"data": [{'key1':'val1'}, {'key2':'val2'}]}
headers = {'content-type':'application/json','Cookie':'csrftoken=axXsa39e5hq8gqlTjJFHAbUWtg2FQgnSd3cxxkx9khatqgersthtSryDxtF0cVCk'}
r = requests.post(url, data=json.dumps(data), headers=headers)
r.text

i think these may works by adding Cookie but it would be better if u use @csrf_exempt decorater in receive_json function by these way

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def receive_json(request):
    if request.method == 'POST':
        received_data = json.loads(request.body.decode("utf-8"))
        return StreamingHttpResponse('it was post request: ' + str(received_data))
    return StreamingHttpResponse('it was get request')

Essentially you need first to perform a GET request to get a csrftoken, than post that together with the data. There are a few ways to do this. Here is one (untested however):

import requests
import json
url = "http://127.0.0.1:8000/"


s = requests.Session()
s.get(url)
headers = {
  'content-type':'application/json',
  'X-CSRFToken': s.cookies["csrftoken"],
}
data = {"data": [{'key1':'val1'}, {'key2':'val2'}]}
r = s.post(url, data=json.dumps(data), headers=headers)
r.text

You can find more information in Django's CSRF documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM