简体   繁体   English

如何将数据从 python 客户端发送到 Django web 服务器?

[英]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.我希望 python3 程序将 JSON 数据发送到 Django web 服务器并在 Z2567A58EC9705EB7189DZ 页面上打印它们。 This is what I have in Views.py:这就是我在 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:和 python 代码:

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我认为这些可以通过添加 Cookie 来工作,但如果你通过这些方式在 receive_json function 中使用 @csrf_exempt 装饰器会更好

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.本质上,您首先需要执行 GET 请求以获取 csrftoken,然后将其与数据一起发布。 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 .您可以在Django 的 CSRF 文档中找到更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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