Fetch a file from a local url with Python requests?

后端 未结 6 1246
误落风尘
误落风尘 2020-12-02 14:29

I am using Python\'s requests library in one method of my application. The body of the method looks like this:

def handle_remote_file(url, **kwargs):
    res         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-02 15:15

    As @WooParadog explained requests library doesn't know how to handle local files. Although, current version allows to define transport adapters.

    Therefore you can simply define you own adapter which will be able to handle local files, e.g.:

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

    I'm using requests-testadapter module in the above example.

提交回复
热议问题