Python requests: URL base in Session

2024/11/19 19:34:12

When using a Session, it seems you need to provide the full URL each time, e.g.

session = requests.Session()
session.get('http://myserver/getstuff')
session.get('http://myserver/getstuff2')

This gets a little tedious. Is there a way to do something like:

session = requests.Session(url_base='http://myserver')
session.get('/getstuff')
session.get('/getstuff2')
Answer

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 urljoinclass LiveServerSession(Session):def __init__(self, base_url=None):super().__init__()self.base_url = base_urldef 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')
https://en.xdnf.cn/q/26402.html

Related Q&A

size of NumPy array

Is there an equivalent to the MATLAB size() command in Numpy? In MATLAB, >>> a = zeros(2,5)0 0 0 0 00 0 0 0 0 >>> size(a)2 5In Python, >>> a = zeros((2,5)) >>> a ar…

Feature Importance Chart in neural network using Keras in Python

I am using python(3.6) anaconda (64 bit) spyder (3.1.2). I already set a neural network model using keras (2.0.6) for a regression problem(one response, 10 variables). I was wondering how can I generat…

numpy.max or max ? Which one is faster?

In python, which one is faster ? numpy.max(), numpy.min()ormax(), min()My list/array length varies from 2 to 600. Which one should I use to save some run time ?

Nested Json to pandas DataFrame with specific format

I need to format the contents of a Json file in a certain format in a pandas DataFrame so that I can run pandassql to transform the data and run it through a scoring model. file = C:\scoring_model\json…

Iterating over dictionary items(), values(), keys() in Python 3

If I understand correctly, in Python 2, iter(d.keys()) was the same as d.iterkeys(). But now, d.keys() is a view, which is in between the list and the iterator. Whats the difference between a view and …

Is there a method that tells my program to quit?

For the "q" (quit) option in my program menu, I have the following code:elif choice == "q":print()That worked all right until I put it in an infinite loop, which kept printing blank…

Hiding Axis Labels

Im trying to hide the axis labels on the first subplot at 211. Id like to label the figure, not just a subplot (reference: "Isub Event Characteristics"). How can I control font properties lik…

Why does Python preemptively hang when trying to calculate a very large number?

Ive asked this question before about killing a process that uses too much memory, and Ive got most of a solution worked out.However, there is one problem: calculating massive numbers seems to be untouc…

Django, name parameter in urlpatterns

Im following a tutorial where my urlpatterns are:urlpatterns = patterns(,url(r^passwords/$, PasswordListView.as_view(), name=passwords_api_root),url(r^passwords/(?P<id>[0-9]+)$, PasswordInstance…

The most Pythonic way of checking if a value in a dictionary is defined/has zero length

Say I have a dictionary, and I want to check if a key is mapped to a nonempty value. One way of doing this would be the len function:mydict = {"key" : "value", "emptykey"…