apis_core.generic package

Subpackages

Submodules

apis_core.generic.abc module

class apis_core.generic.abc.GenericModel[source]

Bases: object

get_absolute_url()[source]
classmethod get_add_permission()[source]
get_api_detail_endpoint()[source]
classmethod get_change_permission()[source]
get_create_success_url()[source]
classmethod get_createview_url()[source]
classmethod get_delete_permission()[source]
get_delete_url()[source]
get_edit_url()[source]
get_enrich_url()[source]
get_field_value_after_merge(other, field)[source]

This method finds the value of a field after merging other into self. It first tries to find a merge method that is specific to that field (merge_{fieldname}) and then tries to find a method that is specific to the type of the field (merge_{fieldtype}) If neither of those exist, it uses the others field value if the field in self is not set, otherwise it keeps the value in self.

classmethod get_importview_url()[source]
classmethod get_listview_url()[source]
get_merge_booleanfield(other: BooleanField, field: BooleanField)[source]
get_merge_charfield_value(other: CharField, field: CharField)[source]
get_merge_textfield_value(other: TextField, field: TextField)[source]
get_merge_url(other_id)[source]
get_update_success_url()[source]
merge_fields(other)[source]

This method iterates through the model fields and uses the get_field_value_after_merge method to copy values from other to self. It is called by the merge_with method.

apis_core.generic.api_views module

class apis_core.generic.api_views.ModelViewSet(**kwargs)[source]

Bases: ModelViewSet

API ViewSet for a generic model. The queryset is overridden by the first match from the first_member_match helper. The serializer class is overridden by the first match from the first_member_match helper.

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

basename = None
description = None
detail = None
dispatch(*args, **kwargs)[source]

.dispatch() is pretty much the same as Django’s regular dispatch, but with extra hooks for startup, finalize, and exception handling.

filter_backends = [<class 'apis_core.generic.filterbackends.GenericFilterBackend'>]
get_queryset()[source]

Get the list of items for this view. This must be an iterable, and may be a queryset. Defaults to using self.queryset.

This method should always be used rather than accessing self.queryset directly, as self.queryset gets evaluated only once, and those results are cached for all subsequent requests.

You may want to override this if you need to provide different querysets depending on the incoming request.

(Eg. return a list of items that is specific to the user)

get_serializer_class()[source]

Return the class to use for the serializer. Defaults to using self.serializer_class.

You may want to override this if you need to provide different serializations depending on the incoming request.

(Eg. admins get full serialization, others get basic serialization)

name = None
suffix = None

apis_core.generic.filterbackends module

class apis_core.generic.filterbackends.GenericFilterBackend[source]

Bases: DjangoFilterBackend

get_filterset_class(view, queryset=None)[source]

Return the FilterSet class used to filter the queryset.

apis_core.generic.filtersets module

class apis_core.generic.filtersets.GenericFilterSet(data=None, queryset=None, *, request=None, prefix=None)[source]

Bases: FilterSet

Our GenericFilterSet sets the default form to be our GenericFilterSetForm, which is set up to ignore the columns field of the form.

class Meta[source]

Bases: object

form

alias of GenericFilterSetForm

base_filters = {}
declared_filters = {}

apis_core.generic.generators module

class apis_core.generic.generators.CustomEndpointEnumerator(patterns=None, urlconf=None)[source]

Bases: EndpointEnumerator

get_api_endpoints(patterns=None, prefix='')[source]

Call the EndpointEnumerator’s get_api_endpoints method to get all the automatically found endpoints, remove the ones that we want to override and the add our custom endpoints to this list.

class apis_core.generic.generators.CustomSchemaGenerator(*args, **kwargs)[source]

Bases: SchemaGenerator

endpoint_inspector_cls

alias of CustomEndpointEnumerator

apis_core.generic.helpers module

apis_core.generic.helpers.default_search_fields(model, field_names=None)[source]

Retrieve the default model fields to use for a search operation By default those are all the CharFields and TextFields of a model. It is also possible to define those fields on the model using the _default_search_fields attribute. The method also takes a field_names argument to override the list of fields.

apis_core.generic.helpers.first_member_match(dotted_path_list: tuple[str], fallback=None) object[source]
apis_core.generic.helpers.generate_search_filter(model, query, fields_to_search=None, prefix='')[source]

Generate a default search filter that searches for the query This helper can be used by autocomplete querysets if nothing fancier is needed. If the prefix is set, the field names will be prefixed with that string - this can be useful if you want to use the generate_search_filter in a Q combined query while searching over multiple models.

apis_core.generic.helpers.import_string(dotted_path)[source]
apis_core.generic.helpers.makeclassprefix(string: str) str[source]
apis_core.generic.helpers.module_paths(model, path: str = '', suffix: str = '') list[source]
apis_core.generic.helpers.mro_paths(model)[source]

