| 1 | import collections |
| 2 | |
| 3 | from .preflight_handler import _PreflightHandler |
| 4 | |
| 5 | |
| 6 | def custom_cors(config): |
| 7 | def wrapper(function): |
| 8 | name = f"{function.__name__}_cors_config" |
| 9 | setattr(function, name, config) |
| 10 | return function |
| 11 | |
| 12 | return wrapper |
| 13 | |
| 14 | |
| 15 | class CorsViewMixin(_PreflightHandler): |
| 16 | cors_config = None |
| 17 | |
| 18 | @classmethod |
| 19 | def get_request_config(cls, request, request_method): |
| 20 | try: |
| 21 | from . import APP_CONFIG_KEY |
| 22 | |
| 23 | cors = request.app[APP_CONFIG_KEY] |
| 24 | except KeyError: |
| 25 | raise ValueError("aiohttp-cors is not configured.") |
| 26 | |
| 27 | method = getattr(cls, request_method.lower(), None) |
| 28 | |
| 29 | if not method: |
| 30 | raise KeyError() |
| 31 | |
| 32 | config_property_key = f"{request_method.lower()}_cors_config" |
| 33 | |
| 34 | custom_config = getattr(method, config_property_key, None) |
| 35 | if not custom_config: |
| 36 | custom_config = {} |
| 37 | |
| 38 | class_config = cls.cors_config |
| 39 | if not class_config: |
| 40 | class_config = {} |
| 41 | |
| 42 | return collections.ChainMap(custom_config, class_config, cors.defaults) |
| 43 | |
| 44 | async def _get_config(self, request, origin, request_method): |
| 45 | return self.get_request_config(request, request_method) |
| 46 | |
| 47 | async def options(self): |
| 48 | response = await self._preflight_handler(self.request) |
| 49 | return response |