djblets.extensions.extension¶
Base classes for implementing extensions.
- class BaseStaticBundleConfig[source]¶
Bases:
TypedDict
Base class for a bundle configuration.
This provides the configuration settings allowed by both CSS and JavaScript bundles for extensions.
New in version 5.0.
- source_filenames: Sequence[str]¶
A list of filenames that are included in this bundle.
It’s recommended that this contain a single “index” file that is responsible for importing other files that comprise the bundle.
If specifying
index.ts
orindex.js
the bundle will be treated as a TypeScript/JavaScript-based bundle, and all imported modules within the bundle will be resolved and compiled together.- Type:
- apply_to: Sequence[str]¶
A list of URL names that the bundle should be automatically loaded on.
If provided, the bundle will be selectively loaded only on these pages.
- Type:
- compiler_options: dict[str, Any]¶
Extra options to pass to the compiler.
This is currently unused by the compilers supported by Djblets.
- Type:
- extra_context: dict[str, str]¶
Extra context to include in the generated template.
For CSS, this will control the attributes of the
<link>
tag. It can be used to offer stylesheets for print or other forms of media via themedia
attribute.For JavaScript, this will control the attributes of the
<script>
tag. You can, for example, set"async"
or"defer"
toTrue
to add these attributes.- Type:
- include_bundles: Sequence[str]¶
A list of bundles to include whenever this bundle is included.
These bundles will be included prior to including this bundle. They must all be provided by the same extension.
- output_filename: str¶
The name of the bundle file to generate and load into pages.
This is expected to be a relative path. The extension support will take care of placing this file in an appropriate path.
If not provided, a default filename will be created for the bundle.
- Type:
- template_name: Optional[str]¶
The name of the Django template used to load this bundle.
This can be used to provide special logic for loading the bundle. It’s generally not needed.
- __annotations__ = {'apply_to': ForwardRef('NotRequired[Sequence[str]]', module='djblets.extensions.extension'), 'compiler_options': ForwardRef('NotRequired[dict[str, Any]]', module='djblets.extensions.extension'), 'extra_context': ForwardRef('NotRequired[dict[str, str]]', module='djblets.extensions.extension'), 'include_bundles': ForwardRef('NotRequired[Sequence[str]]', module='djblets.extensions.extension'), 'output_filename': ForwardRef('NotRequired[str]', module='djblets.extensions.extension'), 'source_filenames': ForwardRef('Sequence[str]', module='djblets.extensions.extension'), 'template_name': ForwardRef('NotRequired[Optional[str]]', module='djblets.extensions.extension')}¶
- __closed__ = False¶
- __extra_items__ = None¶
- __mutable_keys__ = frozenset({'apply_to', 'compiler_options', 'extra_context', 'include_bundles', 'output_filename', 'source_filenames', 'template_name'})¶
- __optional_keys__ = frozenset({})¶
- __orig_bases__ = (<function TypedDict>,)¶
- __readonly_keys__ = frozenset({})¶
- __required_keys__ = frozenset({'apply_to', 'compiler_options', 'extra_context', 'include_bundles', 'output_filename', 'source_filenames', 'template_name'})¶
- __total__ = True¶
- class CSSBundleConfig[source]¶
Bases:
BaseStaticBundleConfig
CSS static media configuration.
These provide the options for customizing CSS/LessCSS build behavior.
See
BaseStaticBundleConfig
for more options.New in version 5.0.
- variant: Optional[str]¶
The variant mode used for the CSS.
This can be set to
"datauri"
to encode any referenced images or fonts inline usingurl("data:...")
.
- __annotations__ = {'apply_to': ForwardRef('NotRequired[Sequence[str]]', module='djblets.extensions.extension'), 'compiler_options': ForwardRef('NotRequired[dict[str, Any]]', module='djblets.extensions.extension'), 'extra_context': ForwardRef('NotRequired[dict[str, str]]', module='djblets.extensions.extension'), 'include_bundles': ForwardRef('NotRequired[Sequence[str]]', module='djblets.extensions.extension'), 'output_filename': ForwardRef('NotRequired[str]', module='djblets.extensions.extension'), 'source_filenames': ForwardRef('Sequence[str]', module='djblets.extensions.extension'), 'template_name': ForwardRef('NotRequired[Optional[str]]', module='djblets.extensions.extension'), 'variant': ForwardRef('NotRequired[Optional[str]]', module='djblets.extensions.extension')}¶
- __closed__ = False¶
- __extra_items__ = None¶
- __mutable_keys__ = frozenset({'apply_to', 'compiler_options', 'extra_context', 'include_bundles', 'output_filename', 'source_filenames', 'template_name', 'variant'})¶
- __optional_keys__ = frozenset({})¶
- __orig_bases__ = (<class 'djblets.extensions.extension.BaseStaticBundleConfig'>,)¶
- __readonly_keys__ = frozenset({})¶
- __required_keys__ = frozenset({'apply_to', 'compiler_options', 'extra_context', 'include_bundles', 'output_filename', 'source_filenames', 'template_name', 'variant'})¶
- __total__ = True¶
- class JSBundleConfig[source]¶
Bases:
BaseStaticBundleConfig
JavaScript static media configuration.
These provide the options for customizing JavaScript/TypeScript build behavior.
See
BaseStaticBundleConfig
for more options.New in version 5.0.
- __annotations__ = {'apply_to': ForwardRef('NotRequired[Sequence[str]]', module='djblets.extensions.extension'), 'compiler_options': ForwardRef('NotRequired[dict[str, Any]]', module='djblets.extensions.extension'), 'extra_context': ForwardRef('NotRequired[dict[str, str]]', module='djblets.extensions.extension'), 'include_bundles': ForwardRef('NotRequired[Sequence[str]]', module='djblets.extensions.extension'), 'output_filename': ForwardRef('NotRequired[str]', module='djblets.extensions.extension'), 'source_filenames': ForwardRef('Sequence[str]', module='djblets.extensions.extension'), 'template_name': ForwardRef('NotRequired[Optional[str]]', module='djblets.extensions.extension')}¶
- __closed__ = False¶
- __extra_items__ = None¶
- __mutable_keys__ = frozenset({'apply_to', 'compiler_options', 'extra_context', 'include_bundles', 'output_filename', 'source_filenames', 'template_name'})¶
- __optional_keys__ = frozenset({})¶
- __orig_bases__ = (<class 'djblets.extensions.extension.BaseStaticBundleConfig'>,)¶
- __readonly_keys__ = frozenset({})¶
- __required_keys__ = frozenset({'apply_to', 'compiler_options', 'extra_context', 'include_bundles', 'output_filename', 'source_filenames', 'template_name'})¶
- __total__ = True¶
- CSSBundleConfigs¶
A mapping of CSS bundle names to configurations.
New in version 5.0.
alias of
Dict
[str
,CSSBundleConfig
]
- JSBundleConfigs¶
A mapping of JavaScript bundle names to configurations.
New in version 5.0.
alias of
Dict
[str
,JSBundleConfig
]
- class JSExtension(extension: Extension)[source]¶
Bases:
object
Base class for a JavaScript extension.
This can be subclassed to provide the information needed to initialize a JavaScript extension.
The JSExtension subclass is expected to define a
model_class
attribute naming its JavaScript counterpart. This would be the variable name for the (uninitialized) model for the extension, defined in a JavaScript bundle.It may also define
apply_to
, which is a list of URL names that the extension will be initialized on. If not provided, the extension will be initialized on all pages.To provide additional data to the model instance, the JSExtension subclass can implement
get_model_data()
and return a dictionary of data to pass. You may also override theget_settings()
method to return, a dict of settings to themodel_class
. By default, the associated extension’s settings are returned.- model_class: Optional[str] = None¶
The name of the JavaScript model class to instantiate.
This class will be instantiated on the page. It should be a subclass of
Djblets.Extension()
.
- apply_to: Optional[List[str]] = None¶
The list of URL names to load this extension on.
If not provided, this will be loaded on all pages.
- __init__(extension: Extension) None [source]¶
Initialize the JavaScript extension.
- Parameters:
extension (
Extension
) – The main extension that owns this JavaScript extension.
- applies_to(url_name: str) bool [source]¶
Return whether this extension applies to the given URL name.
- get_model_data(request: HttpRequest, **kwargs) djblets.util.typing.JSONDict [source]¶
Return model data for the Extension model instance in JavaScript.
Subclasses can override this to return custom data to pass to the extension class defined in
model_class
. This data must be JSON-serializable.- Parameters:
request (
django.http.HttpRequest
) – The HTTP request from the client.- Returns:
Model data to pass to the constructor of the JavaScript extension class.
- Return type:
- get_settings() djblets.util.typing.JSONDict [source]¶
Return the settings for the JS Extension.
By default, this is the associated
Extension
object’s settings. Subclasses may override this method to provide different settings.These settings will be provided to the
model_class
as asettings
key in its initialization options.- Returns:
The extension settings.
- Return type:
- __annotations__ = {'apply_to': 'Optional[List[str]]', 'model_class': 'Optional[str]'}¶
- class Extension(extension_manager: ExtensionManager)[source]¶
Bases:
object
Base class for an extension.
Extensions must subclass this class. They’ll automatically have support for settings, adding hooks, and plugging into the administration UI.
For information on writing extensions, see Writing Extensions.
- info: ClassVar[ExtensionInfo]¶
Information and metadata about the extension.
- instance: Optional[Extension] = None¶
The instance of this extension created by the extension manager.
- Type:
- registration: RegisteredExtension¶
The extension registration in the database.
- metadata: Optional[ExtensionMetadata] = None¶
Metadata describing the package.
This is used to set the name, version, and other information for the extension. This data defaults to coming from the extension’s Python package metadata, but can be set on the extension itself. You would want to use this if shipping multiple extensions in a single package, if you want to include a space in the package name, or if you want the version to be set independently of the package, for example.
The following keys are supported:
Name
: The displayed name of the extension.Version
: The version of the extension.Summary
: A summary of the extension.Description
: A more detailed description of the extension.License
: The license the extension was released under.Author
: The name of the author writing/maintaining the extension.Author-email
: The e-mail address of the author writing/maintaining the extension.Author-home-page
: The URL of the author writing/maintaining the extension.Home-page
: The URL of the extension’s home/product/company page.
- is_configurable: bool = False¶
Whether or not the extension is user-configurable.
If
True
, the extension will have a Configure link in the extension list that will take the user to a page for modifying extension settings. The extension must provide aadmin_urls.py
file defining a top-level URL (^$
) pointing to a view that will handle configuration.
- default_settings: JSONDict = {}¶
Default settings for the extension.
These values will be used when looking up keys in
settings
that don’t have custom values saved in the database.
- has_admin_site: bool = False¶
Whether or not the extension has a database administration site.
If
True
, the extension will have a Database link in the extension list that will take the user to a page for adding/editing any database models registered by the extension.
- requirements: List[str] = []¶
A list of any extension IDs to enable when this extension is enabled.
This is used to ensure that another extension is enabled before this one. It’s primarily for extensions that are augmenting or depending on another extension’s functionality.
- resources: List[WebAPIResource] = []¶
A list of API resource instances offered by this extension.
Each entry in the list is an instance of a custom
WebAPIResource
. These resources will appear underneath the extension’s own resource.
- apps: List[str] = []¶
A list of Django application module paths to load.
Each of these will be added to
INSTALLED_APPS
while the extension is enabled. It follows the same format as that setting.
- context_processors: List[str] = []¶
A list of Django context processors to load.
Each of these will be added to
TEMPLATE_CONTEXT_PROCESSORS
while the extension is enabled. It follows the same format as that setting.
- middleware: List[str] = []¶
A list of Django middleware to load.
Each of these will be run as if they were part of
MIDDLEWARE
depending on your setup) while the extension is enabled. It follows the same format as that setting.
- css_bundles: CSSBundleConfigs = {}¶
A dictionary of CSS bundles to include in the package.
These will be automatically packaged along with the extension, and can be loaded in templates using
{% ext_css_bundle %}
.Each key in the dictionary is the name of the bundle, and the value is a dictionary containing a
source_filenames
key pointing to a list of CSS/LessCSS files.A special bundle ID of
default
will cause the CSS to be loaded on every page.Changed in version 5.0: Added specific typing for bundle configuration. Previous versions allowed arbitrary dictionaries to be used.
- js_bundles: JSBundleConfigs = {}¶
A dictionary of JavaScript bundles to include in the package.
These will be automatically packaged along with the extension, and can be loaded in templates using
{% ext_js_bundle %}
.Each key in the dictionary is the name of the bundle, and the value is a dictionary containing a
source_filenames
key pointing to a list of JavaScript files.A special bundle ID of
default
will cause the JavaScript to be loaded on every page.Changed in version 5.0: Added specific typing for bundle configuration. Previous versions allowed arbitrary dictionaries to be used.
- js_extensions: Sequence[type[JSExtension]] = []¶
A list of JavaScript extension classes to enable on pages.
Each entry in the list is a
JSExtension
subclass to load.
- admin_urlpatterns: List[URLResolver]¶
URLs for the extension’s admin interface.
- Type:
list
ofdjango.urls.URLResolver
- admin_site_urlpatterns: List[Union[URLPattern, URLResolver]]¶
URLs for the extension’s admin site (DB forms, etc).
- Type:
list
ofdjango.urls.URLPattern
- __init__(extension_manager: ExtensionManager) None [source]¶
Initialize the extension.
Subclasses should not override this. Instead, they should override
initialize()
.- Parameters:
extension_manager (
djblets.extensions.manager.ExtensionManager
) – The extension manager that manages this extension.
- extension_manager: ExtensionManager¶
The extension manager that manages this extension.
- hooks: Set[ExtensionHook]¶
The hooks currently registered and enabled for the extension.
- settings: ExtensionSettings¶
The settings for the extension.
- admin_site: Optional[AdminSite]¶
The database administration site set for the extension.
This will be set automatically if
has_admin_site`
isTrue
.- Type:
django.contrib.admin.sites.AdminSite
- middleware_classes: Sequence[Callable]¶
The list of middleware classses.
New in version 2.2.4.
- Type:
list
ofcallable
- initialize() None [source]¶
Initialize the extension.
Subclasses can override this to provide any custom initialization. They do not need to call the parent function, as it does nothing.
- shutdown() None [source]¶
Shut down the extension.
By default, this calls shutdown_hooks.
Subclasses should override this if they need custom shutdown behavior.
- get_static_url(path: str) str [source]¶
Return the URL to a static media file for this extension.
This takes care of resolving the static media path name to a path relative to the web server. If a versioned media file is found, it will be used, so that browser-side caching can be used.
- get_bundle_id(name: str) str [source]¶
Return the ID for a CSS or JavaScript bundle.
This ID should be used when manually referencing the bundle in a template. The ID will be unique across all extensions.
- __annotations__ = {'admin_site': 'Optional[AdminSite]', 'admin_site_urlpatterns': 'List[Union[URLPattern, URLResolver]]', 'admin_urlpatterns': 'List[URLResolver]', 'apps': 'List[str]', 'context_processors': 'List[str]', 'css_bundles': 'CSSBundleConfigs', 'default_settings': 'JSONDict', 'extension_manager': 'ExtensionManager', 'has_admin_site': 'bool', 'hooks': 'Set[ExtensionHook]', 'id': 'ClassVar[str]', 'info': 'ClassVar[ExtensionInfo]', 'instance': 'Optional[Extension]', 'is_configurable': 'bool', 'js_bundles': 'JSBundleConfigs', 'js_extensions': 'Sequence[type[JSExtension]]', 'metadata': 'Optional[ExtensionMetadata]', 'middleware': 'List[str]', 'middleware_classes': 'Sequence[Callable]', 'registration': 'RegisteredExtension', 'requirements': 'List[str]', 'resources': 'List[WebAPIResource]', 'settings': 'ExtensionSettings'}¶
- class ExtensionInfo(ext_class: Type[Extension], package_name: str, metadata: Dict[str, Any] = {})[source]¶
Bases:
object
Information on an extension.
This class stores the information and metadata on an extension. This includes the name, version, author information, where it can be downloaded, whether or not it’s enabled or installed, and anything else that may be in the Python package for the extension.
- encodings: List[str] = ['utf-8', 'UTF-8', 'latin1']¶
Encodings to try using to decode metadata.
Deprecated since version 3.3: This is no longer used by Djblets and may be removed in a future version.
- classmethod create_from_entrypoint(entrypoint: EntryPoint, ext_class: Type[Extension]) ExtensionInfo [source]¶
Create a new ExtensionInfo from a Python EntryPoint.
This will pull out information from the EntryPoint and return a new ExtensionInfo from it.
It handles pulling out metadata from the older
PKG-INFO
files and the newerMETADATA
files.- Parameters:
entrypoint (
importlib.metadata.EntryPoint
) – The EntryPoint pointing to the extension class.ext_class (
type
) – The extension class (subclass ofExtension
).
- Returns:
An ExtensionInfo instance, populated with metadata from the package.
- Return type:
- __init__(ext_class: Type[Extension], package_name: str, metadata: Dict[str, Any] = {}) None [source]¶
Instantiate the ExtensionInfo using metadata and an extension class.
This will set information about the extension based on the metadata provided by the caller and the extension class itself.
- Parameters:
ext_class (
type
) – The extension class (subclass ofExtension
).package_name (
str
) – The package name owning the extension.metadata (
ExtensionMetadata
, optional) – Optional metadata for the extension. If the extension provides its own metadata, that will take precedence.
- Raises:
TypeError – The parameters passed were invalid (they weren’t a new-style call or a legacy entrypoint-related call).
- requirements: List[Type[Extension]]¶
A list of any extension IDs to enable when this extension is enabled.
This is used to ensure that another extension is enabled before this one. It’s primarily for extensions that are augmenting or depending on another extension’s functionality.
- __annotations__ = {'encodings': 'List[str]', 'requirements': 'List[Type[Extension]]'}¶
- installed_static_version_path[source]¶
The path to the static media version file.
This file records the version of the extension used when last installing the static media files.
- Type:
- has_resource(path: str) bool [source]¶
Return whether an extension has a resource in its package.
A resource is a file or directory that exists within an extension’s package.
- extract_resource(path: str) Optional[str] [source]¶
Return the filesystem path to an extracted resource.
A resource is a file or directory that exists within an extension’s package.
This will extract the resource from the package, if the package is compressed, and then return the local path to the file on the filesystem.
- write_installed_static_version() None [source]¶
Write the extension’s current static media version to disk.
This will write the extension’s current version in its static media directory, creating that directory if necessary. This will allow the extension manager to check if new media files need to be installed.
- Raises:
djblets.extensions.errors.InstallExtensionMediaError – There was an error writing the version to the static media directory. Details are in the error message.