如何使用Django发送POST请求?

问题描述 投票:29回答:5

我不想使用html文件,但只有django才需要发出POST请求。

就像urllib2发送get请求一样。

python django urllib2
5个回答
32
投票

结合使用urllib2和urllib中的方法将达到目的。这是我使用这两个方法发布数据的方式:

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

urlopen()是用于打开网址的方法。urlencode()将参数转换为百分比编码的字符串。


32
投票

这是使用python-requests编写接受答案的示例的方式:

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

更加直观。有关更简单的示例,请参见Quickstart


6
投票

您现在唯一要看的是:

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


4
投票

可以在Django中使用urllib2。毕竟,它仍然是python。要将POSTurllib2一起发送,可以发送data参数(取自here):

urllib2.urlopen(url [,data] [,timeout])

[..]提供数据参数时,HTTP请求将是POST而不是GET


1
投票

请注意,当您使用🐍requests并发出POST请求,将您的字典传递给data参数时,如下所示:

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

您正在传递参数form-encoded

如果仅使用JSON(服务器-服务器集成中最流行的类型)发送POST请求,则需要在str()参数中提供data。如果使用JSON,则需要import json lib并进行如下操作:

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

文档is here

© www.soinside.com 2019 - 2024. All rights reserved.