简体   繁体   English

如何使用 django 发送 POST 请求?

[英]How to send a POST request using django?

I dont want to use html file, but only with django I have to make POST request.我不想使用html文件,但只有使用 django 我必须发出 POST 请求。

Just like urllib2 sends a get request.就像urllib2发送get请求一样。

Here's how you'd write the accepted answer's example using python-requests :以下是使用python-requests编写已接受答案示例的方法:

post_data = {'name': 'Gladys'}
response = requests.post('http://example.com', data=post_data)
content = response.content

Much more intuitive.更直观。 See the Quickstart for more simple examples.有关更简单的示例,请参阅快速入门

In Python 2, a combination of methods from urllib2 and urllib will do the trick.在 Python 2 中,来自urllib2urllib的方法的组合可以解决问题。 Here is how I post data using the two:以下是我如何使用两者发布数据:

post_data = [('name','Gladys'),]     # a sequence of two element tuples
result = urllib2.urlopen('http://example.com', urllib.urlencode(post_data))
content = result.read()

urlopen() is a method you use for opening urls. urlopen()是一种用于打开 url 的方法。 urlencode() converts the arguments to percent-encoded string. urlencode()将参数转换为百分比编码的字符串。

The only thing you should look at now:你现在应该看的唯一一件事:

https://requests.readthedocs.io/en/master/ https://requests.readthedocs.io/en/master/

You can use urllib2 in django.可以在 Django 中使用urllib2 After all, it's still python.毕竟,它仍然是python。 To send a POST with urllib2 , you can send the data parameter (taken from here ):要使用urllib2发送POST ,您可以发送data参数(取自此处):

urllib2.urlopen(url[, data][, timeout]) urllib2.urlopen(url[, 数据][, 超时])

[..] the HTTP request will be a POST instead of a GET when the data parameter is provided [..] 当提供数据参数时,HTTP 请求将是 POST 而不是 GET

Pay attention, that when you're using 🐍 requests , and make POST request passing your dictionary in data parameter like this:请注意,当您使用 🐍 requests ,并使POST请求在data参数中传递您的字典,如下所示:

payload = {'param1':1, 'param2':2}
r = request.post('https://domain.tld', data=payload)

you are passing parameters form-encoded .您正在传递参数form-encoded

If you want to send POST request with only JSON (most popular type in server-server integration) you need to provide a str() in data parameter.如果您只想使用 JSON(服务器-服务器集成中最流行的类型)发送POST请求,您需要在data参数中提供str() In case with JSON, you need to import json lib and make like this:如果使用 JSON,您需要import json lib 并像这样制作:

 payload = {'param1':1, 'param2':2}
 r = request.post('https://domain.tld', data=json.dumps(payload))`

documentation is here文档在这里

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

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