Repository navigation
Rewriting the url of a httpx.Request #3537
Replies: 1 comment
|
For the fixed GitHub API origin in your example, configure import httpx
async def update_file(auth, repo, file_path, payload):
async with httpx.AsyncClient(
base_url="https://api.github.com",
auth=auth,
headers={"Accept": "application/vnd.github+json"},
) as client:
return await client.put(
f"/repos/{repo}/contents/{file_path}",
json=payload,
)In your application, keep that client at the existing client lifetime and remove the URL-setting hook. The helper above creates a scoped client only to make the example self-contained. Request hooks mutate a request in place; returning a different Client configuration. AI-assisted; checked URL resolution, |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I have an implementation that writes code like:
the
self.http_clientis ahttpx.AsyncHttpClientwith a Custom authentication scheme on it (it adds a token of the authorization header) and aevent_hooksfor request that sets the absolute url for the request.The hook is set at construction time, via:
event_hooks={"request": [set_github_url]},and initially I implemented
set_github_urlas follow:But this does not work. Because the url is now absolute, but the headers on the request don't have the Host header set. When you build a
httpx.Requestwith an absolute url, aself._prepare(headers)call will do that for you, but if you set theurldirectly it does not.so instead my implementation is as follow:
That works, but I find it ugly. Could we have a
set_urlor ajoin_urlfunction the request object that sets the right header for us? Maybe event better acopy_with(url=...)kind of method that return a new copy of the request and leave the older one untouched.Does that make sense?
All reactions