ADR#

class ansys.dynamicreporting.core.serverless.adr.ADR(*args, **kwargs)#

Bases: object

Ansys Dynamic Reporting (ADR) class.

This class provides a high-level API for interacting with ADR without running the full web server. It encapsulates Django setup, database configuration, media/static configuration, and report rendering/export.

Parameters:
ansys_installationstr, optional

Path to an Ansys/Nexus installation. If "docker", ADR will spin up a Docker container and copy the core bits from it. If not provided, get_install_info() attempts to infer the installation location.

ansys_versionint, optional

Explicit Ansys version to use. If omitted, ADR tries to infer it from the installation content.

db_directorystr, optional

Directory for a local SQLite database (and media subdirectory). Either this or databases is required unless in_memory=True.

databasesdict, optional

Full Django DATABASES configuration. If provided, it replaces the default SQLite configuration. Must include a "default" key.

media_directorystr, optional

Directory where uploaded media files are stored. If omitted, ADR uses CEI_NEXUS_LOCAL_MEDIA_DIR or falls back to <db_directory>/media.

static_directorystr, optional

Directory where static files are collected. If omitted, static exports are not available.

media_urlstr, default: “/media/”

Base URL (relative) for serving media files.

static_urlstr, default: “/static/”

Base URL (relative) for serving static files.

debugbool, optional

Explicit Django DEBUG flag. If omitted, the value from the ADR settings module is used.

optsdict, optional

Extra environment variables to inject into os.environ before setup.

requestHttpRequest, optional

Django request object, useful when ADR is used in a web context.

logfilestr, optional

Path to the log file. If omitted, logging typically goes to stderr.

docker_imagestr, optional

Docker image URL to use when ansys_installation="docker". Defaults to DOCKER_REPO_URL.

in_memorybool, default: False

If True, ADR configures an in-memory SQLite database and temporary media/static directories, suitable for tests or ephemeral usage.

Raises:
ADRException

If Docker bootstrapping or installation copying fails.

ImproperlyConfiguredError

If required configuration such as DB or media directories is missing or invalid.

InvalidAnsysPath

If a valid Ansys installation cannot be located.

InvalidPath

If a configured path does not exist and cannot be created.

Examples

Basic local SQLite usage:

install_loc = r"C:\Program Files\ANSYS Inc\v252"
db_dir = r"C:\DBs\docex"
from ansys.dynamicreporting.core.serverless import ADR, String, BasicLayout

adr = ADR(
    ansys_installation=install_loc,
    db_directory=db_dir,
    static_directory=r"C:\DBs\static",
)
adr.setup(collect_static=True)

item = adr.create_item(
    String,
    name="intro_text",
    content="It's alive!",
    tags="dp=dp227 section=intro",
    source="sls-test",
)
template = adr.create_template(
    BasicLayout,
    name="Serverless Simulation Report",
    parent=None,
    tags="dp=dp227",
)
template.set_filter("A|i_tags|cont|dp=dp227;")
template.save()

html_content = adr.render_report(
    name="Serverless Simulation Report",
    context={},
    item_filter="A|i_tags|cont|dp=dp227;",
)

Methods

ADR.backup_database([output_directory, ...])

Create a JSON (optionally gzipped) backup of an ADR database.

ADR.close()

Close DB connections and clean up any temporary directories.

ADR.copy_objects(object_type, target_database, *)

Copy ADR objects (and associated media) between databases.

ADR.create_item(item_type, **kwargs)

Create and persist a new Item of the given type.

ADR.create_objects(objects, **kwargs)

Persist multiple ADR objects, returning the count of saved objects.

ADR.create_template(template_type, **kwargs)

Create and persist a new Template of the given type.

ADR.ensure_setup()

Verify that ADR has been instantiated and setup() called.

ADR.export_report_as_html(output_directory, *)

Export a report as a standalone HTML file (plus assets).

ADR.export_report_as_pdf(*[, filename, ...])

Render a PDF report and write it to disk.

ADR.export_report_as_pptx(*[, filename, ...])

Render a PPTX report and write it to disk.

ADR.get_database_config([raise_exception])

Return the Django DATABASES configuration, if available.

ADR.get_instance()

