如何使用Django发送POST请求?

40 投票
5 回答
84976 浏览
提问于 2025-04-16 13:42

我不想使用 html 文件,只想用 Django 来发送 POST 请求。

就像 urllib2 发送 GET 请求一样。

5 个回答

8

现在你只需要关注这一点:

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

45

下面是如何使用 python-requests 来写被接受的答案中的例子:

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

这样写起来更直观了。你可以查看 快速入门,里面有更多简单的例子。

37

在Python 2中,可以通过结合使用urllib2urllib这两个模块的方法来实现数据的发送。下面是我使用这两个模块发送数据的方法:

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()则是把参数转换成百分号编码的字符串。

撰写回答