ADR#
- class ansys.dynamicreporting.core.serverless.adr.ADR(*args, **kwargs)#
Bases:
objectAnsys 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_installation
str,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_version
int,optional Explicit Ansys version to use. If omitted, ADR tries to infer it from the installation content.
- db_directory
str,optional Directory for a local SQLite database (and media subdirectory). Either this or
databasesis required unlessin_memory=True.- databases
dict,optional Full Django
DATABASESconfiguration. If provided, it replaces the default SQLite configuration. Must include a"default"key.- media_directory
str,optional Directory where uploaded media files are stored. If omitted, ADR uses
CEI_NEXUS_LOCAL_MEDIA_DIRor falls back to<db_directory>/media.- static_directory
str,optional Directory where static files are collected. If omitted, static exports are not available.
- media_url
str, default: “/media/” Base URL (relative) for serving media files.
- static_url
str, 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.
- opts
dict,optional Extra environment variables to inject into
os.environbefore setup.- request
HttpRequest,optional Django request object, useful when ADR is used in a web context.
- logfile
str,optional Path to the log file. If omitted, logging typically goes to stderr.
- docker_image
str,optional Docker image URL to use when
ansys_installation="docker". Defaults toDOCKER_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.
- ansys_installation
- Raises:
ADRExceptionIf Docker bootstrapping or installation copying fails.
ImproperlyConfiguredErrorIf required configuration such as DB or media directories is missing or invalid.
InvalidAnsysPathIf a valid Ansys installation cannot be located.
InvalidPathIf 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.
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
Itemof 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
Templateof the given type.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
DATABASESconfiguration, if available.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
Absolute path to the resolved Ansys/Nexus installation.
Detected or configured Ansys version.
Default
Datasetassociated with this ADR instance.Directory where the primary database resides.
Return
Trueifsetup()has been successfully completed.Directory where media files (uploads) are stored.
Relative URL prefix used for media files.
Default
Sessionassociated with this ADR instance.GUID of the default
Session.Directory where static files are collected.
Relative URL prefix used for static files.
- 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_directory
strorPath, default: “.” Directory in which to place the backup file.
- database
str, default: “default” ADR database alias to back up.
- compressbool, default:
False If
True, write a.json.gzfile instead of plain JSON.- ignore_primary_keysbool, default:
False If
True, use--natural-primaryto ignore primary key values and rely on natural keys instead.
- output_directory
- Raises:
ADRExceptionIf 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
Itemobjects, ensures theirSessionandDatasetare also present in the target database, creating them as needed.For
Templateobjects, 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,Itemsubclass, orTemplate.- target_database
str Django database alias to copy into.
- query
str, default: “” ADR query string used to select objects from the source DB.
- target_media_dir
strorPath, 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:
intNumber of objects copied (or that would be copied in test mode).
- Raises:
ADRExceptionIf 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
Itemof the given type.- Parameters:
- item_typetype[
Item] Concrete
Itemsubclass (e.g.String,HTML).- **kwargs
Any Field values to use when constructing the new item.
- item_typetype[
- Returns:
ItemThe newly created item instance.
- Raises:
TypeErrorIf
item_typeis not a subclass ofItem.ADRExceptionIf no keyword arguments are provided.
- static create_objects(objects: list | ObjectSet, **kwargs: Any) int#
Persist multiple ADR objects, returning the count of saved objects.
- static create_template(template_type: type[Template], **kwargs: Any) Template#
Create and persist a new
Templateof the given type.- Parameters:
- template_typetype[
Template] Concrete
Templatesubclass (e.g.BasicLayout).- **kwargs
Any Attributes for template creation. May include
parent.
- template_typetype[
- Returns:
TemplateThe newly created template instance.
- Raises:
TypeErrorIf
template_typeis not a subclass ofTemplate.ADRExceptionIf no keyword arguments are provided.
- property db_directory: str#
Directory where the primary database resides.
If
_db_directoryis 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
ADRhas been instantiated andsetup()called.- Raises:
RuntimeErrorIf 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_directory
strorPath Directory where the report will be exported. It is created if it does not exist.
- filename
str, 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).- context
dict,optional Context to pass to the report template.
- item_filter
str,optional ADR filter applied to items in the report.
- **kwargs
Any 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.
- output_directory
- Returns:
PathPath to the generated HTML file.
- Raises:
ADRExceptionIf no keyword arguments are provided or if the static directory is not configured.
ImproperlyConfiguredErrorIf 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:
- filename
strorPath,optional Target PDF filename. If omitted, use
"<guid>.pdf"based on the template GUID.- context
dict,optional Context to pass to the report template.
- item_filter
str,optional ADR filter applied to items in the report.
- **kwargs
Any 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.
- filename
- Returns:
- Raises:
ADRExceptionIf 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
filenameis not provided, the template’soutput_pptxproperty is used, or a fallback based on the template GUID.- Parameters:
- filename
strorPath,optional Target PPTX filename. If omitted, use the template’s
output_pptxproperty or"<guid>.pptx".- context
dict,optional Context to pass to the report template.
- item_filter
str,optional ADR filter applied to items in the report.
- **kwargs
Any 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.
- filename
- Returns:
- Raises:
ADRExceptionIf 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
DATABASESconfiguration, if available.- Parameters:
- Returns:
- Raises:
ImproperlyConfiguredErrorIf Django settings are not configured and
raise_exception=True.
- classmethod get_instance() ADR#
Retrieve the configured ADR singleton instance.
- Returns:
- Raises:
RuntimeErrorIf 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.
- static get_report(**kwargs) Template#
Fetch a root report template (no parent) using template fields.
- Parameters:
- **kwargs
Any Filter arguments (for example,
name="Report Name").
- **kwargs
- Returns:
TemplateThe matching root template.
- Raises:
ADRExceptionIf 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:
- Returns:
ObjectSetorlistEither an
ObjectSetof templates or a list of field tuples/values.
- load_templates(templates: dict) None#
Load a template tree from a Python dictionary.
- Parameters:
- templates
dict A mapping produced by
Template.to_dict(), typically by reading JSON and decoding it.
- templates
- Raises:
ADRExceptionIf 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_path
strorPath Path to the JSON file containing templates exported via
Template.to_json().
- file_path
- Raises:
FileNotFoundErrorIf the file does not exist.
- 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,Itemsubclass, orTemplate.- query
str, default: “” ADR query string (e.g.
"A|i_tags|cont|dp=dp227;").- **kwargs
Any Additional keyword arguments forwarded to
.find.
- Returns:
ObjectSetQuery results wrapped in
ObjectSet.
- Raises:
TypeErrorIf
query_typeis 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:
- Returns:
strRendered HTML content (media type
text/html).
- Raises:
ADRExceptionIf 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:
- Returns:
bytesPDF document bytes (media type
application/pdf).
- Raises:
ADRExceptionIf 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
PPTXLayoutare supported.- Parameters:
- Returns:
bytesPPTX document bytes (media type
application/vnd.openxmlformats-officedocument.presentationml.presentation).
- Raises:
ADRExceptionIf 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.
- setup(collect_static: bool = False) None#
Configure Django and perform ADR initialization.
This method:
Optionally locates and imports the
envemodule for geometry.Adds the Nexus Django directory to
sys.pathand 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
SessionandDataset.
- Parameters:
- collect_staticbool,
optional If
True, runcollectstaticinto_static_directory.
- collect_staticbool,
- Raises:
ImportErrorIf the Nexus Django settings could not be imported.
DatabaseMigrationErrorIf migrations fail on any database.
GeometryMigrationErrorIf geometry update checks fail.
ImproperlyConfiguredErrorIf settings or required paths are invalid.
StaticFilesCollectionErrorIf
collectstaticfails.