Simple examples
get
import requests
gotten = requests.get('https://raw.githubusercontent.com/ReneNyffenegger/about-python/master/libraries/requests/get.py')
print('Status code: ', gotten.status_code)
print('Headers:');
for header in gotten.headers:
print(" %-30s: %s" % (header, gotten.headers[header]))
print('Encoding: ', gotten.encoding)
print()
print(gotten.text)
Specify a request header
import requests
query = """
select
(lang(?label) as ?lang)
?label
{
wd:Q22661317 rdfs:label ?label .
}
"""
response = requests.get(
"https://query.wikidata.org/sparql" ,
params = {"query" : query },
headers = {"Accept": "application/sparql-results+json"}
)
print(response.json())
Download and save file
import requests
f = open ('script.downloaded', 'wb')
r = requests.get('https://raw.githubusercontent.com/ReneNyffenegger/about-python/master/libraries/requests/download-and-save-file.py', stream = True)
for chunk in r.iter_content(chunk_size = 1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
f.flush()
f.close()
POSTing UTF-8 data causing wrong Content-Length
I believe that I ran into an issue where the Content-Length
was calculated to low when I tried to POST UTF-8 data with a request similar to:
res = requests.post(
url,
data = body
)
I was able to by explicitly use .encode('utf-8')
on the request's body:
res = requests.post(
url,
data = body.encode('utf-8')
)
Logging
import requests
import logging
from http.client import HTTPConnection
urlliblogger = logging.getLogger('urllib3')
urlliblogger.setLevel(logging.DEBUG)
# logging from urllib3 to console
logstream = logging.StreamHandler()
logstream.setLevel(logging.DEBUG)
urlliblogger.addHandler(logstream)
HTTPConnection.debuglevel = 1
print(requests.get('https://api.openstreetmap.org/api/0.6/node/1894790125'))
Installation on Windows
requests must apparently (at least on my machine) be installed as admin.
As non-admin:
> pip install requests
…
… Rödel rödel rödel
…
ERROR: Could not install packages due to an OSError: [WinError 2] The system cannot find the file specified: 'C:\\Python311\\Scripts\\normalizer.exe' -> 'C:\\Python311\\Scripts\\normalizer.exe.deleteme'
When I tried to install this library on Windows under username René
(note the accent), I received a UnicodeDecodeError: 'ascii' codec can't decode byte 0xe9 in position 57: ordinal not in range(128)
.