====== Requêtes HTTP en Python ======
* [[https://docs.python.org/fr/3/library/urllib.request.html]]
* [[https://docs.python.org/3.1/howto/urllib2.html]]
* [[https://stackoverflow.com/questions/32795460/loading-json-object-in-python-using-urllib-request-and-json-modules]]
* [[http://zetcode.com/python/requests/]]
import urllib.request
import json
req = urllib.request.Request("https://adresse.com")
with urllib.request.urlopen(req) as f:
response = f.read()
data = json.loads(response.decode('utf-8'))
print(data) # dictionnaire de la réponse JSON
Requête POST:
post_data = {
"title": box['title'],
"parent_folder": "-1"
}
# avec des données, la requête est automatiquement une POST
req = urllib.request.Request("https://url.com/form.php", urllib.parse.urlencode(post_data).encode('ascii'))
with urllib.request.urlopen(req) as f:
response = f.read()
Avec une authentification basique:
import base64
credentials = {
"Authorization": b'Basic ' + base64.b64encode("user:pass".encode())
}
req = urllib.request.Request("https://adresse.com", headers=credentials)
# ou
req = urllib.request.Request("https://url.com/form.php", urllib.parse.urlencode(post_data).encode('ascii'), credentials)
==== Encoder une URL ====
[[https://stackoverflow.com/questions/1695183/how-to-percent-encode-url-parameters-in-python|Source]]
urllib.parse.quote(url)
==== Sessions ====
Avec [[https://fr.python-requests.org/en/latest/#__do_not_save__|Requests]].
session = requests.Session()
session.headers['Accept'] = 'application/vnd.github.v3+json'
session.auth = ("user", "pass")
r = session.get(url)
if r.status_code != 200:
print("Got HTTP response {}: {}".format(r.status_code, r.json()['message']))
else:
print(r.json())
session.close()
==== Changer le User-Agent ====
[[https://stackoverflow.com/questions/24226781/changing-user-agent-in-python-3-for-urrlib-request-urlopen|Source]]
from urllib.request import urlopen, Request
urlopen(Request(url, headers={'User-Agent': 'Mozilla'}))
==== Serveur HTTP ====
* [[https://realpython.com/python-http-server/|How to Launch an HTTP Server in One Line of Python Code]]