Retrieve the configured ADR singleton instance.

ADR.get_list_reports([r_type])

Return a list of reports or just their names.

ADR.get_report(**kwargs)

Fetch a root report template (no parent) using template fields.

ADR.get_reports(*[, fields, flat])

Return all root report templates, optionally as a values-list.

ADR.load_templates(templates)

Load a template tree from a Python dictionary.

ADR.load_templates_from_file(file_path)

Load a template tree from a JSON file.

ADR.query(query_type, *[, query])

Run an ADR query against sessions, datasets, items, or templates.

ADR.render_report(*[, context, item_filter])

Render a report as an HTML string.

ADR.render_report_as_pdf(*[, context, ...])

Render a report as a PDF byte stream.

ADR.render_report_as_pptx(*[, context, ...])

Render a report as a PPTX byte stream.

ADR.restore_database(input_file, *[, database])

Restore a database from a JSON (or JSON.gz) dump file.

ADR.set_default_dataset(dataset)

Convenience method for setting dataset.

ADR.set_default_session(session)

Convenience method for setting session.

ADR.setup([collect_static])

Configure Django and perform ADR initialization.

Attributes

ADR.ansys_installation

Absolute path to the resolved Ansys/Nexus installation.

ADR.ansys_version

Detected or configured Ansys version.

ADR.dataset

Default Dataset associated with this ADR instance.

ADR.db_directory

Directory where the primary database resides.

ADR.is_setup

Return True if setup() has been successfully completed.

ADR.media_directory

Directory where media files (uploads) are stored.

ADR.media_url

Relative URL prefix used for media files.

ADR.session

Default Session associated with this ADR instance.

ADR.session_guid

GUID of the default Session.

ADR.static_directory

Directory where static files are collected.

ADR.static_url

Relative URL prefix used for static files.

property ansys_installation: str#

Absolute path to the resolved Ansys/Nexus installation.

property ansys_version: int#

Detected or configured Ansys version.

backup_database(output_directory: str | Path = '.', *, database: str = 'default', compress: bool = False, ignore_primary_keys: bool = False) None#

Create a JSON (optionally gzipped) backup of an ADR database.

Parameters:
output_directorystr or Path, default: “.”

Directory in which to place the backup file.

databasestr, default: “default”

ADR database alias to back up.

compressbool, default: False

If True, write a .json.gz file instead of plain JSON.

ignore_primary_keysbool, default: False

If True, use --natural-primary to ignore primary key values and rely on natural keys instead.

Raises:
ADRException

If in-memory mode is active, the target DB is not configured, the output directory is invalid, or the backup command fails.

close() None#

Close DB connections and clean up any temporary directories.

This is safe to call multiple times and is typically used when tearing down an ADR instance at process exit or the end of a test.

copy_objects(object_type: Session | Dataset | type[Item] | type[Template], target_database: str, *, query: str = '', target_media_dir: str | Path = '', test: bool = False) int#

Copy ADR objects (and associated media) between databases.

This method:

  • Queries objects of the given type from the source database (currently hard-coded to "default").

  • For Item objects, ensures their Session and Dataset are also present in the target database, creating them as needed.

  • For Template objects, only copies root templates (children are copied recursively).

  • Copies media files to a target media directory, optionally rebuilding 3D geometry files.

Parameters:
object_typetype

One of Session, Dataset, Item subclass, or Template.

target_databasestr

Django database alias to copy into.

querystr, default: “”

ADR query string used to select objects from the source DB.

target_media_dirstr or Path, default: “”

Target directory for media files, required when copying items with associated files and the target database is not SQLite.

testbool, default: False

If True, do not actually write anything; just log and return the count of objects that would be copied.

Returns:
int

Number of objects copied (or that would be copied in test mode).

Raises:
ADRException

If misconfigured (e.g. missing DB aliases, invalid media directory, non-top-level templates, or copy errors).

create_item(item_type: type[Item], **kwargs: Any) Item#

Create and persist a new Item of the given type.

Parameters:
item_typetype[Item]

Concrete Item subclass (e.g. String, HTML).

**kwargsAny

Field values to use when constructing the new item.

Returns:
Item

The newly created item instance.

Raises:
TypeError

If item_type is not a subclass of Item.

