Skip to content
UCLALibraryPublic

About

DLux: UCLA Digital Library metadata management application

Resources

Stars

1 star

Watchers

1 watching

Forks

Repository files navigation

DLux

This is a Django application for managing digital library metadata.

System Architecture

  • basics: dlux uses standard Django models to define data types, and the django admin site as the primary management interface.
  • won't write any views, but will make liberal use of django's admin site customizations. [link to admin site docs]
  • how it's different: organized first by field

Field-first organization

Basic Django paradigm: organize first by concern (e.g. MVC: models.py, fields.py, admin.py,)

experience w/ Californica: we work mainly by field, thus a given task requires synchrinizing work across a bunch of files

alternate ways of organizing: react / vue components -> still keep javascript, html, and css parts separate (and separate e.g. state from logic within js) -> BUT only within a limited-scope component. Easy to jump back and forth between

Principles

  • define everyting in dluxfield objects, somewhere separate from the typical django models.py, admin.py, etc.
  • most of the attributes of DluxField should be basic Django types, for example Field subclasses, or
  • in models.py, admin.py, and other django files, programmatically generate everything by combining elements from DluxField

Implications

Type checking / IDE autocompletes

good for typing the basic django types that go into the DluxField objects

won't know attributes of models - for example, won't autocomplete Work.ti to Work.title. This is actually okay, because we shouldn't actually be referring directly to these in the code! Instead, we should be iterating over DLuxField objects and programmatically creating whatever needs to be created

in the django console, on the other hand, autocompletion is based on Django introspecting the fully created models, so we can use it to explore the actual fields of individual models / records

Example

models.py:

from django.db.models import CharField, IntegerField, Model
from dlux.fields import DluxField, FieldGroup, with_field_groups

# DLux-specific, stuff, organized by fields

class CharacterMetadata(FieldGroup):
    name = DluxField(
        django = CharField(max_length=200),
        csv = ["Name"],
        solr = ["name_tesi"],
    )

class MinionMetadata(FieldGroup):
    n_eyes = DluxField(
        django = IntegerField(),
        csv = ["Eyes"],
        solr = ["eyes_isi"],
    )

# Create django objects based on the FieldGroup and DluxField objects

@with_field_groups(CharacterMetadata, MinionMetadata)
class Minion(Model):
    # Don't need this in practice, only here since we're not in models.py
    class Meta:
        app_label="dlux"

From the django shell you could then run:

>>> james = Minion(name="James", n_eyes=1)
>>> james.name
"James"

>>> james.n_eyes
1

>>> james._meta.get_fields()
(<django.db.models.fields.BigAutoField: id>, <django.db.models.fields.CharField: name>,
<django.db.models.fields.IntegerField: n_eyes>)

Conventions

Django Field types in dlux_fields.py

All fields are defined in dlux_fields.py as DluxField objects. Each DluxField object has a django attribute, which is a standard Django field type (e.g., CharField, TextField, IntegerField, etc.). The other attributes of the DluxField object are used to define mappings for different data sources (e.g. CSVs and Solr).

Regarding the django attribute, the convention for usage of CharField and TextField is as follows:

  • Use CharField for singular (i.e. non-multivalue) textual fields where an HTML text input box is most appropriate for data entry in the admin UI. Django renders a text input by default for CharField.
  • Use TextField for singular (i.e. non-multivalue) textual fields where an HTML textarea is most appropriate for data entry in the admin UI. Django renders a textarea by default for TextField.
  • For multivalue textual fields that make use of our custom extension of ArrayField from the django-jsonform library, use TextField as the base field within ArrayField, for consistency's sake. The ArrayField accepts a schema attribute, which can be used to specify the widget to render for the TextField base field, defaulting to a basic text input. To instead render a textarea, for example:
description = DluxField(
    django=ArrayField(
        TextField(),
        blank=True,
        default=list,
        schema={
            "type": "list",
            "items": {
                "type": "string",
                "widget": "textarea",  # This is where the textarea widget is specified
            },
        },
    ),
    csv=["Description.note"],
    solr=["description_tesim"],
)

See the django-jsonform docs for more information on the schema attribute and available widgets.

Developer Information

Overview of environment

The development environment requires:

  • git (at least version 2)
  • docker(version 25+) and docker compose (version 2+)

Dev container

This project comes with a basic dev container definition, in .devcontainer/devcontainer.json. It's known to work with VS Code, and may work with other IDEs like PyCharm. For VS Code, it also installs the following extensions:

  • Python (which includes our type checker, pyright, as part of the pylance language server)
  • ruff (formatter and linter)
  • tamasfe.even-better-toml (linter for toml config files)
  • redhat.vscode-yaml (schema-aware yaml linter)

When prompted by VS Code, click "Reopen in container". This will (re)build the Django container, dlux-django. It will also (re)build a copy of that container, vsc-dlux-<long_hash>-uid, install VS Code development tools & extensions within that container, and start the docker compose system. VS Code will be connected to the Django container, with all code available for editing in that context.

