2 from urllib
.request
import url2pathname
7 class LocalFileAdapter(requests
.adapters
.BaseAdapter
):
8 """Protocol Adapter to allow Requests to GET file:// URLs
12 def _chkpath(_
, path
):
13 """Return an HTTP status for the given filesystem path."""
14 if os
.path
.isdir(path
):
15 return 400, "Path Not A File"
16 if not os
.path
.isfile(path
):
17 return 404, "File Not Found"
18 if not os
.access(path
, os
.R_OK
):
19 return 403, "Access Denied"
23 def send(self
, req
, **kwargs
): # pylint: disable=unused-argument
24 """Return the file specified by the given request
26 @type req: C{PreparedRequest}
28 path
= os
.path
.normcase(os
.path
.normpath(url2pathname(req
.path_url
)))
29 response
= requests
.Response()
31 response
.status_code
, response
.reason
= self
._chkpath
(req
.method
, path
)
32 if response
.status_code
== 200 and req
.method
.lower() != "head":
34 response
.raw
= open(path
, "rb")
35 response
.raw
.release_conn
= response
.raw
.close
36 except (OSError, IOError) as err
:
37 response
.status_code
= 500
38 response
.reason
= str(err
)
40 if isinstance(req
.url
, bytes
):
41 response
.url
= req
.url
.decode("utf-8")
43 response
.url
= req
.url
45 response
.request
= req
46 response
.connection
= self