urllib2/requests 和 HTTP 相对路径 [英] urllib2/requests and HTTP relative path
问题描述
如何强制 urllib2/requests 模块使用相对路径而不是完整/绝对 URL??
How can I force urllib2/requests modules to use relative paths instead of full/absolute URL??
当我使用 urllib2/requests 发送请求时,我在代理中看到它解析为:
when I send request using urllib2/requests I see in my proxy that it resolves it to:
GET https://xxxx/path/to/something HTTP/1.1
不幸的是,我将它发送到的服务器无法理解该请求并给了我奇怪的 302.我知道它在 RFC 中,它只是不起作用,我正在尝试在 python 代码中修复它.我无权访问该服务器.
Unfortunately, the server to which I'm sending it, cannot understand that request and gives me weird 302. I know it's in RFC, it just doesn't work and I'm tryign to fix it in python code. I don't have access to that server.
相对路径,效果很好
GET /path/to/something HTTP/1.1
Host: xxxx
那么如何强制 requests/urllib2 不使用绝对路径?并使用简单的相对路径?
So how can I force requests/urllib2 to not use absolute paths? and use simple relative paths?
推荐答案
以下代码可能适用于您的情况:
Probably the following code would do for your case:
from urlparse import urljoin
import requests
class RelativeSession(requests.Session):
def __init__(self, base_url):
super(RelativeSession, self).__init__()
self.__base_url = base_url
def request(self, method, url, **kwargs):
url = urljoin(self.__base_url, url)
return super(RelativeSession, self).request(method, url, **kwargs)
session = RelativeSession('http://server.net')
response = session.get('/rel/url')
这篇关于urllib2/requests 和 HTTP 相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!