Python请求从本地URL获取文件

ozg*_*gur 22 python http python-requests

我在我的应用程序的一个方法中使用Python的请求库.方法的主体如下所示:

def handle_remote_file(url, **kwargs):
    response = requests.get(url, ...)
    buff = StringIO.StringIO()
    buff.write(response.content)
    ...
    return True
Run Code Online (Sandbox Code Playgroud)

我想为该方法编写一些单元测试,但是,我想要做的是传递一个假的本地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))
Run Code Online (Sandbox Code Playgroud)

当我使用本地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'
Run Code Online (Sandbox Code Playgroud)

问题是如何将本地URL传递给requests.get

PS:我编写了上面的例子.它可能包含许多错误.

b1r*_*r3k 27

由于@WooParadog解释请求库不知道如何处理本地文件.虽然,当前版本允许定义传输适配器.

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

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>')
Run Code Online (Sandbox Code Playgroud)

我在上面的例子中使用了request-testadapter模块.


sso*_*low 12

这是我写的一个传输适配器,它比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
Run Code Online (Sandbox Code Playgroud)

(尽管有这个名字,但是在我考虑检查谷歌之前它是完全写的,所以它与b1r3k无关.)与其他答案一样,请按照以下步骤操作:

requests_session = requests.session()
requests_session.mount('file://', LocalFileAdapter())
r = requests_session.get('file:///path/to/your/file')
Run Code Online (Sandbox Code Playgroud)


Sil*_*Sil 11

最简单的方法似乎是使用请求文件。

https://github.com/dashea/requests-file(也可以通过 PyPI 获得)

“Requests-File 是与 Requests Python 库一起使用的传输适配器,允许通过 file:// URL 访问本地文件系统。”

这与 requests-html 的结合是纯粹的魔法:)

  • 亲爱的未来读者,这个答案非常精彩且简洁。但是,如果您在想要删除文件时发现自己遇到了“Win Errno 32”异常,请首先尝试通过“resp.raw.release_conn()”关闭文件句柄。 (2认同)

Woo*_*dog 10

packages/urllib3/poolmanager.py几乎解释了它.请求不支持本地URL.

pool_classes_by_scheme = {                                                        
    'http': HTTPConnectionPool,                                                   
    'https': HTTPSConnectionPool,                                              
}                                                                                 
Run Code Online (Sandbox Code Playgroud)

  • 这不是解决方案,只是它不起作用的理由。你能提供解决方案吗? (4认同)

Jas*_*mbs 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')
Run Code Online (Sandbox Code Playgroud)

然后,在测试设置或装饰测试功能的某个地方,我mock.patch用来修补请求的get函数:

@mock.patch('requests.get', local_get)
def test_handle_remote_file(self):
    ...
Run Code Online (Sandbox Code Playgroud)

这种技术有些脆弱 - 如果底层代码调用requests.request或构造Session并调用它,它就无济于事.可能有一种方法可以在较低级别修补请求以支持file:URL,但在我的初步调查中,似乎没有明显的钩点,所以我选择了这种更简单的方法.