desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'test that \'where\' syntax with unknown \'$\' operator returns 400.'
def test_get_invalid_where_syntax(self):
(response, status) = self.get(self.known_resource, '?where={"field": {"$foo": "bar"}}') self.assert400(status)
'test that invalid sort syntax returns a 400'
def test_get_invalid_sort_syntax(self):
(response, status) = self.get(self.known_resource, '?sort=[("prog":1)]') self.assert400(status)
'test that supported operators are not considered invalid filters (#388). Also, test that nested filters are validated.'
def test_get_allowed_filters_operators(self):
where = '?where={"$and": [{"field1": "value1"}, {"field2": "value2"}]}' settings = self.app.config['DOMAIN'][self.known_resource] settings['allowed_filters'] = ['field1', 'field2'] (response, status) = self.get(self.known_resource, where) self.assert200(status) settings['allowed_filt...
'test that nested filter operators are working correctly.'
def test_get_nested_filter_operators_unvalidated(self):
where = ''.join(('?where={"$and":[{"$or":[{"fldA":"valA"},', '{"fldB":"valB"}]},{"fld2":"val2"}]}')) (response, status) = self.get(self.known_resource, where) self.assert200(status)
'test that nested filter operators are working correctly.'
def test_get_nested_filter_operators_validated(self):
self.app.config['VALIDATE_FILTERS'] = True where = ''.join(('?where={"$and":[{"$or":[{"fldA":"valA"},', '{"fldB":"valB"}]},{"fld2":"val2"}]}')) (response, status) = self.get(self.known_resource, where) self.assert400(status) where = ''.join(('?where={"$and":[{"$or":[{"role":', '["agent","client"]},{...
'test that checks all fields of the where clause to be valid resource fields according to the resource schema.'
def test_get_invalid_where_fields(self):
self.app.config['VALIDATE_FILTERS'] = True where = '?where={"$and": [{"bad_field": "val"}, {"fld2": "val2"}]}' (response, status) = self.get(self.known_resource, where) self.assert400(status) where = '?where={"prog": "stringValue"}' (response, status) = self.get(self.known_resourc...
'Documents created outside the API context could be lacking the LAST_UPDATED and/or DATE_CREATED fields.'
def test_getitem_missing_standard_date_fields(self):
contacts = self.random_contacts(1, False) ref = 'test_update_field' contacts[0]['ref'] = ref _db = self.connection[MONGO_DBNAME] _db.contacts.insert(contacts) (response, status) = self.get(self.known_resource, item=ref) self.assertItemResponse(response, status)
'Test that xml nodes are ordered and #441 is addressed.'
def test_xml_ordered_nodes(self):
r = self.test_client.get(('%s?max_results=1' % self.known_resource_url), headers=[('Accept', 'application/xml')]) data = r.get_data() idx1 = data.index('_created') idx2 = data.index('_etag') idx3 = data.index('_id') idx4 = data.index('_updated') self.assertTrue((idx1 < idx2 < idx3 < idx4)) ...
'Test that CORS is also supported at SCHEMA_ENDPOINT'
def test_CORS_OPTIONS_schema(self):
self.app.config['SCHEMA_ENDPOINT'] = 'schema' self.app._init_schema_endpoint() methods = ['GET', 'OPTIONS'] self.test_CORS_OPTIONS('schema', methods)
'Validate method to be invoked when performing an update, not an insert. :param document: the document to be validated. :param document_id: the unique id of the document. :param persisted_document: the persisted document to be updated.'
def validate_update(self, document, document_id, persisted_document=None):
self.document_id = document_id self.persisted_document = persisted_document return super(Validator, self).validate(document, update=True)
'Validation method to be invoked when performing a document replacement. This differs from :func:`validation_update` since in this case we want to perform a full :func:`validate` (the new document is to be considered a new insertion and required fields needs validation). However, like with validate_update, we also want...
def validate_replace(self, document, document_id, persisted_document=None):
self.document_id = document_id self.persisted_document = persisted_document return super(Validator, self).validate(document)
'{\'nullable\': True}'
def _normalize_default(self, mapping, schema, field):
if ((not self.persisted_document) or (field not in self.persisted_document)): super(Validator, self)._normalize_default(mapping, schema, field)
'{\'oneof\': [ {\'type\': \'callable\'}, {\'type\': \'string\'}'
def _normalize_default_setter(self, mapping, schema, field):
if ((not self.persisted_document) or (field not in self.persisted_document)): super(Validator, self)._normalize_default_setter(mapping, schema, field)
'{\'type\': [\'dict\', \'hashable\', \'hashables\']}'
def _validate_dependencies(self, dependencies, field, value):
persisted = self._filter_persisted_fields_not_in_document(dependencies) if persisted: dcopy = copy.copy(self.document) for field in persisted: dcopy[field] = self.persisted_document[field] validator = self._get_child_validator() validator.validate(dcopy, update=self.u...
'{\'type\': \'boolean\'}'
def _validate_readonly(self, read_only, field, value):
persisted_value = (self.persisted_document.get(field) if self.persisted_document else None) if (value != persisted_value): super(Validator, self)._validate_readonly(read_only, field, value)
'This function is called to check if a username / password combination is valid. Must be overridden with custom logic. :param username: username provided with current request. :param password: password provided with current request :param allowed_roles: allowed user roles. :param resource: resource being requested. :pa...
def check_auth(self, username, password, allowed_roles, resource, method):
raise NotImplementedError
'Returns a standard a 401 response that enables basic auth. Override if you want to change the response and/or the realm.'
def authenticate(self):
resp = Response(None, 401, {'WWW-Authenticate': ('Basic realm="%s"' % __package__)}) abort(401, description='Please provide proper credentials', response=resp)
'Validates the the current request is allowed to pass through. :param allowed_roles: allowed roles for the current request, can be a string or a list of roles. :param resource: resource being requested.'
def authorized(self, allowed_roles, resource, method):
auth = request.authorization if auth: self.set_user_or_token(auth.username) return (auth and self.check_auth(auth.username, auth.password, allowed_roles, resource, method))
'This function is called to check if a token is valid. Must be overridden with custom logic. :param userid: user id included with the request. :param hmac_hash: hash included with the request. :param headers: request headers. Suitable for hash computing. :param data: request data. Suitable for hash computing. :param al...
def check_auth(self, userid, hmac_hash, headers, data, allowed_roles, resource, method):
raise NotImplementedError
'Returns a standard a 401. Override if you want to change the response.'
def authenticate(self):
abort(401, description='Please provide proper credentials')
'Validates the the current request is allowed to pass through. :param allowed_roles: allowed roles for the current request, can be a string or a list of roles. :param resource: resource being requested.'
def authorized(self, allowed_roles, resource, method):
auth = request.headers.get('Authorization') try: (userid, hmac_hash) = auth.split(':') self.set_user_or_token(userid) except: auth = None return (auth and self.check_auth(userid, hmac_hash, request.headers, request.get_data(), allowed_roles, resource, method))
'This function is called to check if a token is valid. Must be overridden with custom logic. :param token: decoded user name. :param allowed_roles: allowed user roles :param resource: resource being requested. :param method: HTTP method being executed (POST, GET, etc.)'
def check_auth(self, token, allowed_roles, resource, method):
raise NotImplementedError
'Returns a standard a 401. Override if you want to change the response.'
def authenticate(self):
resp = Response(None, 401, {'WWW-Authenticate': ('Basic realm="%s"' % __package__)}) abort(401, description='Please provide proper credentials', response=resp)
'Validates the the current request is allowed to pass through. :param allowed_roles: allowed roles for the current request, can be a string or a list of roles. :param resource: resource being requested.'
def authorized(self, allowed_roles, resource, method):
auth = None if hasattr(request.authorization, 'username'): auth = request.authorization.username if ((not auth) and request.headers.get('Authorization')): auth = request.headers.get('Authorization').strip() if auth.lower().startswith(('token', 'bearer')): auth = auth.spli...
'Eve main WSGI app is implemented as a Flask subclass. Since we want to be able to launch our API by simply invoking Flask\'s run() method, we need to enhance our super-class a little bit.'
def __init__(self, import_name=__package__, settings='settings.py', validator=Validator, data=Mongo, auth=None, redis=None, url_converters=None, json_encoder=None, media=GridFSMediaStorage, **kwargs):
super(Eve, self).__init__(import_name, **kwargs) self.logger.addFilter(RequestFilter()) self.validator = validator self.settings = settings self.load_config() self.validate_domain_struct() self.url_map.converters['regex'] = RegexConverter if url_converters: self.url_map.converter...
'Pass our own subclass of :class:`werkzeug.serving.WSGIRequestHandler to Flask. :param host: the hostname to listen on. Set this to ``\'0.0.0.0\'`` to have the server available externally as well. Defaults to ``\'127.0.0.1\'``. :param port: the port of the webserver. Defaults to ``5000``. :param debug: if given, enable...
def run(self, host=None, port=None, debug=None, **options):
options.setdefault('request_handler', EveWSGIRequestHandler) super(Eve, self).run(host, port, debug, **options)
'API settings are loaded from standard python modules. First from `settings.py`(or alternative name/path passed as an argument) and then, when defined, from the file specified in the `EVE_SETTINGS` environment variable. Since we are a Flask subclass, any configuration value supported by Flask itself is available (besid...
def load_config(self):
self.config.from_object('eve.default_settings') if isinstance(self.settings, dict): self.config.update(self.settings) else: if os.path.isabs(self.settings): pyfile = self.settings else: def find_settings_file(file_name): abspath = os.path.abspa...
'Validates that Eve configuration settings conform to the requirements.'
def validate_domain_struct(self):
try: domain = self.config['DOMAIN'] except: raise ConfigException('DOMAIN dictionary missing or wrong.') if (not isinstance(domain, dict)): raise ConfigException('DOMAIN must be a dict.')
'Makes sure that REST methods expressed in the configuration settings are supported. .. versionchanged:: 0.2.0 Default supported methods are now class-level attributes. Resource validation delegated to _validate_resource_settings(). .. versionchanged:: 0.1.0 Support for PUT method. .. versionchanged:: 0.0.4 Support for...
def validate_config(self):
self.validate_methods(self.supported_resource_methods, self.config.get('RESOURCE_METHODS'), 'resource') self.validate_methods(self.supported_item_methods, self.config.get('ITEM_METHODS'), 'item') for (resource, settings) in self.config['DOMAIN'].items(): self._validate_resource_settings(resource, se...
'Validates one resource in configuration settings. :param resource: name of the resource which settings refer to. :param settings: settings of resource to be validated. .. versionchanged:: 0.4 validate that auth_field is not set to ID_FIELD. See #266. .. versionadded:: 0.2'
def _validate_resource_settings(self, resource, settings):
self.validate_methods(self.supported_resource_methods, settings['resource_methods'], ('[%s] resource ' % resource)) self.validate_methods(self.supported_item_methods, settings['item_methods'], ('[%s] item ' % resource)) if (('POST' in settings['resource_methods']) or ('PATCH' in settings['item_m...
'Validates that user role directives are syntactically and formally adequate. :param directive: either \'allowed_[read_|write_]roles\' or \'allow_item_[read_|write_]roles\'. :param candidate: the candidate setting to be validated. :param resource: name of the resource to which the candidate settings refer to. .. versio...
def validate_roles(self, directive, candidate, resource):
roles = candidate[directive] if (not isinstance(roles, list)): raise ConfigException(("'%s' must be list[%s]." % (directive, resource)))
'Compares allowed and proposed methods, raising a `ConfigException` when they don\'t match. :param allowed: a list of supported (allowed) methods. :param proposed: a list of proposed methods. :param item: name of the item to which the methods would be applied. Used when raising the exception.'
def validate_methods(self, allowed, proposed, item):
diff = (set(proposed) - set(allowed)) if diff: raise ConfigException(('Unallowed %s method(s): %s. Supported: %s' % (item, ', '.join(diff), ', '.join(allowed))))
'Validates a resource schema. :param resource: resource name. :param schema: schema definition for the resource. .. versionchanged:: 0.6.2 Do not allow \'$\' and \'.\' in root and dict field names. #780. .. versionchanged:: 0.6 ID_FIELD in the schema is not an offender anymore. .. versionchanged:: 0.5 Add ETAG to autom...
def validate_schema(self, resource, schema):
def validate_field_name(field): forbidden = ['$', '.'] if any(((x in field) for x in forbidden)): raise SchemaException(("Field '%s' cannot contain any of the following: '%s'." % (field, ', '.join(forbidden)))) resource_settings = self.config['DOMAIN'][reso...
'When not provided, fills individual resource settings with default or global configuration settings. .. versionchanged:: 0.4 `versioning` `VERSION` added to automatic projection (when applicable) .. versionchanged:: 0.2 Setting of actual resource defaults is delegated to _set_resource_defaults(). .. versionchanged:: 0...
def set_defaults(self):
for (resource, settings) in self.config['DOMAIN'].items(): self._set_resource_defaults(resource, settings)
'Low-level method which sets default values for one resource. .. versionchanged:: 0.6.2 Fix: startup crash when both SOFT_DELETE and ALLOW_UNKNOWN are True. (#722). .. versionchanged:: 0.6.1 Fix: inclusive projection defined for a datasource is ignored (#722). .. versionchanged:: 0.6 Support for \'mongo_indexes\'. .. v...
def _set_resource_defaults(self, resource, settings):
settings.setdefault('url', resource) settings.setdefault('resource_methods', self.config['RESOURCE_METHODS']) settings.setdefault('public_methods', self.config['PUBLIC_METHODS']) settings.setdefault('allowed_roles', self.config['ALLOWED_ROLES']) settings.setdefault('allowed_read_roles', self.config[...
'Set the default values for the resource \'datasource\' setting. .. versionadded:: 0.7'
def _set_resource_datasource(self, resource, schema, settings):
settings.setdefault('datasource', {}) ds = settings['datasource'] ds.setdefault('source', resource) ds.setdefault('filter', None) ds.setdefault('default_sort', None) self._set_resource_projection(ds, schema, settings) aggregation = ds.setdefault('aggregation', None) if aggregation: ...
'Set datasource projection for a resource .. versionchanged:: 0.6.3 Fix: If datasource source is specified no fields are included by default. Closes #842. .. versionadded:: 0.6.2'
def _set_resource_projection(self, ds, schema, settings):
projection = ds.get('projection', {}) exclusion = (any(((k, v) for (k, v) in projection.items() if (v == 0))) if projection else None) if ((not exclusion) and len(schema) and (settings['allow_unknown'] is False)): if (not projection): projection.update(dict(((field, 1) for field in schem...
'When not provided, fills individual schema settings with default or global configuration settings. :param schema: the resource schema to be initialized with default values .. versionchanged: 0.6 Add default ID_FIELD to the schema, so documents with an existing ID_FIELD can also be stored. .. versionchanged: 0.0.7 Sett...
def set_schema_defaults(self, schema, id_field):
schema.setdefault(id_field, {'type': 'objectid'}) for data_relation in list(extract_key_values('data_relation', schema)): data_relation.setdefault('field', id_field)
'Prefix to API endpoints. .. versionadded:: 0.2'
@property def api_prefix(self):
return api_prefix(self.config['URL_PREFIX'], self.config['API_VERSION'])
'Builds the API url map for one resource. Methods are enabled for each mapped endpoint, as configured in the settings. .. versionchanged:: 0.5 Don\'t add resource to url rules if it\'s flagged as internal. Strip regexes out of config.URLS helper. Closes #466. .. versionadded:: 0.2'
def _add_resource_url_rules(self, resource, settings):
self.config['SOURCES'][resource] = settings['datasource'] if settings['internal_resource']: return url = ('%s/%s' % (self.api_prefix, settings['url'])) pretty_url = settings['url'] if ('<' in pretty_url): pretty_url = (pretty_url[:(pretty_url.index('<') + 1)] + pretty_url[(pretty_url...
'Builds the API url map. Methods are enabled for each mapped endpoint, as configured in the settings. .. versionchanged:: 0.4 Renamed from \'_add_url_rules\' to \'_init_url_rules\' to make code more DRY. Individual resource rules get built from register_resource now. .. versionchanged:: 0.2 Delegate adding of resource ...
def _init_url_rules(self):
self.config['URLS'] = {} self.config['SOURCES'] = {} self.url_map.strict_slashes = False self.add_url_rule(('%s/' % self.api_prefix), 'home', view_func=home_endpoint, methods=['GET', 'OPTIONS'])
'Registers new resource to the domain. Under the hood this validates given settings, updates default values and adds necessary URL routes (builds api url map). If there exists some resource with given name, it is overwritten. :param resource: resource name. :param settings: settings for given resource. .. versionchange...
def register_resource(self, resource, settings):
self.config['DOMAIN'][resource] = settings self._set_resource_defaults(resource, settings) self._validate_resource_settings(resource, settings) self._add_resource_url_rules(resource, settings) if (settings['versioning'] is True): versioned_resource = (resource + self.config['VERSIONS']) ...
'Register custom error handlers so we make sure that all errors return a parseable body. .. versionchanged: 0.6.5 Replace obsolete app.register_error_handler_spec() with register_error_handler(), which works with Flask>=0.11.1. Closes #904, #945. .. versionadded:: 0.4'
def register_error_handlers(self):
for code in self.config['STANDARD_ERRORS']: self.register_error_handler(code, error_endpoint)
'If enabled, configures the OPLOG endpoint. .. versionchanged:: 0.7 Add \'u\' field to oplog audit schema. See #846. .. versionadded:: 0.5'
def _init_oplog(self):
(name, endpoint, audit, extra) = (self.config['OPLOG_NAME'], self.config['OPLOG_ENDPOINT'], self.config['OPLOG_AUDIT'], self.config['OPLOG_RETURN_EXTRA_FIELD']) settings = self.config['DOMAIN'].setdefault(name, {}) settings.setdefault('datasource', {'source': name}) settings['resource_methods'] = ['GET'...
'Configures the schema endpoint if set in configuration.'
def _init_schema_endpoint(self):
endpoint = self.config['SCHEMA_ENDPOINT'] if endpoint: schema_url = ('%s/%s' % (self.api_prefix, endpoint)) self.add_url_rule(schema_url, 'schema_collection', view_func=schema_collection_endpoint, methods=['GET', 'OPTIONS']) self.add_url_rule((schema_url + '/<resource>'), 'schema_item', ...
'If HTTP_X_METHOD_OVERRIDE is included with the request and method override is allowed, make sure the override method is returned to Eve as the request method, so normal routing and method validation can be performed.'
def __call__(self, environ, start_response):
if self.config['ALLOW_OVERRIDE_HTTP_METHOD']: environ['REQUEST_METHOD'] = environ.get('HTTP_X_HTTP_METHOD_OVERRIDE', environ['REQUEST_METHOD']).upper() return super(Eve, self).__call__(environ, start_response)
'Return the graph as a nested list.'
def nested(self, format_callback=None):
seen = set() roots = [] for root in self.edges.get(None, ()): roots.extend(self._nested(root, seen, format_callback)) return roots
'Returns a Form class for use in the admin add view. This is used by add_view and change_view.'
@filter_hook def get_model_form(self, **kwargs):
if (self.exclude is None): exclude = [] else: exclude = list(self.exclude) if ((self.exclude is None) and hasattr(self.form, '_meta') and self.form._meta.exclude): exclude.extend(self.form._meta.exclude) exclude = (exclude or None) defaults = {'form': self.form, 'fields': ((s...
'Send a message to the user. The default implementation posts a message using the django.contrib.messages backend.'
def message_user(self, message, level='info'):
if (hasattr(messages, level) and callable(getattr(messages, level))): getattr(messages, level)(self.request, message)
'Get model object instance by object_id, used for change admin view'
@filter_hook def get_object(self, object_id):
queryset = self.queryset() model = queryset.model try: object_id = model._meta.pk.to_python(object_id) return queryset.get(pk=object_id) except (model.DoesNotExist, ValidationError): return None
'Returns a dict of all perms for this model. This dict has the keys ``add``, ``change``, and ``delete`` mapping to the True/False for each of those actions.'
def get_model_perms(self):
return {'view': self.has_view_permission(), 'add': self.has_add_permission(), 'change': self.has_change_permission(), 'delete': self.has_delete_permission()}
'Hook for specifying field ordering.'
def get_ordering(self):
return (self.ordering or ())
'Returns a QuerySet of all model instances that can be edited by the admin site. This is used by changelist_view.'
@filter_hook def queryset(self):
return self.model._default_manager.get_queryset()
'The \'delete\' admin view for this model.'
def init_request(self, object_id, *args, **kwargs):
self.obj = self.get_object(unquote(object_id)) if (not self.has_delete_permission(self.obj)): raise PermissionDenied if (self.obj is None): raise Http404((_('%(name)s object with primary key %(key)r does not exist.') % {'name': force_text(self.opts.verbose_name), 'key...
'Given a model instance delete it from the database.'
@filter_hook def delete_model(self):
self.log('delete', '', self.obj) self.obj.delete()
'Return a sequence containing the fields to be displayed on the list.'
@filter_hook def get_list_display(self):
self.base_list_display = (((COL_LIST_VAR in self.request.GET) and (self.request.GET[COL_LIST_VAR] != '') and self.request.GET[COL_LIST_VAR].split('.')) or self.list_display) return list(self.base_list_display)
'Return a sequence containing the fields to be displayed as links on the changelist. The list_display parameter is the list of fields returned by get_list_display().'
@filter_hook def get_list_display_links(self):
if (self.list_display_links or (not self.list_display)): return self.list_display_links else: return list(self.list_display)[:1]
'Get model queryset. The query has been filted and ordered.'
@filter_hook def get_list_queryset(self):
queryset = self.queryset() if (not queryset.query.select_related): if self.list_select_related: queryset = queryset.select_related() elif (self.list_select_related is None): related_fields = [] for field_name in self.list_display: try: ...
'Returns the proper model field name corresponding to the given field_name to use for ordering. field_name may either be the name of a proper model field or the name of a method (on the admin or model) or a callable with the \'admin_order_field\' attribute. Returns None if no proper model field name can be matched.'
@filter_hook def get_ordering_field(self, field_name):
try: field = self.opts.get_field(field_name) return field.name except models.FieldDoesNotExist: if callable(field_name): attr = field_name elif hasattr(self, field_name): attr = getattr(self, field_name) else: attr = getattr(self.model,...
'Returns the list of ordering fields for the change list. First we check the get_ordering() method in model admin, then we check the object\'s default ordering. Then, any manually-specified ordering from the query string overrides anything. Finally, a deterministic order is guaranteed by ensuring the primary key is use...
@filter_hook def get_ordering(self):
ordering = list((super(ListAdminView, self).get_ordering() or self._get_default_ordering())) if ((ORDER_VAR in self.params) and self.params[ORDER_VAR]): ordering = [(pfx + self.get_ordering_field(field_name)) for (n, pfx, field_name) in map((lambda p: p.rpartition('-')), self.params[ORDER_VAR].split('.'...
'Returns a OrderedDict of ordering field column numbers and asc/desc'
@filter_hook def get_ordering_field_columns(self):
ordering = self._get_default_ordering() ordering_fields = OrderedDict() if ((ORDER_VAR not in self.params) or (not self.params[ORDER_VAR])): for field in ordering: if field.startswith('-'): field = field[1:] order_type = 'desc' else: ...
'Return the select column menu items link. We must use base_list_display, because list_display maybe changed by plugins.'
def get_check_field_url(self, f):
fields = [fd for fd in self.base_list_display if (fd != f.name)] if (len(self.base_list_display) == len(fields)): if f.primary_key: fields.insert(0, f.name) else: fields.append(f.name) return self.get_query_string({COL_LIST_VAR: '.'.join(fields)})
'Return the fields info defined in model. use FakeMethodField class wrap method as a db field.'
def get_model_method_fields(self):
methods = [] for name in dir(self): try: if getattr(getattr(self, name), 'is_column', False): methods.append((name, getattr(self, name))) except: pass return [FakeMethodField(name, getattr(method, 'short_description', capfirst(name.replace('_', ' ')...
'Prepare the context for templates.'
@filter_hook def get_context(self):
self.title = (_('%s List') % force_text(self.opts.verbose_name)) model_fields = [(f, (f.name in self.list_display), self.get_check_field_url(f)) for f in (list(self.opts.fields) + self.get_model_method_fields()) if (f.name not in self.list_exclude)] new_context = {'model_name': force_text(self.opts.verbo...
'The \'change list\' admin view for this model.'
@csrf_protect_m @filter_hook def get(self, request, *args, **kwargs):
response = self.get_result_list() if response: return response context = self.get_context() context.update((kwargs or {})) response = self.get_response(context, *args, **kwargs) return (response or TemplateResponse(request, (self.object_list_template or self.get_template_list('views/mode...
'Generates the list column headers.'
@filter_hook def result_headers(self):
row = ResultRow() row['num_sorted_fields'] = 0 row.cells = [self.result_header(field_name, row) for field_name in self.list_display] return row
'Generates the actual list of data.'
@filter_hook def result_item(self, obj, field_name, row):
item = ResultItem(field_name, row) try: (f, attr, value) = lookup_field(field_name, obj, self) except (AttributeError, ObjectDoesNotExist, NoReverseMatch): item.text = mark_safe(("<span class='text-muted'>%s</span>" % EMPTY_CHANGELIST_VALUE)) else: if (f is None): ...
'Generates the series of links to the pages in a paginated list.'
@inclusion_tag('xadmin/includes/pagination.html') def block_pagination(self, context, nodes, page_type='normal'):
(paginator, page_num) = (self.paginator, self.page_num) pagination_required = (((not self.show_all) or (not self.can_show_all)) and self.multi_page) if (not pagination_required): page_range = [] else: ON_EACH_SIDE = {'normal': 5, 'small': 3}.get(page_type, 3) ON_ENDS = 2 ...
'Returns a Form class for use in the admin add view. This is used by add_view and change_view.'
@filter_hook def get_model_form(self, **kwargs):
if (self.exclude is None): exclude = [] else: exclude = list(self.exclude) exclude.extend(self.get_readonly_fields()) if ((self.exclude is None) and hasattr(self.form, '_meta') and self.form._meta.exclude): exclude.extend(self.form._meta.exclude) exclude = (exclude or None) ...
'Hook for specifying custom readonly fields.'
@filter_hook def get_readonly_fields(self):
return self.readonly_fields
'Determines the HttpResponse for the add_view stage.'
@filter_hook def post_response(self):
request = self.request msg = (_('The %(name)s "%(obj)s" was added successfully.') % {'name': force_text(self.opts.verbose_name), 'obj': ("<a class='alert-link' href='%s'>%s</a>" % (self.model_admin_url('change', self.new_obj._get_pk_val()), force_text(self.new_obj)))}) if ('_continue' i...
'Determines the HttpResponse for the change_view stage.'
@filter_hook def post_response(self):
opts = self.new_obj._meta obj = self.new_obj request = self.request verbose_name = opts.verbose_name pk_value = obj._get_pk_val() msg = (_('The %(name)s "%(obj)s" was changed successfully.') % {'name': force_text(verbose_name), 'obj': force_text(obj)}) if ('_continue' in reque...
'Returns the edited object represented by this log entry'
def get_edited_object(self):
return self.content_type.get_object_for_this_type(pk=self.object_id)
'Unregisters the given model(s). If a model isn\'t already registered, this will raise NotRegistered.'
def unregister(self, model_or_iterable):
from xadmin.views.base import BaseAdminView if isinstance(model_or_iterable, (ModelBase, BaseAdminView)): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if isinstance(model, ModelBase): if (model not in self._registry): raise NotRegistered...
'Returns True if the given HttpRequest has permission to view *at least one* page in the admin site.'
def has_permission(self, request):
return (request.user.is_active and request.user.is_staff)
'Check that all things needed to run the admin have been correctly installed. The default implementation checks that LogEntry, ContentType and the auth context processor are installed.'
def check_dependencies(self):
from django.contrib.contenttypes.models import ContentType if (not ContentType._meta.installed): raise ImproperlyConfigured("Put 'django.contrib.contenttypes' in your INSTALLED_APPS setting in order to use the admin application.") default_template_engine = Engine....
'Decorator to create an admin view attached to this ``AdminSite``. This wraps the view and provides permission checking by calling ``self.has_permission``. You\'ll want to use this from within ``AdminSite.get_urls()``: class MyAdminSite(AdminSite): def get_urls(self): from django.conf.urls import url urls = super(MyAdm...
def admin_view(self, view, cacheable=False):
def inner(request, *args, **kwargs): if ((not self.has_permission(request)) and getattr(view, 'need_site_permission', True)): return self.create_admin_view(self.login_view)(request, *args, **kwargs) return view(request, *args, **kwargs) if (not cacheable): inner = never_cache...
'Displays the i18n JavaScript that the Django admin requires. This takes into account the USE_I18N setting. If it\'s set to False, the generated JavaScript will be leaner and faster.'
def i18n_javascript(self, request):
if settings.USE_I18N: from django.views.i18n import javascript_catalog else: from django.views.i18n import null_javascript_catalog as javascript_catalog return javascript_catalog(request, packages=['django.conf', 'xadmin'])
'Returns True if some choices would be output for this filter.'
def has_output(self):
raise NotImplementedError
'Returns the filtered queryset.'
def do_filte(self, queryset):
raise NotImplementedError
'Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset cleaned_data dictionaries.'
def get_all_cleaned_data(self):
cleaned_data = {} for (form_key, attrs) in self.get_form_list().items(): form_obj = self.get_step_form_obj(form_key) if form_obj.is_valid(): if ((type(attrs) is dict) and ('convert' in attrs)): callback = attrs['convert'] if callable(callback): ...
'Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn\'t validate, None will be returned.'
def get_cleaned_data_for_step(self, step):
if (step in self.get_form_list()): form_obj = self.get_step_form_obj(step) if form_obj.is_valid(): return form_obj.cleaned_data return None
'Returns the next step after the given `step`. If no more steps are available, None will be returned. If the `step` argument is None, the current step will be determined automatically.'
def get_next_step(self, step=None):
if (step is None): step = self.steps.current obj = self.get_form_list().keys() if six.PY3: obj = [s for s in obj] key = (obj.index(step) + 1) if (len(obj) > key): return obj[key] return None
'Returns the previous step before the given `step`. If there are no steps available, None will be returned. If the `step` argument is None, the current step will be determined automatically.'
def get_prev_step(self, step=None):
if (step is None): step = self.steps.current obj = self.get_form_list().keys() if six.PY3: obj = [s for s in obj] key = (obj.index(step) - 1) if (key >= 0): return obj[key] return None
'Returns the index for the given `step` name. If no step is given, the current step will be used to get the index.'
def get_step_index(self, step=None):
if (step is None): step = self.steps.current obj = self.get_form_list().keys() if six.PY3: obj = [s for s in obj] return obj.index(step)
'Returns a list of related fields (also many to many) :param local_only: :param include_hidden: :return: list'
def _get_all_related_objects(self, local_only=False, include_hidden=False, include_proxy_eq=False):
include_parents = (True if (local_only is False) else PROXY_PARENTS) fields = self.opts._get_fields(forward=False, reverse=True, include_parents=include_parents, include_hidden=include_hidden) if include_proxy_eq: children = chain.from_iterable((c._relation_tree for c in self.opts.concrete_model._me...
'Flag, approve, or remove some comments from an admin action. Actually calls the `action` argument to perform the heavy lifting.'
def _bulk_flag(self, queryset, action, done_message):
n_comments = 0 for comment in queryset: action(self.request, comment) n_comments += 1 msg = ungettext('1 comment was successfully %(action)s.', '%(count)s comments were successfully %(action)s.', n_comments) self.message_user((msg % {'count': n_comments, 'action':...
'Helper function for building an attribute dictionary.'
def build_attrs(self, extra_attrs=None, **kwargs):
self.attrs = self.widget.build_attrs(extra_attrs=None, **kwargs) return self.attrs
'Applies the correct ordering to the given version queryset.'
def _order_version_queryset(self, queryset):
if self.history_latest_first: return queryset.order_by('-pk') return queryset.order_by('pk')
'Applies the correct ordering to the given version queryset.'
def _reversion_order_version_queryset(self, queryset):
if (not self.history_latest_first): queryset = queryset.order_by('pk') return queryset
'Retreives all the related Version objects for the given FormSet.'
def get_related_versions(self, obj, version, formset):
object_id = obj.pk try: fk_name = ((formset.fk.name + '_') + formset.fk.rel.get_related_field().name) except AttributeError: fk_name = formset.ct_fk_field.name revision_versions = version.revision.version_set.all() related_versions = dict([(related_version.object_id, related_version)...
'Hacks the given formset to contain the correct initial data.'
def _hack_inline_formset_initial(self, revision_view, formset):
initial = [] related_versions = self.get_related_versions(revision_view.org_obj, revision_view.version, formset) formset.related_versions = related_versions for related_obj in formset.queryset: if (smart_text(related_obj.pk) in related_versions): initial.append(related_versions.pop(s...
'Helper function for building an attribute dictionary.'
def build_attrs(self, extra_attrs=None, **kwargs):
self.attrs = self.widget.build_attrs(extra_attrs=None, **kwargs) return self.attrs
'Returns a BaseInlineFormSet class for use in admin add/change views.'
@filter_hook def get_formset(self, **kwargs):
if (self.exclude is None): exclude = [] else: exclude = list(self.exclude) exclude.extend(self.get_readonly_fields()) if ((self.exclude is None) and hasattr(self.form, '_meta') and self.form._meta.exclude): exclude.extend(self.form._meta.exclude) exclude = (exclude or None) ...
'Return a list of choices for use in a form object. Each choice is a tuple (name, description).'
def get_action_choices(self):
choices = [] for (ac, name, description, icon) in self.actions.values(): choice = (name, (description % model_format_dict(self.opts)), icon) choices.append(choice) return choices
'cookielib has no legitimate use for this method; add it back if you find one.'
def add_header(self, key, val):
raise NotImplementedError('Cookie headers should be added with add_unredirected_header()')
'Make a MockResponse for `cookielib` to read. :param headers: a httplib.HTTPMessage or analogous carrying the headers'
def __init__(self, headers):
self._headers = headers
'Dict-like get() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains. .. warning:: operation is O(n), not O(1).'
def get(self, name, default=None, domain=None, path=None):
try: return self._find_no_duplicates(name, domain, path) except KeyError: return default
'Dict-like set() that also supports optional domain and path args in order to resolve naming collisions from using one cookie jar over multiple domains.'
def set(self, name, value, **kwargs):
if (value is None): remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path')) return if isinstance(value, Morsel): c = morsel_to_cookie(value) else: c = create_cookie(name, value, **kwargs) self.set_cookie(c) return c
'Dict-like iterkeys() that returns an iterator of names of cookies from the jar. See itervalues() and iteritems().'
def iterkeys(self):
for cookie in iter(self): (yield cookie.name)