Problems
  • If VS Code says "No Python found" and offers to have uv install it, click either "Don't ask me any more" (or similar), or "No/Cancel". The combination of VS Code + uv + dev containers can cause this. Python is present in the container, which is what matters here.
  • If running on Linux / WSL, starting the system via docker compose up for the first time will create a .venv directory in your local project folder. This .venv directory may be owned by root. This is caused by the anonymous VOLUME specified in the Dockerfile. This is harmless, but may be annoying; if so, chown your_user:your_user .venv will fix it, and the permissions should not revert to root on subsequent runs.

The project's directory is available within the container at /home/django/django_app.

PostgreSQL container

The development database is a Docker container running PostgreSQL 16, which matches our deployment environment.

Django container

This uses Django 5.2, in a Debian 12 (Bookworm) container running Python 3.13. All code runs in the container, so local version of Python does not matter.

The container runs via docker_scripts/entrypoint.sh, which

  • Updates container with any new requirements, if the image hasn't been rebuilt (DEV environment only).
  • Waits for the database to be completely available. This can take 5-10 seconds, depending on your hardware.
  • Applies any pending migrations (DEV environment only).
  • Creates a generic Django superuser, if one does not already exist (DEV environment only).
  • Starts the Django application server.

Setup

  1. Build using docker compose.

    $ docker compose build

  2. Bring the system up, with containers running in the background.

    $ docker compose up -d

  3. Logs can be viewed, if needed (-f to tail logs).

    $ docker compose logs -f db
    $ docker compose logs -f django
    
  4. Run commands in the containers, if needed.

    # Open psql client in the dev database container
    $ docker compose exec db psql -d django_db -U django_db
    # Open a shell in the django container
    $ docker compose exec django bash
    # Django-aware Python shell
    $ docker compose exec django python manage.py shell
    # Apply new migrations without a restart
    $ docker compose exec django python manage.py migrate
    # Populate database with sample data (once it exists...)
    $ docker compose exec django python manage.py loaddata --app DJANGO_APP_NAME FIXTURE_NAME
    
  5. Connect to the running application via browser

    Application and Admin

  6. Edit code locally. All changes are immediately available in the running container, but if a restart is needed:

    $ docker compose restart django

  7. Shut down the system when done.

    $ docker compose down

Loading data

Add application-specific instructions here.

Logging

Basic logging is available, with logs captured in logs/application.log. At present, logs from both the custom application code and Django itself are captured.

Logging level is set to INFO via .docker-compose_django.env. If there's a regular need/desire for DEBUG level, we can discuss that.

How to log

Logging can be used in any Python file in the project. For example, in views.py:

# Include the module with other imports
import logging
# Instantiate a logger, generally before any functions in the file
logger = logging.getLogger(__name__)

def my_view():
    logger.info('This is a log message from my_view')

    query_results = SomeModel.objects.all()
    for r in query_results:
        logger.info(f'{r.some_field=}')

    try:
        1/0
    except Exception as e:
        logger.exception('Example exception')

    logger.debug('This DEBUG message only appears if DJANGO_LOG_LEVEL=DEBUG')

Log format

The current log format includes:

  • Level: DEBUG, INFO, WARNING, ERROR, or CRITICAL
  • Timestamp via asctime
  • Logger name: to distinguish between sources of messages (django vs the specific application)
  • Module: somewhat redundant with logger name
  • Message: The main thing being logged

Viewing the log

Local development environment: view logs/application.log.

In deployed container:

  • /logs/: see latest 200 lines of the log
  • /logs/nnn: see latest nnn lines of the log

Testing

Tests focus on code which has significant side effects or implements custom logic. Run tests in the container:

$ docker compose exec django python manage.py test

Preparing a release

Our deployment system is triggered by changes to the Helm chart. Typically, this is done by incrementing image:tag (on or near line 9) in charts/prod-<appname></appname>-values.yaml. We use a simple semantic versioning system:

  • Bug fixes: update patch level (e.g., v1.0.1 to v1.0.2)
  • Backward compatible functionality changes: update minor level (e.g., v1.0.1 to v1.1.0)
  • Breaking changes: update major level (e.g., v1.0.1 to v2.0.0)

In addition to updating version in the Helm chart, update the Release Notes in release_notes.html. Put the latest changes first, following the established format.

Management Commands

Eureka-dlux field comparison command

The compare_fields_with_eureka management command compares local fields with those in Eureka, using a CSV report of all Eureka fields. The command categorizes fields into known mappings, likely mappings, those requiring human review, and empty Eureka fields.

To run the command, use:

$ docker compose exec django python manage.py compare_fields_with_eureka

By default, this outputs a JSON report to stdout. Other options are available:

`-f, --format {json|markdown}`: Specify the output format of the report. Supported formats are JSON and Markdown. The default is `json`.
`-o, --output PATH`: Specify the file path to write the report. If not provided, the report is printed to `stdout`.

About

DLux: UCLA Digital Library metadata management application

Resources

Stars

1 star

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages