cl: add missing errors
[piglit.git] / framework / replay / local_file_adapter.py
blob770e445e359050f695bc412ef921b560727feb6a
1 import os
2 from urllib.request import url2pathname
4 import requests
7 class LocalFileAdapter(requests.adapters.BaseAdapter):
8 """Protocol Adapter to allow Requests to GET file:// URLs
9 """
11 @staticmethod
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"
21 return 200, "OK"
23 def send(self, req, **kwargs): # pylint: disable=unused-argument
24 """Return the file specified by the given request
26 @type req: C{PreparedRequest}
27 """
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":
33 try:
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")
42 else:
43 response.url = req.url
45 response.request = req
46 response.connection = self
48 return response
50 def close(self):
51 pass