ADRException

If no keyword arguments are provided.

static create_objects(objects: list | ObjectSet, **kwargs: Any) int#

Persist multiple ADR objects, returning the count of saved objects.

Parameters:
objectslist or ObjectSet

Iterable of ADR model instances to save.

**kwargsAny

Additional keyword arguments passed to each object’s save method (for example, using="remote").

Returns:
int

Number of objects successfully saved.

Raises:
ADRException

If objects is not iterable.

static create_template(template_type: type[Template], **kwargs: Any) Template#

Create and persist a new Template of the given type.

Parameters:
template_typetype[Template]

Concrete Template subclass (e.g. BasicLayout).

**kwargsAny

Attributes for template creation. May include parent.

Returns:
Template

The newly created template instance.

Raises:
TypeError

If template_type is not a subclass of Template.

ADRException

If no keyword arguments are provided.

property dataset: Dataset#

Default Dataset associated with this ADR instance.

property db_directory: str#

Directory where the primary database resides.

If _db_directory is not set, this attempts to infer the directory from the SQLite DB path associated with the default database alias.

classmethod ensure_setup() None#

Verify that ADR has been instantiated and setup() called.

Raises:
RuntimeError

If no instance exists or setup has not been completed.

export_report_as_html(output_directory: str | Path, *, filename: str = 'index.html', dark_mode: bool = False, context: dict | None = None, item_filter: str = '', **kwargs: Any) Path#

Export a report as a standalone HTML file (plus assets).

Parameters:
output_directorystr or Path

Directory where the report will be exported. It is created if it does not exist.

filenamestr, default: “index.html”

Name of the HTML file within output_directory.

dark_modebool, default: False

If True, the report is rendered using a dark theme (where supported).

contextdict, optional

Context to pass to the report template.

item_filterstr, optional

ADR filter applied to items in the report.

**kwargsAny

Additional keyword arguments to pass to fetch the report template. Eg: guid, name, etc. At least one keyword argument must be provided to fetch the report.

Returns:
Path

Path to the generated HTML file.

Raises:
ADRException

If no keyword arguments are provided or if the static directory is not configured.

ImproperlyConfiguredError

If the static directory is not configured or if the output directory cannot be created.

Examples

>>> from ansys.dynamicreporting.core.serverless import ADR
>>> adr = ADR(
            ansys_installation=r"C:\Program Files\ANSYS Inc\v252",
            db_directory=r"C:\DBs\docex",
            media_directory=r"C:\DBs\docex\media",
            static_directory=r"C:\static"
        )
>>> adr.setup(collect_static=True)
>>> output_path = adr.export_report_as_html(
            Path.cwd() / "htmlex",
            context={},
            item_filter="A|i_tags|cont|dp=dp227;",
            name="Serverless Simulation Report",
        )
export_report_as_pdf(*, filename: str | Path = None, context: dict | None = None, item_filter: str = '', **kwargs: Any) None#

Render a PDF report and write it to disk.

Parameters:
filenamestr or Path, optional

Target PDF filename. If omitted, use "<guid>.pdf" based on the template GUID.

contextdict, optional

Context to pass to the report template.

item_filterstr, optional

ADR filter applied to items in the report.

**kwargsAny

Additional keyword arguments to pass to the report template. Eg: guid, name, etc. At least one keyword argument must be provided to fetch the report.

Returns:
None
Raises:
ADRException

If no keyword arguments are provided or if the report rendering fails.

Examples

>>> from ansys.dynamicreporting.core.serverless import ADR
>>> adr = ADR(ansys_installation=r"C:\Program Files\ANSYS Inc\v252", db_directory=r"C:\DBs\docex")
>>> adr.setup()
>>> adr.export_report_as_pdf(filename="report.pdf", name="Serverless Simulation Report", item_filter="A|i_tags|cont|dp=dp227;")
export_report_as_pptx(*, filename: str | Path = None, context: dict | None = None, item_filter: str = '', **kwargs: Any) None#

Render a PPTX report and write it to disk.

If filename is not provided, the template’s output_pptx property is used, or a fallback based on the template GUID.

Parameters:
filenamestr or Path, optional

Target PPTX filename. If omitted, use the template’s output_pptx property or "<guid>.pptx".

