37๐
In Python 2, a combination of methods from urllib2
and urllib
will do the trick. 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.
urlencode() converts the arguments to percent-encoded string.
45๐
Hereโs how youโd write the accepted answerโs example using 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.
- [Django]-What is "load url from future" in Django
- [Django]-Django substr / substring in templates
- [Django]-Django development IDE
- [Django]-Location of Django logs and errors
- [Django]-Django and Restful APIs
- [Django]-How to encode UTF8 filename for HTTP headers? (Python, Django)
5๐
You can use urllib2
in django. After all, itโs still python. To send a POST
with urllib2
, you can send the data
parameter (taken from here):
urllib2.urlopen(url[, data][, timeout])
[..] the HTTP request will be a POST instead of a GET when the data parameter is provided
- [Django]-Django vs. Model View Controller
- [Django]-How to add Indian Standard Time (IST) in Django?
- [Django]-Save() prohibited to prevent data loss due to unsaved related object
2๐
Pay attention, that when youโre using ๐ requests
, and make POST
request passing your dictionary in data
parameter like this:
payload = {'param1':1, 'param2':2}
r = request.post('https://domain.tld', data=payload)
you are passing parameters 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. In case with JSON, you need to import json
lib and make like this:
payload = {'param1':1, 'param2':2}
r = request.post('https://domain.tld', data=json.dumps(payload))`
documentation is here
OR:
just use json
parameter with provided data in the dict
payload = {'param1':1, 'param2':2}
r = request.post('https://domain.tld', json=payload)`
- [Django]-How to render an ordered dictionary in django templates?
- [Django]-Different db for testing in Django?
- [Django]-How to force Django Admin to use select_related?