cors.py 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. # -*- coding: utf-8 -*-
  2. # INFO - G.M -17-05-2018 - CORS support
  3. # original code from https://gist.github.com/mmerickel/1afaf64154b335b596e4
  4. # see also
  5. # here : https://groups.google.com/forum/#!topic/pylons-discuss/2Sw4OkOnZcE
  6. from pyramid.events import NewResponse
  7. def add_cors_support(config):
  8. # INFO - G.M - 17-05-2018 - CORS Preflight stuff (special requests)
  9. config.add_directive(
  10. 'add_cors_preflight_handler',
  11. add_cors_preflight_handler
  12. )
  13. config.add_route_predicate('cors_preflight', CorsPreflightPredicate)
  14. # INFO - G.M - 17-05-2018 CORS Headers for all responses
  15. config.add_subscriber(add_cors_to_response, NewResponse)
  16. class CorsPreflightPredicate(object):
  17. def __init__(self, val, config):
  18. self.val = val
  19. def text(self):
  20. return 'cors_preflight = %s' % bool(self.val)
  21. phash = text
  22. def __call__(self, context, request):
  23. if not self.val:
  24. return False
  25. return (
  26. request.method == 'OPTIONS' and
  27. 'Origin' in request.headers and
  28. 'Access-Control-Request-Method' in request.headers
  29. )
  30. def add_cors_preflight_handler(config):
  31. # INFO - G.M - 17-05-2018 - Add route for CORS preflight
  32. # see https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request
  33. # for more info about preflight
  34. config.add_route(
  35. 'cors-options-preflight', '/{catch_all:.*}',
  36. cors_preflight=True,
  37. )
  38. config.add_view(
  39. cors_options_view,
  40. route_name='cors-options-preflight',
  41. )
  42. def cors_options_view(context, request):
  43. response = request.response
  44. if 'Access-Control-Request-Headers' in request.headers:
  45. response.headers['Access-Control-Allow-Methods'] = (
  46. 'OPTIONS,HEAD,GET,POST,PUT,DELETE'
  47. )
  48. response.headers['Access-Control-Allow-Headers'] = (
  49. 'Content-Type,Accept,Accept-Language,Authorization,X-Request-ID'
  50. )
  51. return response
  52. def add_cors_to_response(event):
  53. # INFO - G.M - 17-05-2018 - Add some CORS headers to all requests
  54. request = event.request
  55. response = event.response
  56. if 'Origin' in request.headers:
  57. response.headers['Access-Control-Expose-Headers'] = (
  58. 'Content-Type,Date,Content-Length,Authorization,X-Request-ID'
  59. )
  60. # TODO - G.M - 17-05-2018 - Allow to configure this header in config
  61. response.headers['Access-Control-Allow-Origin'] = '*'
  62. response.headers['Access-Control-Allow-Credentials'] = 'true'