通过Python请求从本地URL提取文件?

问题描述 投票:23回答:4

我在我的应用程序的一种方法中使用Python的requests库。该方法的主体如下所示:

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:我整理了上面的示例。它可能包含许多错误。

python http python-requests local-files
4个回答
28
投票

正如@WooParadog解释的那样,请求库不知道如何处理本地文件。虽然,当前版本允许定义transport adapters

因此,您可以简单地定义自己的适配器,该适配器将能够处理本地文件,例如:

from requests_testadapter import Resp

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>')

在上面的示例中,我正在使用requests-testadapter模块。


14
投票

这里是我编写的传输适配器,它比b1r3k的功能更强大,并且除了Requests本身之外没有其他依赖项。我尚未对其进行详尽的测试,但是我尝试的内容似乎没有错误。

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

((尽管名称,它完全写在我想检查Google之前,所以它与b1r3k无关。)与其他答案一样,请遵循以下条件:

requests_session = requests.session()
requests_session.mount('file://', LocalFileAdapter())
r = requests_session.get('file:///path/to/your/file')

9
投票

packages/urllib3/poolmanager.py几乎可以解释这一点。请求不支持本地网址。

pool_classes_by_scheme = {                                                        
    'http': HTTPConnectionPool,                                                   
    'https': HTTPSConnectionPool,                                              
}                                                                                 

6
投票

[在最近的项目中,我遇到了同样的问题。由于请求不支持“文件”方案,因此我将修补我们的代码以在本地加载内容。首先,我定义一个函数来替换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,但是在我的初步调查中,似乎没有明显的关联点,因此我采用了这种简单的方法。

© www.soinside.com 2019 - 2024. All rights reserved.