contextdict, optional

Context to pass to the report template.

item_filterstr, optional

ADR filter applied to items in the report.

**kwargsAny

Additional keyword arguments to pass to the report template. Eg: guid, name, etc. At least one keyword argument must be provided to fetch the report.

Returns:
None
Raises:
ADRException

If no keyword arguments are provided or if the template is not of type PPTXLayout or if the report rendering fails.

Examples

>>> from ansys.dynamicreporting.core.serverless import ADR
>>> adr = ADR(ansys_installation=r"C:\Program Files\ANSYS Inc\v252", db_directory=r"C:\DBs\docex")
>>> adr.setup()
>>> adr.export_report_as_pptx(name="Serverless Simulation Report", item_filter="A|i_tags|cont|dp=dp227;")
classmethod get_database_config(raise_exception: bool = False) dict | None#

Return the Django DATABASES configuration, if available.

Parameters:
raise_exceptionbool, default: False

If True, raise ImproperlyConfiguredError when settings are not yet configured.

Returns:
dict or None

The DATABASES mapping, or None if settings are not configured and raise_exception is False.

Raises:
ImproperlyConfiguredError

If Django settings are not configured and raise_exception=True.

classmethod get_instance() ADR#

Retrieve the configured ADR singleton instance.

Returns:
ADR

The existing ADR instance.

Raises:
RuntimeError

If no instance has been created yet.

get_list_reports(r_type: str | None = 'name') ObjectSet | list#

Return a list of reports or just their names.

Parameters:
r_type{“name”, “report”, None}, optional

If "name", return a list of report names. If "report" or None, return an ObjectSet of templates.

Returns:
ObjectSet or list

Either templates or report names.

Raises:
ADRException

If r_type is not one of the supported options.

static get_report(**kwargs) Template#

Fetch a root report template (no parent) using template fields.

Parameters:
**kwargsAny

Filter arguments (for example, name="Report Name").

Returns:
Template

The matching root template.

Raises:
ADRException

If no kwargs are provided or the template cannot be found.

static get_reports(*, fields: list | None = None, flat: bool = False) ObjectSet | list#

Return all root report templates, optionally as a values-list.

Parameters:
fieldslist, optional

If provided, use values_list on the underlying queryset with these fields.

flatbool, default: False

Passed through to values_list. Typically used when a single field name is provided in fields.

Returns:
ObjectSet or list

Either an ObjectSet of templates or a list of field tuples/values.

property is_setup: bool#

Return True if setup() has been successfully completed.

load_templates(templates: dict) None#

Load a template tree from a Python dictionary.

Parameters:
templatesdict

A mapping produced by Template.to_dict(), typically by reading JSON and decoding it.

Raises:
ADRException

If no root (parent-less) template can be found in the mapping.

load_templates_from_file(file_path: str | Path) None#

Load a template tree from a JSON file.

Parameters:
file_pathstr or Path

Path to the JSON file containing templates exported via Template.to_json().

Raises:
FileNotFoundError

If the file does not exist.

property media_directory: str#

Directory where media files (uploads) are stored.

property media_url: str#

Relative URL prefix used for media files.

static query(query_type: Session | Dataset | type[Item] | type[Template], *, query: str = '', **kwargs: Any) ObjectSet#

Run an ADR query against sessions, datasets, items, or templates.

Parameters:
query_typetype

One of Session, Dataset, Item subclass, or Template.

querystr, default: “”

ADR query string (e.g. "A|i_tags|cont|dp=dp227;").

**kwargsAny

Additional keyword arguments forwarded to .find.

Returns:
ObjectSet

Query results wrapped in ObjectSet.

Raises:
TypeError

If query_type is not a supported ADR model type.

render_report(*, context: dict | None = None, item_filter: str = '', **kwargs: Any) str#

Render a report as an HTML string.

Parameters:
contextdict, optional

Context to pass to the report template.

item_filterstr, optional

ADR filter applied to items in the report.

**kwargsAny

Additional keyword arguments to pass to the report template. Eg: guid, name, etc. At least one keyword argument must be provided to fetch the report.

Returns:
str

Rendered HTML content (media type text/html).

Raises:
ADRException

