url.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #
  2. # Copyright 2018-2022 Elyra Authors
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. from pathlib import Path
  17. from urllib.request import url2pathname
  18. from requests import Response
  19. from requests.adapters import BaseAdapter
  20. class FileTransportAdapter(BaseAdapter):
  21. """
  22. File Transport Adapter for the requests library. Use this
  23. adapter to enable the requests library to load a resource
  24. from the 'file' schema using HTTP 'GET'.
  25. """
  26. def send(self, req, **kwargs):
  27. """
  28. Return the file specified by the given request
  29. """
  30. response = Response()
  31. response.request = req
  32. response.connection = self
  33. if isinstance(req.url, bytes):
  34. response.url = req.url.decode("utf-8")
  35. else:
  36. response.url = req.url
  37. if req.method.lower() not in ["get"]:
  38. response.status_code = 405
  39. response.reason = "Method not allowed"
  40. return response
  41. p = Path(url2pathname(req.path_url))
  42. if p.is_dir():
  43. response.status_code = 400
  44. response.reason = "Not a file"
  45. return response
  46. elif not p.is_file():
  47. response.status_code = 404
  48. response.reason = "File not found"
  49. return response
  50. with open(p, "rb") as fh:
  51. response.status_code = 200
  52. response._content = fh.read()
  53. return response
  54. def close(self):
  55. pass