Python requests: URL base in Session

This feature has been asked on the forums a few times 1, 2, 3. The preferred approach as documented here, is subclassing, as follows:

from requests import Session
from urllib.parse import urljoin

class LiveServerSession(Session):
    def __init__(self, base_url=None):
        super().__init__()
        self.base_url = base_url

    def request(self, method, url, *args, **kwargs):
        joined_url = urljoin(self.base_url, url)
        return super().request(method, joined_url, *args, **kwargs)

You would use this simply as follows:

baseUrl="http://api.twitter.com"
with LiveServerSession(baseUrl) as s:
    resp = s.get('/1/statuses/home_timeline.json')

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)