Skip to content

Create direct submission function #27

Description

@jchate6

Users may want to automate message submission.
This will require some infrastructure and documentation:

  • Build direct submission method
  • Update README describing how to incorporate this into custom code.

Incorporate something like the following to publisher.py

def publish_to_hermes(message_info, datums=None, targets=None, *, user=None, **kwargs):
    """POST a fully-assembled HERMES message to ``/api/v0/submit_message/``.
    """
    if targets is None:
        targets = Target.objects.none()
    if datums is None:
        datums = []

    creds = resolve_hermes_credentials(user)
    if not creds.get('api_key'):
        return {'message': (
            'No HERMES API key available. Configure either per-user credentials on '
            "the user's HermesProfile page, or TOM-wide credentials at "
            "settings.HERMES_CONFIGURATION['HERMES_API_TOKEN']."
        )}
    if not creds.get('base_url'):
        return {'message': (
            'No HERMES BASE_URL configured. Set settings.HERMES_CONFIGURATION["HERMES_BASE_URL"].'
        )}

    stream_base_url = creds['base_url']
    submit_url = stream_base_url + 'api/v0/submit_message/'
    headers = {'Authorization': f"Token {creds['api_key']}"}

    # Build the HERMES-schema JSON body from the TOM models.
    try:
        message = create_hermes_message(message_info, datums, targets, **kwargs)
    except HermesMessageException as e:
        return {'message': 'ERROR: ' + str(e)}

    # Submit. If the POST or the status check raises, surface the HTTP
    # response to the caller so they can inspect it; don't crash the
    # request-handling view.
    response = None
    try:
        response = requests.post(url=submit_url, json=message, headers=headers)
        response.raise_for_status()
    except Exception as ex:
        logger.error(repr(ex))
        if response is not None:
            logger.error(response.content)
        return response if response is not None else {'message': f'ERROR: {ex!r}'}

    # Log a one-line summary of the successful publish. Without this the
    # only operator-visible signal in the runserver log is the bare
    # ``POST /share/ ... 302`` from Django's request log; the
    # HERMES-assigned uuid (the message id we publish under) is otherwise
    # invisible to the operator.
    message_uuid = response.json().get('uuid', '<no-uuid>')
    logger.info(
        f'publish_to_hermes: published topic={message_info.topic} '
        f'message_uuid={message_uuid}'
    )
    return response

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    Status
    Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions