Debian Codegraph @

rest_framework/settings.py

raw
1 """
2 Settings for REST framework are all namespaced in the REST_FRAMEWORK setting.
3 For example your project's `settings.py` file might look like this:
4
5 REST_FRAMEWORK = {
6 'DEFAULT_RENDERER_CLASSES': [
7 'rest_framework.renderers.JSONRenderer',
8 'rest_framework.renderers.TemplateHTMLRenderer',
9 ],
10 'DEFAULT_PARSER_CLASSES': [
11 'rest_framework.parsers.JSONParser',
12 'rest_framework.parsers.FormParser',
13 'rest_framework.parsers.MultiPartParser',
14 ],
15 }
16
17 This module provides the `api_setting` object, that is used to access
18 REST framework settings, checking for user settings first, then falling
19 back to the defaults.
20 """
21 from django.conf import settings
22 # Import from `django.core.signals` instead of the official location
23 # `django.test.signals` to avoid importing the test module unnecessarily.
24 from django.core.signals import setting_changed
25 from django.utils.module_loading import import_string
26
27 from rest_framework import DJANGO_DURATION_FORMAT, ISO_8601
28
29 DEFAULTS = {
30 # Base API policies
31 'DEFAULT_RENDERER_CLASSES': [
32 'rest_framework.renderers.JSONRenderer',
33 'rest_framework.renderers.BrowsableAPIRenderer',
34 ],
35 'DEFAULT_PARSER_CLASSES': [
36 'rest_framework.parsers.JSONParser',
37 'rest_framework.parsers.FormParser',
38 'rest_framework.parsers.MultiPartParser'
39 ],
40 'DEFAULT_AUTHENTICATION_CLASSES': [
41 'rest_framework.authentication.SessionAuthentication',
42 'rest_framework.authentication.BasicAuthentication'
43 ],
44 'DEFAULT_PERMISSION_CLASSES': [
45 'rest_framework.permissions.AllowAny',
46 ],
47 'DEFAULT_THROTTLE_CLASSES': [],
48 'DEFAULT_CONTENT_NEGOTIATION_CLASS': 'rest_framework.negotiation.DefaultContentNegotiation',
49 'DEFAULT_METADATA_CLASS': 'rest_framework.metadata.SimpleMetadata',
50 'DEFAULT_VERSIONING_CLASS': None,
51
52 # Generic view behavior
53 'DEFAULT_PAGINATION_CLASS': None,
54 'DEFAULT_FILTER_BACKENDS': [],
55
56 # Schema
57 'DEFAULT_SCHEMA_CLASS': 'rest_framework.schemas.openapi.AutoSchema',
58
59 # Throttling
60 'DEFAULT_THROTTLE_RATES': {
61 'user': None,
62 'anon': None,
63 },
64 'NUM_PROXIES': None,
65
66 # Pagination
67 'PAGE_SIZE': None,
68
69 # Filtering
70 'SEARCH_PARAM': 'search',
71 'ORDERING_PARAM': 'ordering',
72
73 # Versioning
74 'DEFAULT_VERSION': None,
75 'ALLOWED_VERSIONS': None,
76 'VERSION_PARAM': 'version',
77
78 # Authentication
79 'UNAUTHENTICATED_USER': 'django.contrib.auth.models.AnonymousUser',
80 'UNAUTHENTICATED_TOKEN': None,
81
82 # View configuration
83 'VIEW_NAME_FUNCTION': 'rest_framework.views.get_view_name',
84 'VIEW_DESCRIPTION_FUNCTION': 'rest_framework.views.get_view_description',
85
86 # Exception handling
87 'EXCEPTION_HANDLER': 'rest_framework.views.exception_handler',
88 'NON_FIELD_ERRORS_KEY': 'non_field_errors',
89 'LIST_SERIALIZER_ERRORS_AS_DICT': True,
90
91 # Testing
92 'TEST_REQUEST_RENDERER_CLASSES': [
93 'rest_framework.renderers.MultiPartRenderer',
94 'rest_framework.renderers.JSONRenderer'
95 ],
96 'TEST_REQUEST_DEFAULT_FORMAT': 'multipart',
97
98 # Hyperlink settings
99 'URL_FORMAT_OVERRIDE': 'format',
100 'FORMAT_SUFFIX_KWARG': 'format',
101 'URL_FIELD_NAME': 'url',
102
103 # Input and output formats
104 'DATE_FORMAT': ISO_8601,
105 'DATE_INPUT_FORMATS': [ISO_8601],
106
107 'DATETIME_FORMAT': ISO_8601,
108 'DATETIME_INPUT_FORMATS': [ISO_8601],
109
110 'TIME_FORMAT': ISO_8601,
111 'TIME_INPUT_FORMATS': [ISO_8601],
112
113 'DURATION_FORMAT': DJANGO_DURATION_FORMAT,
114
115 # Encoding
116 'UNICODE_JSON': True,
117 'COMPACT_JSON': True,
118 'STRICT_JSON': True,
119 'COERCE_DECIMAL_TO_STRING': True,
120 'COERCE_BIGINT_TO_STRING': False,
121 'UPLOADED_FILES_USE_URL': True,
122
123 # Browsable API
124 'HTML_SELECT_CUTOFF': 1000,
125 'HTML_SELECT_CUTOFF_TEXT': "More than {count} items...",
126
127 # Schemas
128 'SCHEMA_COERCE_PATH_PK': True,
129 'SCHEMA_COERCE_METHOD_NAMES': {
130 'retrieve': 'read',
131 'destroy': 'delete'
132 },
133 }
134
135
136 # List of settings that may be in string import notation.
137 IMPORT_STRINGS = [
138 'DEFAULT_RENDERER_CLASSES',
139 'DEFAULT_PARSER_CLASSES',
140 'DEFAULT_AUTHENTICATION_CLASSES',
141 'DEFAULT_PERMISSION_CLASSES',
142 'DEFAULT_THROTTLE_CLASSES',
143 'DEFAULT_CONTENT_NEGOTIATION_CLASS',
144 'DEFAULT_METADATA_CLASS',
145 'DEFAULT_VERSIONING_CLASS',
146 'DEFAULT_PAGINATION_CLASS',
147 'DEFAULT_FILTER_BACKENDS',
148 'DEFAULT_SCHEMA_CLASS',
149 'EXCEPTION_HANDLER',
150 'TEST_REQUEST_RENDERER_CLASSES',
151 'UNAUTHENTICATED_USER',
152 'UNAUTHENTICATED_TOKEN',
153 'VIEW_NAME_FUNCTION',
154 'VIEW_DESCRIPTION_FUNCTION'
155 ]
156
157
158 # List of settings that have been removed
159 REMOVED_SETTINGS = [
160 'PAGINATE_BY', 'PAGINATE_BY_PARAM', 'MAX_PAGINATE_BY',
161 ]
162
163
164 def perform_import(val, setting_name):
165 """
166 If the given setting is a string import notation,
167 then perform the necessary import or imports.
168 """
169 if val is None:
170 return None
171 elif isinstance(val, str):
172 return import_from_string(val, setting_name)
173 elif isinstance(val, (list, tuple)):
174 return [import_from_string(item, setting_name) for item in val]
175 return val
176
177
178 def import_from_string(val, setting_name):
179 """
180 Attempt to import a class from a string representation.
181 """
182 try:
183 return import_string(val)
184 except ImportError as e:
185 msg = "Could not import '%s' for API setting '%s'. %s: %s." % (val, setting_name, e.__class__.__name__, e)
186 raise ImportError(msg)
187
188
189 class APISettings:
190 """
191 A settings object that allows REST Framework settings to be accessed as
192 properties. For example:
193
194 from rest_framework.settings import api_settings
195 print(api_settings.DEFAULT_RENDERER_CLASSES)
196
197 Any setting with string import paths will be automatically resolved
198 and return the class, rather than the string literal.
199
200 Note:
201 This is an internal class that is only compatible with settings namespaced
202 under the REST_FRAMEWORK name. It is not intended to be used by 3rd-party
203 apps, and test helpers like `override_settings` may not work as expected.
204 """
205 def __init__(self, user_settings=None, defaults=None, import_strings=None):
206 if user_settings:
207 self._user_settings = self.__check_user_settings(user_settings)
208 self.defaults = defaults or DEFAULTS
209 self.import_strings = import_strings or IMPORT_STRINGS
210 self._cached_attrs = set()
211
212 @property
213 def user_settings(self):
214 if not hasattr(self, '_user_settings'):
215 self._user_settings = getattr(settings, 'REST_FRAMEWORK', {})
216 return self._user_settings
217
218 def __getattr__(self, attr):
219 if attr not in self.defaults:
220 raise AttributeError("Invalid API setting: '%s'" % attr)
221
222 try:
223 # Check if present in user settings
224 val = self.user_settings[attr]
225 except KeyError:
226 # Fall back to defaults
227 val = self.defaults[attr]
228
229 # Coerce import strings into classes
230 if attr in self.import_strings:
231 val = perform_import(val, attr)
232
233 # Cache the result
234 self._cached_attrs.add(attr)
235 setattr(self, attr, val)
236 return val
237
238 def __check_user_settings(self, user_settings):
239 SETTINGS_DOC = "https://www.django-rest-framework.org/api-guide/settings/"
240 for setting in REMOVED_SETTINGS:
241 if setting in user_settings:
242 raise RuntimeError("The '%s' setting has been removed. Please refer to '%s' for available settings." % (setting, SETTINGS_DOC))
243 return user_settings
244
245 def reload(self):
246 for attr in self._cached_attrs:
247 delattr(self, attr)
248 self._cached_attrs.clear()
249 if hasattr(self, '_user_settings'):
250 delattr(self, '_user_settings')
251
252
253 api_settings = APISettings(None, DEFAULTS, IMPORT_STRINGS)
254
255
256 def reload_api_settings(*args, **kwargs):
257 setting = kwargs['setting']
258 if setting == 'REST_FRAMEWORK':
259 api_settings.reload()
260
261
262 setting_changed.connect(reload_api_settings)