Create a list of MRO classes for a Django model

apis_core.generic.helpers.permission_fullname(action: str, model: object) str[source]
apis_core.generic.helpers.template_names_via_mro(model, suffix='')[source]

Use the MRO to generate a list of template names for a model

apis_core.generic.importers module

class apis_core.generic.importers.GenericModelImporter(uri, model)[source]

Bases: object

A generic importer class It provides the standard methods for importing data from an URI and creating a model instance of it. By default it fetches a resource, first tries to parse it using our rdf parser, if that fails tries to parse it using json and then extracts the fields whose keys match the model field names. Projects can inherit from this class and override the default methods or simple write their own from scratch.

clean_uri(uri)[source]
create_instance()[source]
get_data(drop_unknown_fields=True)[source]

fetch the data using the request method and mangle the data using the mangle_data method. If the drop_unknown_fields argument is true, remove all fields from the data dict that do not have an equivalent field in the model.

property get_uri
import_into_instance(instance, fields='__all__')[source]
import_uri = None
mangle_data(data)[source]
model = None
request(uri)[source]

apis_core.generic.renderers module

class apis_core.generic.renderers.GenericRDFBaseRenderer[source]

Bases: BaseRenderer

render(data, accepted_media_type=None, renderer_context=None)[source]
class apis_core.generic.renderers.GenericRDFN3Renderer[source]

Bases: GenericRDFBaseRenderer

format = 'rdf+n3'
media_type = 'text/n3'
class apis_core.generic.renderers.GenericRDFTurtleRenderer[source]

Bases: GenericRDFBaseRenderer

format = 'rdf+turtle'
media_type = 'text/turtle'
class apis_core.generic.renderers.GenericRDFXMLRenderer[source]

Bases: GenericRDFBaseRenderer

format = 'rdf+xml'
media_type = 'application/rdf+xml'

apis_core.generic.routers module

class apis_core.generic.routers.CustomAPIRootView(**kwargs)[source]

Bases: APIRootView

The default basic root view for CustomDefaultRouter

This view lists the output of the default APIRootView of the Django Rest Framework. In addition, it injects the routes of the genericmodelapi (those are not hardcoded registered but autogenerated based on the models that inherit from GenericModel).

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

get(request, *args, **kwargs)[source]
class apis_core.generic.routers.CustomDefaultRouter(*args, **kwargs)[source]

Bases: DefaultRouter

The CustomDefaultRouter only diverts from the Django Rest Framework DefaultRouter by setting the APIRootView to our CustomAPIRootView.

APIRootView

alias of CustomAPIRootView

apis_core.generic.serializers module

class apis_core.generic.serializers.ContentTypeInstanceSerializer(*args, **kwargs)[source]

Bases: Serializer

When a field is instantiated, we store the arguments that were used, so that we can present a helpful representation of the object.

to_internal_value(data)[source]

Dict of native values <- Dict of primitive datatypes.

class apis_core.generic.serializers.GenericHyperlinkedIdentityField(*args, **kwargs)[source]

Bases: GenericHyperlinkedRelatedField

When a field is instantiated, we store the arguments that were used, so that we can present a helpful representation of the object.

class apis_core.generic.serializers.GenericHyperlinkedModelSerializer(*args, **kwargs)[source]

Bases: HyperlinkedModelSerializer

When a field is instantiated, we store the arguments that were used, so that we can present a helpful representation of the object.

alias of GenericHyperlinkedRelatedField

serializer_url_field

alias of GenericHyperlinkedIdentityField

class apis_core.generic.serializers.GenericHyperlinkedRelatedField(*args, **kwargs)[source]

Bases: HyperlinkedRelatedField

When a field is instantiated, we store the arguments that were used, so that we can present a helpful representation of the object.

get_url(obj, view_name, request, format)[source]

Given an object, return the URL that hyperlinks to the object.

May raise a NoReverseMatch if the view_name and lookup_field attributes are not configured to correctly match the URL conf.

use_pk_only_optimization()[source]
class apis_core.generic.serializers.SimpleObjectSerializer(*args, **kwargs)[source]

Bases: Serializer

When a field is instantiated, we store the arguments that were used, so that we can present a helpful representation of the object.

class Meta[source]

Bases: object

fields = ['url', 'label', 'content_type_key', 'content_type_name']
get_content_type_key(obj) str[source]
get_content_type_name(obj) str[source]
get_label(obj) str[source]
apis_core.generic.serializers.serializer_factory(model, serializer=<class 'apis_core.generic.serializers.GenericHyperlinkedModelSerializer'>, fields='__all__', **kwargs)[source]

apis_core.generic.tables module

class apis_core.generic.tables.ActionColumn(*args, **kwargs)[source]

Bases: CustomTemplateColumn

A custom template column with some additional attributes for actions.

