I've used a variety of python HTTP libs in the past, and I've settled on requests as my favourite. Existing libs had pretty useable interfaces, but code can end up being a few lines too long for simple operations. A basic PUT in requests looks like:
payload = {'username': 'bob', 'email': '[email protected]'}
>>> r = requests.put("http://somedomain.org/endpoint", data=payload)
You can then check the response status code with:
r.status_code
or the response with:
r.content
Requests has a lot synactic sugar and shortcuts that'll make your life easier.
Answer from John Bear on Stack OverflowHTTP PUT request in Python using JSON data - Stack Overflow
Put request using python
Building a Python PUT/UPDATE request dictionary
I don't really understand Requests python module
Videos
I've used a variety of python HTTP libs in the past, and I've settled on requests as my favourite. Existing libs had pretty useable interfaces, but code can end up being a few lines too long for simple operations. A basic PUT in requests looks like:
payload = {'username': 'bob', 'email': '[email protected]'}
>>> r = requests.put("http://somedomain.org/endpoint", data=payload)
You can then check the response status code with:
r.status_code
or the response with:
r.content
Requests has a lot synactic sugar and shortcuts that'll make your life easier.
import urllib2
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request('http://example.org', data='your_put_data')
request.add_header('Content-Type', 'your/contenttype')
request.get_method = lambda: 'PUT'
url = opener.open(request)
Your data is already a JSON-formatted string. You can pass it directly to requests.put instead of converting it with json.dumps again.
Change:
response = requests.put(url, data=json.dumps(data), headers=headers)
to:
response = requests.put(url, data=data, headers=headers)
Alternatively, your data can store a data structure instead, so that json.dumps can convert it to JSON.
Change:
data = '[{"$key": 8},{"$key": 7}]'
to:
data = [{"$key": 8},{"$key": 7}]
HTTP methods in the requests library have a json argument that, when given, will perform json.dumps() for you and set the Content-Type header to application/json:
data = [{"$key": 8},{"$key": 7}]
response = requests.put(url, json=data)
Hey everyone,
I am building a system with an ESP32 microcontroller, which should adjust the time according to the date. I have an external file that I want to get the current date-time and put on the server, then the micmicrocontroller asks for the time and adjust it. I have created a server, I can acaccesst and use get requests, but I can not put information there, which is what I need. What can I do here?
import datetime
import requests
req = requests.get('http://192.168.137.10:8081/')
j_data = {"time": "something", "mode": "mode"}
print(req.text)
url = 'http://192.168.137.10:8081/'
req1 = requests.put(url, j_data)