m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

384 lines
14 KiB

6 months ago
  1. # -*- coding: utf-8 -*-
  2. """
  3. core
  4. ~~~~
  5. Core functionality shared between the extension and the decorator.
  6. :copyright: (c) 2016 by Cory Dolphin.
  7. :license: MIT, see LICENSE for more details.
  8. """
  9. import re
  10. import logging
  11. from collections.abc import Iterable
  12. from datetime import timedelta
  13. from flask import request, current_app
  14. from werkzeug.datastructures import Headers, MultiDict
  15. LOG = logging.getLogger(__name__)
  16. # Response Headers
  17. ACL_ORIGIN = 'Access-Control-Allow-Origin'
  18. ACL_METHODS = 'Access-Control-Allow-Methods'
  19. ACL_ALLOW_HEADERS = 'Access-Control-Allow-Headers'
  20. ACL_EXPOSE_HEADERS = 'Access-Control-Expose-Headers'
  21. ACL_CREDENTIALS = 'Access-Control-Allow-Credentials'
  22. ACL_MAX_AGE = 'Access-Control-Max-Age'
  23. ACL_RESPONSE_PRIVATE_NETWORK = 'Access-Control-Allow-Private-Network'
  24. # Request Header
  25. ACL_REQUEST_METHOD = 'Access-Control-Request-Method'
  26. ACL_REQUEST_HEADERS = 'Access-Control-Request-Headers'
  27. ACL_REQUEST_HEADER_PRIVATE_NETWORK = 'Access-Control-Request-Private-Network'
  28. ALL_METHODS = ['GET', 'HEAD', 'POST', 'OPTIONS', 'PUT', 'PATCH', 'DELETE']
  29. CONFIG_OPTIONS = ['CORS_ORIGINS', 'CORS_METHODS', 'CORS_ALLOW_HEADERS',
  30. 'CORS_EXPOSE_HEADERS', 'CORS_SUPPORTS_CREDENTIALS',
  31. 'CORS_MAX_AGE', 'CORS_SEND_WILDCARD',
  32. 'CORS_AUTOMATIC_OPTIONS', 'CORS_VARY_HEADER',
  33. 'CORS_RESOURCES', 'CORS_INTERCEPT_EXCEPTIONS',
  34. 'CORS_ALWAYS_SEND', 'CORS_ALLOW_PRIVATE_NETWORK']
  35. # Attribute added to request object by decorator to indicate that CORS
  36. # was evaluated, in case the decorator and extension are both applied
  37. # to a view.
  38. FLASK_CORS_EVALUATED = '_FLASK_CORS_EVALUATED'
  39. # Strange, but this gets the type of a compiled regex, which is otherwise not
  40. # exposed in a public API.
  41. RegexObject = type(re.compile(''))
  42. DEFAULT_OPTIONS = dict(origins='*',
  43. methods=ALL_METHODS,
  44. allow_headers='*',
  45. expose_headers=None,
  46. supports_credentials=False,
  47. max_age=None,
  48. send_wildcard=False,
  49. automatic_options=True,
  50. vary_header=True,
  51. resources=r'/*',
  52. intercept_exceptions=True,
  53. always_send=True,
  54. allow_private_network=False)
  55. def parse_resources(resources):
  56. if isinstance(resources, dict):
  57. # To make the API more consistent with the decorator, allow a
  58. # resource of '*', which is not actually a valid regexp.
  59. resources = [(re_fix(k), v) for k, v in resources.items()]
  60. # Sort by regex length to provide consistency of matching and
  61. # to provide a proxy for specificity of match. E.G. longer
  62. # regular expressions are tried first.
  63. def pattern_length(pair):
  64. maybe_regex, _ = pair
  65. return len(get_regexp_pattern(maybe_regex))
  66. return sorted(resources,
  67. key=pattern_length,
  68. reverse=True)
  69. elif isinstance(resources, str):
  70. return [(re_fix(resources), {})]
  71. elif isinstance(resources, Iterable):
  72. return [(re_fix(r), {}) for r in resources]
  73. # Type of compiled regex is not part of the public API. Test for this
  74. # at runtime.
  75. elif isinstance(resources, RegexObject):
  76. return [(re_fix(resources), {})]
  77. else:
  78. raise ValueError("Unexpected value for resources argument.")
  79. def get_regexp_pattern(regexp):
  80. """
  81. Helper that returns regexp pattern from given value.
  82. :param regexp: regular expression to stringify
  83. :type regexp: _sre.SRE_Pattern or str
  84. :returns: string representation of given regexp pattern
  85. :rtype: str
  86. """
  87. try:
  88. return regexp.pattern
  89. except AttributeError:
  90. return str(regexp)
  91. def get_cors_origins(options, request_origin):
  92. origins = options.get('origins')
  93. wildcard = r'.*' in origins
  94. # If the Origin header is not present terminate this set of steps.
  95. # The request is outside the scope of this specification.-- W3Spec
  96. if request_origin:
  97. LOG.debug("CORS request received with 'Origin' %s", request_origin)
  98. # If the allowed origins is an asterisk or 'wildcard', always match
  99. if wildcard and options.get('send_wildcard'):
  100. LOG.debug("Allowed origins are set to '*'. Sending wildcard CORS header.")
  101. return ['*']
  102. # If the value of the Origin header is a case-sensitive match
  103. # for any of the values in list of origins
  104. elif try_match_any(request_origin, origins):
  105. LOG.debug("The request's Origin header matches. Sending CORS headers.", )
  106. # Add a single Access-Control-Allow-Origin header, with either
  107. # the value of the Origin header or the string "*" as value.
  108. # -- W3Spec
  109. return [request_origin]
  110. else:
  111. LOG.debug("The request's Origin header does not match any of allowed origins.")
  112. return None
  113. elif options.get('always_send'):
  114. if wildcard:
  115. # If wildcard is in the origins, even if 'send_wildcard' is False,
  116. # simply send the wildcard. Unless supports_credentials is True,
  117. # since that is forbidded by the spec..
  118. # It is the most-likely to be correct thing to do (the only other
  119. # option is to return nothing, which almost certainly not what
  120. # the developer wants if the '*' origin was specified.
  121. if options.get('supports_credentials'):
  122. return None
  123. else:
  124. return ['*']
  125. else:
  126. # Return all origins that are not regexes.
  127. return sorted([o for o in origins if not probably_regex(o)])
  128. # Terminate these steps, return the original request untouched.
  129. else:
  130. LOG.debug("The request did not contain an 'Origin' header. This means the browser or client did not request CORS, ensure the Origin Header is set.")
  131. return None
  132. def get_allow_headers(options, acl_request_headers):
  133. if acl_request_headers:
  134. request_headers = [h.strip() for h in acl_request_headers.split(',')]
  135. # any header that matches in the allow_headers
  136. matching_headers = filter(
  137. lambda h: try_match_any(h, options.get('allow_headers')),
  138. request_headers
  139. )
  140. return ', '.join(sorted(matching_headers))
  141. return None
  142. def get_cors_headers(options, request_headers, request_method):
  143. origins_to_set = get_cors_origins(options, request_headers.get('Origin'))
  144. headers = MultiDict()
  145. if not origins_to_set: # CORS is not enabled for this route
  146. return headers
  147. for origin in origins_to_set:
  148. headers.add(ACL_ORIGIN, origin)
  149. headers[ACL_EXPOSE_HEADERS] = options.get('expose_headers')
  150. if options.get('supports_credentials'):
  151. headers[ACL_CREDENTIALS] = 'true' # case sensitive
  152. if ACL_REQUEST_HEADER_PRIVATE_NETWORK in request_headers \
  153. and request_headers.get(ACL_REQUEST_HEADER_PRIVATE_NETWORK) == 'true':
  154. allow_private_network = 'true' if options.get('allow_private_network') else 'false'
  155. headers[ACL_RESPONSE_PRIVATE_NETWORK] = allow_private_network
  156. # This is a preflight request
  157. # http://www.w3.org/TR/cors/#resource-preflight-requests
  158. if request_method == 'OPTIONS':
  159. acl_request_method = request_headers.get(ACL_REQUEST_METHOD, '').upper()
  160. # If there is no Access-Control-Request-Method header or if parsing
  161. # failed, do not set any additional headers
  162. if acl_request_method and acl_request_method in options.get('methods'):
  163. # If method is not a case-sensitive match for any of the values in
  164. # list of methods do not set any additional headers and terminate
  165. # this set of steps.
  166. headers[ACL_ALLOW_HEADERS] = get_allow_headers(options, request_headers.get(ACL_REQUEST_HEADERS))
  167. headers[ACL_MAX_AGE] = options.get('max_age')
  168. headers[ACL_METHODS] = options.get('methods')
  169. else:
  170. LOG.info("The request's Access-Control-Request-Method header does not match allowed methods. CORS headers will not be applied.")
  171. # http://www.w3.org/TR/cors/#resource-implementation
  172. if options.get('vary_header'):
  173. # Only set header if the origin returned will vary dynamically,
  174. # i.e. if we are not returning an asterisk, and there are multiple
  175. # origins that can be matched.
  176. if headers[ACL_ORIGIN] == '*':
  177. pass
  178. elif (len(options.get('origins')) > 1 or
  179. len(origins_to_set) > 1 or
  180. any(map(probably_regex, options.get('origins')))):
  181. headers.add('Vary', 'Origin')
  182. return MultiDict((k, v) for k, v in headers.items() if v)
  183. def set_cors_headers(resp, options):
  184. """
  185. Performs the actual evaluation of Flask-CORS options and actually
  186. modifies the response object.
  187. This function is used both in the decorator and the after_request
  188. callback
  189. """
  190. # If CORS has already been evaluated via the decorator, skip
  191. if hasattr(resp, FLASK_CORS_EVALUATED):
  192. LOG.debug('CORS have been already evaluated, skipping')
  193. return resp
  194. # Some libraries, like OAuthlib, set resp.headers to non Multidict
  195. # objects (Werkzeug Headers work as well). This is a problem because
  196. # headers allow repeated values.
  197. if (not isinstance(resp.headers, Headers)
  198. and not isinstance(resp.headers, MultiDict)):
  199. resp.headers = MultiDict(resp.headers)
  200. headers_to_set = get_cors_headers(options, request.headers, request.method)
  201. LOG.debug('Settings CORS headers: %s', str(headers_to_set))
  202. for k, v in headers_to_set.items():
  203. resp.headers.add(k, v)
  204. return resp
  205. def probably_regex(maybe_regex):
  206. if isinstance(maybe_regex, RegexObject):
  207. return True
  208. else:
  209. common_regex_chars = ['*', '\\', ']', '?', '$', '^', '[', ']', '(', ')']
  210. # Use common characters used in regular expressions as a proxy
  211. # for if this string is in fact a regex.
  212. return any((c in maybe_regex for c in common_regex_chars))
  213. def re_fix(reg):
  214. """
  215. Replace the invalid regex r'*' with the valid, wildcard regex r'/.*' to
  216. enable the CORS app extension to have a more user friendly api.
  217. """
  218. return r'.*' if reg == r'*' else reg
  219. def try_match_any(inst, patterns):
  220. return any(try_match(inst, pattern) for pattern in patterns)
  221. def try_match(request_origin, maybe_regex):
  222. """Safely attempts to match a pattern or string to a request origin."""
  223. if isinstance(maybe_regex, RegexObject):
  224. return re.match(maybe_regex, request_origin)
  225. elif probably_regex(maybe_regex):
  226. return re.match(maybe_regex, request_origin, flags=re.IGNORECASE)
  227. else:
  228. try:
  229. return request_origin.lower() == maybe_regex.lower()
  230. except AttributeError:
  231. return request_origin == maybe_regex
  232. def get_cors_options(appInstance, *dicts):
  233. """
  234. Compute CORS options for an application by combining the DEFAULT_OPTIONS,
  235. the app's configuration-specified options and any dictionaries passed. The
  236. last specified option wins.
  237. """
  238. options = DEFAULT_OPTIONS.copy()
  239. options.update(get_app_kwarg_dict(appInstance))
  240. if dicts:
  241. for d in dicts:
  242. options.update(d)
  243. return serialize_options(options)
  244. def get_app_kwarg_dict(appInstance=None):
  245. """Returns the dictionary of CORS specific app configurations."""
  246. app = (appInstance or current_app)
  247. # In order to support blueprints which do not have a config attribute
  248. app_config = getattr(app, 'config', {})
  249. return {
  250. k.lower().replace('cors_', ''): app_config.get(k)
  251. for k in CONFIG_OPTIONS
  252. if app_config.get(k) is not None
  253. }
  254. def flexible_str(obj):
  255. """
  256. A more flexible str function which intelligently handles stringifying
  257. strings, lists and other iterables. The results are lexographically sorted
  258. to ensure generated responses are consistent when iterables such as Set
  259. are used.
  260. """
  261. if obj is None:
  262. return None
  263. elif not isinstance(obj, str) and isinstance(obj, Iterable):
  264. return ", ".join(str(item) for item in sorted(obj))
  265. else:
  266. return str(obj)
  267. def serialize_option(options_dict, key, upper=False):
  268. if key in options_dict:
  269. value = flexible_str(options_dict[key])
  270. options_dict[key] = value.upper() if upper else value
  271. def ensure_iterable(inst):
  272. """
  273. Wraps scalars or string types as a list, or returns the iterable instance.
  274. """
  275. if isinstance(inst, str):
  276. return [inst]
  277. elif not isinstance(inst, Iterable):
  278. return [inst]
  279. else:
  280. return inst
  281. def sanitize_regex_param(param):
  282. return [re_fix(x) for x in ensure_iterable(param)]
  283. def serialize_options(opts):
  284. """
  285. A helper method to serialize and processes the options dictionary.
  286. """
  287. options = (opts or {}).copy()
  288. for key in opts.keys():
  289. if key not in DEFAULT_OPTIONS:
  290. LOG.warning("Unknown option passed to Flask-CORS: %s", key)
  291. # Ensure origins is a list of allowed origins with at least one entry.
  292. options['origins'] = sanitize_regex_param(options.get('origins'))
  293. options['allow_headers'] = sanitize_regex_param(options.get('allow_headers'))
  294. # This is expressly forbidden by the spec. Raise a value error so people
  295. # don't get burned in production.
  296. if r'.*' in options['origins'] and options['supports_credentials'] and options['send_wildcard']:
  297. raise ValueError("Cannot use supports_credentials in conjunction with"
  298. "an origin string of '*'. See: "
  299. "http://www.w3.org/TR/cors/#resource-requests")
  300. serialize_option(options, 'expose_headers')
  301. serialize_option(options, 'methods', upper=True)
  302. if isinstance(options.get('max_age'), timedelta):
  303. options['max_age'] = str(int(options['max_age'].total_seconds()))
  304. return options