attrs = {'td': {'style': 'width:1%;'}}
exclude_from_export = True
orderable = False
render(record, table, *args, **kwargs)[source]

Return the content for a specific cell.

This method can be overridden by table.render_FOO methods on the table or by subclassing .Column.

If the value for this cell is in .empty_values, this method is skipped and an appropriate default value is rendered instead. Subclasses should set .empty_values to () if they want to handle all values in .render.

verbose_name = ''
class apis_core.generic.tables.CustomTemplateColumn(*args, **kwargs)[source]

Bases: TemplateColumn

A custom template column - the tables.TemplateColumn class does not allow to set attributes via class variables. Therefor we use this CustomTemplateColumn to set some arguments based on class attributes and override the attributes in child classes.

exclude_from_export = False
orderable = None
template_name = None
verbose_name = None
class apis_core.generic.tables.DeleteColumn(*args, **kwargs)[source]

Bases: ActionColumn

A column showing a delete button

permission = 'delete'
template_name = 'columns/delete.html'
class apis_core.generic.tables.DescriptionColumn(*args, **kwargs)[source]

Bases: CustomTemplateColumn

A column showing a model description

orderable = False
template_name = 'columns/description.html'
class apis_core.generic.tables.EditColumn(*args, **kwargs)[source]

Bases: ActionColumn

A column showing an edit button

permission = 'change'
template_name = 'columns/edit.html'
class apis_core.generic.tables.GenericTable(data=None, order_by=None, orderable=None, empty_text=None, exclude=None, attrs=None, row_attrs=None, pinned_row_attrs=None, sequence=None, prefix=None, order_by_field=None, page_field=None, per_page_field=None, template_name=None, default=None, request=None, show_header=None, show_footer=True, extra_columns=None)[source]

Bases: Table

A generic table that contains an edit button column, a delete button column and a description column

class Meta[source]

Bases: object

fields = ['id', 'desc']
sequence = ('...', 'view', 'edit', 'delete')
base_columns = {'delete': <apis_core.generic.tables.DeleteColumn object>, 'desc': <apis_core.generic.tables.DescriptionColumn object>, 'edit': <apis_core.generic.tables.EditColumn object>, 'view': <apis_core.generic.tables.ViewColumn object>}
class apis_core.generic.tables.MoreLessColumn(preview, fulltext, *args, **kwargs)[source]

Bases: TemplateColumn

Useful for displaying long fields. A preview is shown initially with a “Show more” link which is replaced with a “Show less” link when expanded.

render(record, **kwargs)[source]

Return the content for a specific cell.

This method can be overridden by table.render_FOO methods on the table or by subclassing .Column.

If the value for this cell is in .empty_values, this method is skipped and an appropriate default value is rendered instead. Subclasses should set .empty_values to () if they want to handle all values in .render.

template_name = 'columns/more-less.html'
class apis_core.generic.tables.ViewColumn(*args, **kwargs)[source]

Bases: ActionColumn

A column showing a view button

permission = 'view'
template_name = 'columns/view.html'

apis_core.generic.urls module

class apis_core.generic.urls.ContenttypeConverter[source]

Bases: object

A converter that converts from a string representation of a model (app_label.model) to the actual Django model class.

regex = '\\w+\\.\\w+'
to_python(value)[source]
to_url(value)[source]

apis_core.generic.views module

class apis_core.generic.views.Autocomplete(**kwargs)[source]

Bases: GenericModelMixin, PermissionRequiredMixin, Select2QuerySetView

Autocomplete view for a generic model. Access requires the <model>_view permission. The queryset is overridden by the first match from the first_member_match helper.

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

create_object(value)[source]

Create an object given a text.

get_queryset()[source]

Filter the queryset with GET[‘q’].

get_results(context)[source]

Return data for the ‘results’ key of the response.

permission_action_required = 'view'
post(request, *args, **kwargs)[source]

Create an object given a text after checking permissions.

Runs self.validate() if self.validate_create is True.

setup(*args, **kwargs)[source]

Initialize attributes shared by all view methods.

template_name_suffix = '_autocomplete_result'
class apis_core.generic.views.Create(**kwargs)[source]

Bases: GenericModelMixin, PermissionRequiredMixin, CreateView

Create view for a generic model. Access requires the <model>_add permission. The form class is overridden by the first match from the first_member_match helper.

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

get_form_class()[source]

Return the form class to use in this view.

get_success_url()[source]

Return the URL to redirect to after processing a valid form.

permission_action_required = 'add'
template_name = 'generic/generic_form.html'
class apis_core.generic.views.Delete(**kwargs)[source]

Bases: GenericModelMixin, PermissionRequiredMixin, DeleteView

Delete view for a generic model. Access requires the <model>_delete permission.

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

delete(*args, **kwargs)[source]

Call the delete() method on the fetched object and then redirect to the success URL.

