Skip to content

Requests

Requests is an elegant and simple HTTP library for Python, built for human beings.

Installation

pip install requests

Usage

Download file

import requests
url = "http://beispiel.dort/ichbineinbild.jpg"
filename = url.split("/")[-1]
r: requests.models.Response = requests.get(url, timeout=0.5)

if r.status_code == 200:
    with open(filename, 'wb') as f:
        f.write(r.content)

Encode url

requests.utils.quote('/test', safe='')

Get

requests.get('{{ url }}')

Put url

requests.put({{ url }})

Put json data url

data = {"key": "value"}
requests.put({{ url }} json=data)

Use cookies between requests

You can use Session objects to persists cookies or default data across all requests.

s = requests.Session()

s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')
r = s.get('https://httpbin.org/cookies')

print(r.text)
# '{"cookies": {"sessioncookie": "123456789"}}'

s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('https://httpbin.org/headers', headers={'x-test2': 'true'})

Use a proxy

http_proxy  = "http://10.10.1.10:3128"
https_proxy = "https://10.10.1.11:1080"
ftp_proxy   = "ftp://10.10.1.10:3128"

proxies = { 
              "http"  : http_proxy, 
              "https" : https_proxy, 
              "ftp"   : ftp_proxy
            }

r = requests.get(url, headers=headers, proxies=proxies)

References