我在我的应用程序中使用Python的请求库。该方法的主体如下所示:
def handle_remote_file(url, **kwargs):
response = requests.get(url, ...)
buff = StringIO.StringIO()
buff.write(response.content)
...
return True
我想为该方法编写一些单元测试,但是,我想做的是传递一个虚假的本地 url,例如:
class RemoteTest(TestCase):
def setUp(self):
self.url = 'file:///tmp/dummy.txt'
def test_handle_remote_file(self):
self.assertTrue(handle_remote_file(self.url))
当我使用本地 url 调用 requests.get 时,我收到了以下 KeyError 异常:
requests.get('file:///tmp/dummy.txt')
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/packages/urllib3/poolmanager.pyc in connection_from_host(self, host, port, scheme)
76
77 # Make a fresh ConnectionPool of the desired type
78 pool_cls = pool_classes_by_scheme[scheme]
79 pool = pool_cls(host, port, **self.connection_pool_kw)
80
KeyError: 'file'
问题是如何将本地 url 传递给 requests.get?
PS:上面的例子是我编的。它可能包含许多错误。
@WooParadog解释的那样,请求库不知道如何处理本地文件。虽然,当前版本允许定义传输适配器。
因此,您可以简单地定义自己的适配器,该适配器将能够处理本地文件,例如:
from requests_testadapter import Resp
import os
class LocalFileAdapter(requests.adapters.HTTPAdapter):
def build_response_from_file(self, request):
file_path = request.url[7:]
with open(file_path, 'rb') as file:
buff = bytearray(os.path.getsize(file_path))
file.readinto(buff)
resp = Resp(buff)
r = self.build_response(request, resp)
return r
def send(self, request, stream=False, timeout=None,
verify=True, cert=None, proxies=None):
return self.build_response_from_file(request)
requests_session = requests.session()
requests_session.mount('file://', LocalFileAdapter())
requests_session.get('file://<some_local_path>')
我在上面的例子中使用了请求测试适配器模块。
这是我写的一个传输适配器,它比 b1r3k 的功能更强大,并且除了请求本身之外没有其他依赖项。我还没有详尽地测试它,但我尝试过的似乎没有错误。
import requests
import os, sys
if sys.version_info.major < 3:
from urllib import url2pathname
else:
from urllib.request import url2pathname
class LocalFileAdapter(requests.adapters.BaseAdapter):
"""Protocol Adapter to allow Requests to GET file:// URLs
@todo: Properly handle non-empty hostname portions.
"""
@staticmethod
def _chkpath(method, path):
"""Return an HTTP status for the given filesystem path."""
if method.lower() in ('put', 'delete'):
return 501, "Not Implemented" # TODO
elif method.lower() not in ('get', 'head'):
return 405, "Method Not Allowed"
elif os.path.isdir(path):
return 400, "Path Not A File"
elif not os.path.isfile(path):
return 404, "File Not Found"
elif not os.access(path, os.R_OK):
return 403, "Access Denied"
else:
return 200, "OK"
def send(self, req, **kwargs): # pylint: disable=unused-argument
"""Return the file specified by the given request
@type req: C{PreparedRequest}
@todo: Should I bother filling `response.headers` and processing
If-Modified-Since and friends using `os.stat`?
"""
path = os.path.normcase(os.path.normpath(url2pathname(req.path_url)))
response = requests.Response()
response.status_code, response.reason = self._chkpath(req.method, path)
if response.status_code == 200 and req.method.lower() != 'head':
try:
response.raw = open(path, 'rb')
except (OSError, IOError) as err:
response.status_code = 500
response.reason = str(err)
if isinstance(req.url, bytes):
response.url = req.url.decode('utf-8')
else:
response.url = req.url
response.request = req
response.connection = self
return response
def close(self):
pass
(尽管有这个名字,但它完全是在我想检查谷歌之前写的,所以它与b1r3k无关。与另一个答案一样,请遵循以下内容:
requests_session = requests.session()
requests_session.mount('file://', LocalFileAdapter())
r = requests_session.get('file:///path/to/your/file')
最简单的方法似乎是使用请求文件。
https://github.com/dashea/requests-file(也可通过 PyPI 获得)
"Requests-File 是一个传输适配器,用于 Requests Python 库,允许通过 file://URL 访问本地文件系统。
这与 requests-html 相结合是纯粹的魔术:)
packages/urllib3/poolManager.py几乎解释了它。请求不支持本地 URL。
pool_classes_by_scheme = {
'http': HTTPConnectionPool,
'https': HTTPSConnectionPool,
}
在最近的一个项目中,我遇到了同样的问题。由于请求不支持"file"方案,我将修补我们的代码以在本地加载内容。首先,我定义一个函数来替换requests.get
:
def local_get(self, url):
"Fetch a stream from local files."
p_url = six.moves.urllib.parse.urlparse(url)
if p_url.scheme != 'file':
raise ValueError("Expected file scheme")
filename = six.moves.urllib.request.url2pathname(p_url.path)
return open(filename, 'rb')
然后,在测试设置或装饰测试函数的某个地方,我使用 mock.patch
在请求上修补 get 函数:
@mock.patch('requests.get', local_get)
def test_handle_remote_file(self):
...
这种技术有点脆弱 - 如果底层代码调用requests.request
或构造一个Session
并调用它,则无济于事。可能有一种方法可以在较低级别修补请求以支持file:
URL,但在我最初的调查中,似乎没有明显的钩点,所以我采用了这种更简单的方法。
要从本地 URL 加载文件,例如图像文件,您可以执行以下操作:
import urllib
from PIL import Image
Image.open(urllib.request.urlopen('file:///path/to/your/file.png'))