get_success_url()[source]

Return the URL to redirect to after processing a valid form.

permission_action_required = 'delete'
class apis_core.generic.views.Detail(**kwargs)[source]

Bases: GenericModelMixin, PermissionRequiredMixin, DetailView

Detail view for a generic model. Access requires the <model>_view permission.

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

permission_action_required = 'view'
class apis_core.generic.views.Enrich(**kwargs)[source]

Bases: GenericModelMixin, PermissionRequiredMixin, FormView

Enrich an entity with data from an external source If so, it uses the proper Importer to get the data from the Uri and provides the user with a form to select the fields that should be updated.

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

form_class

alias of GenericEnrichForm

form_valid(form)[source]

Go through all the form fields and extract the ones that start with update_ and that are set (those are the checkboxes that select which fields to update). Then use the importers import_into_instance method to set those fields values on the model instance.

get(*args, **kwargs)[source]

Handle GET requests: instantiate a blank version of the form.

get_context_data(**kwargs)[source]

Insert the form into the context dict.

get_form_kwargs(*args, **kwargs)[source]

Return the keyword arguments for instantiating the form.

get_success_url()[source]

Return the URL to redirect to after processing a valid form.

importer_class = None
permission_action_required = 'change'
setup(*args, **kwargs)[source]

Initialize attributes shared by all view methods.

template_name = 'generic/generic_enrich.html'
class apis_core.generic.views.GenericModelMixin[source]

Bases: object

A mixin providing the common functionality for all the views working with generic models - that is models that are accessed via the contenttype framework (using app_label.model). It sets the .model of the view and generates a list of possible template names (based on the MRO of the model). If the view has a permission_action_required attribute, this is used to set the permission required to access the view for this specific model.

get_permission_required()[source]
get_template_names()[source]
setup(*args, **kwargs)[source]
class apis_core.generic.views.Import(**kwargs)[source]

Bases: GenericModelMixin, PermissionRequiredMixin, FormView

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

form_valid(form)[source]

If the form is valid, redirect to the supplied URL.

get_form_class()[source]

Return the form class to use.

get_success_url()[source]

Return the URL to redirect to after processing a valid form.

permission_action_required = 'add'
template_name = 'generic/generic_import_form.html'
template_name_suffix = '_import'
class apis_core.generic.views.List(**kwargs)[source]

Bases: ListViewObjectFilterMixin, GenericModelMixin, PermissionRequiredMixin, SingleTableMixin, FilterView

List view for a generic model. Access requires the <model>_view permission. It is based on django-filters FilterView and django-tables SingleTableMixin. The table class is overridden by the first match from the first_member_match helper. The filterset class is overridden by the first match from the first_member_match helper. The queryset is overridden by the first match from the first_member_match helper.

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

get_filterset(filterset_class)[source]

We override the get_filterset method, so we can inject a columns selector into the form

get_filterset_class()[source]

Returns the filterset class to use in this view

get_paginate_by(table_data) int | None[source]

Override get_paginate_by from the tables2 TableMixinBase, so we can set the paginate_by value as attribute of the table.

get_queryset()[source]

Return the list of items for this view.

The return value must be an iterable and may be an instance of QuerySet in which case QuerySet specific behavior will be enabled.

get_table_class()[source]

Return the class to use for the table.

get_table_kwargs()[source]

Return the keyword arguments for instantiating the table.

Allows passing customized arguments to the table constructor, for example, to remove the buttons column, you could define this method in your View:

def get_table_kwargs(self):
    return {
        'exclude': ('buttons', )
    }
permission_action_required = 'view'
template_name_suffix = '_list'
class apis_core.generic.views.MergeWith(**kwargs)[source]

Bases: GenericModelMixin, PermissionRequiredMixin, FormView

Generic merge view.

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

form_class

alias of GenericMergeForm

form_valid(form)[source]

If the form is valid, redirect to the supplied URL.

get_context_data(**kwargs)[source]

The context consists of the two objects that are merged as well as a list of changes. Those changes are presented in the view as a table with diffs

get_success_url()[source]

Return the URL to redirect to after processing a valid form.

permission_action_required = 'change'
setup(*args, **kwargs)[source]

Initialize attributes shared by all view methods.

template_name = 'generic/generic_merge.html'
class apis_core.generic.views.Overview(**kwargs)[source]

Bases: TemplateView

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

template_name = 'generic/overview.html'
class apis_core.generic.views.Update(**kwargs)[source]

Bases: GenericModelMixin, PermissionRequiredMixin, UpdateView

Update view for a generic model. Access requires the <model>_change permission. The form class is overridden by the first match from the first_member_match helper.

Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things.

get_form_class()[source]

Return the form class to use in this view.

get_success_url()[source]

Return the URL to redirect to after processing a valid form.

permission_action_required = 'change'