If no keyword arguments are provided or if the report rendering fails.

Examples

>>> from ansys.dynamicreporting.core.serverless import ADR
>>> adr = ADR(ansys_installation=r"C:\Program Files\ANSYS Inc\v252", db_directory=r"C:\DBs\docex")
>>> html_content = adr.render_report(name="Serverless Simulation Report", item_filter="A|i_tags|cont|dp=dp227;")
>>> with open("report.html", "w", encoding="utf-8") as f:
...     f.write(html_content)
render_report_as_pdf(*, context: dict | None = None, item_filter: str = '', **kwargs: Any) bytes#

Render a report as a PDF byte stream.

Parameters:
contextdict, optional

Context to pass to the report template.

item_filterstr, optional

ADR filter applied to items in the report.

**kwargsAny

Additional keyword arguments to pass to the report template. Eg: guid, name, etc. At least one keyword argument must be provided to fetch the report.

Returns:
bytes

PDF document bytes (media type application/pdf).

Raises:
ADRException

If no keyword arguments are provided or if the report rendering fails.

Examples

>>> from ansys.dynamicreporting.core.serverless import ADR
>>> adr = ADR(ansys_installation=r"C:\Program Files\ANSYS Inc\v252", db_directory=r"C:\DBs\docex")
>>> adr.setup()
>>> pdf_stream = adr.render_report_as_pdf(name="Serverless Simulation Report")
>>> with open("report.pdf", "wb") as f:
...     f.write(pdf_stream)
render_report_as_pptx(*, context: dict | None = None, item_filter: str = '', **kwargs: Any) bytes#

Render a report as a PPTX byte stream.

Only templates of type PPTXLayout are supported.

Parameters:
contextdict, optional

Context to pass to the report template.

item_filterstr, optional

ADR filter applied to items in the report.

**kwargsAny

Additional keyword arguments to pass to the report template. Eg: guid, name, etc. At least one keyword argument must be provided to fetch the report.

Returns:
bytes

PPTX document bytes (media type application/vnd.openxmlformats-officedocument.presentationml.presentation).

Raises:
ADRException

If no keyword arguments are provided or if the template is not of type PPTXLayout or if the report rendering fails.

Examples

>>> from ansys.dynamicreporting.core.serverless import ADR
>>> adr = ADR(ansys_installation=r"C:\Program Files\ANSYS Inc\v252", db_directory=r"C:\DBs\docex")
>>> adr.setup()
>>> pptx_stream = adr.render_report_as_pptx(name="Serverless Simulation Report", item_filter="A|i_tags|cont|dp=dp227;")
>>> with open("report.pptx", "wb") as f:
...     f.write(pptx_stream)
restore_database(input_file: str | Path, *, database: str = 'default') None#

Restore a database from a JSON (or JSON.gz) dump file.

Parameters:
input_filestr or Path

Path to the dump file.

databasestr, default: “default”

Django database alias to restore into.

Raises:
ADRException

If the target DB is not configured, the file does not exist, or the load command fails.

property session: Session#

Default Session associated with this ADR instance.

property session_guid: UUID#

GUID of the default Session.

set_default_dataset(dataset: Dataset) None#

Convenience method for setting dataset.

set_default_session(session: Session) None#

Convenience method for setting session.

setup(collect_static: bool = False) None#

Configure Django and perform ADR initialization.

This method:

  • Optionally locates and imports the enve module for geometry.

  • Adds the Nexus Django directory to sys.path and imports the serverless settings module.

  • Builds an overrides dict and calls django.conf.settings.configure().

  • Runs Django migrations for all configured databases.

  • Runs geometry migration/update checks.

  • Optionally collects static files to _static_directory.

  • Creates a default Session and Dataset.

Parameters:
collect_staticbool, optional

If True, run collectstatic into _static_directory.

Raises:
ImportError

If the Nexus Django settings could not be imported.

DatabaseMigrationError

If migrations fail on any database.

GeometryMigrationError

If geometry update checks fail.

ImproperlyConfiguredError

If settings or required paths are invalid.

StaticFilesCollectionError

If collectstatic fails.

property static_directory: str#

Directory where static files are collected.

property static_url: str#

Relative URL prefix used for static files.