Skip to main content

mentorHub-utils

PyPi install

pipenv install mentorhub-utils

Overview

These utilities support the mentorHub platform.

Table of Contents

Flask Utilities

This is a collection of simple Flask utilities:

  • MongoJSONEncoder converts ObjectID and datetime values to strings
  • create_token() builds a Roles Based Access Control (RBAC) token
  • create_breadcrumb(token) builds the breadcrumb used when updating the database

Usage

MongoJSONEncoder

This is a helper class that allows the flask.json method to properly handle ObjectID and datetime values by converting them to strings.

from flask import Flask
from mentorhub_utils import MongoJSONEncoder

# Initialize Flask App
app = Flask(__name__)
app.json = MongoJSONEncoder(app)

# In flask request handler
from flask import jsonify
print jsonify(dict)

Tokens

All API's will be secured with industry standard bearer tokens used to implement Role Based Access Control (RBAC). The create_token method will decode the token and extract claims for a user_id and roles, throwing an exception if the token is not found or not properly encoded.

{
    "user_id": "The users PersonID",
    "roles": ["Staff", "Mentor", "Member"]
}

Valid roles are listed in the mentorhub-mongodb repo's enumerators file but the roles listed above are the only one's currently used in the mentorHub platform.

Breadcrumbs

All database collections include a lastModified "breadcrumb" property used to track changes over time. The breadcrumb has the following properties:

{
        "atTime": "date-time the document was last modified",
        "byUser": "UserID claim from the access token",
        "fromIp": "IP Address the request originated at",  
        "correlationId": "A correlationID to use in logging"
}

Example

Here is how these methods are used in a Flask Route Handler

from mentorhub_utils import create_breadcrumb, create_token
token = create_token()
breadcrumb = create_breadcrumb(token)
MyService.doSomething(myData, ..., token, breadcrumb)
logger.info(f"Did Something completed successfully {breadcrumb.correlationId}")

Config Utilities

This is collection of utilities to support API Configuration in a standard way

  • Mentorhub_Config handles configuration values
  • config_routes() is a Flask request handler

Usage

Standard Config

Config

Standard mental hub configuration values. Configurations are managed in a consistent way favoring file based configuration values, then environment, configuration values, and then default values. See the Mentorhub_Config.py for details on the configuration values.

config = Mentorhub_Config.get_instance()
print config.LOGGING_LEVEL

config_routes()

This is a simple flask request handler to be used to expose the config data on a config endpoint.

from flask import Flask
app = Flask(__name__)
config_handler = create_config_routes()
app.register_blueprint(config_handler, url_prefix='/api/config')

Mongo Utilities

Simple wrappers for MongoIO and a Config Initializer.

Usage

get_instance()

Get a reference to the Singleton object

mongo_io = MentorHubMongoIO.get_instance()

configure(enumerators_key)

This method will initialize the MongoIO singleton object, connect to the database, and update the Config.versions and Config.enumerators values. You should call this function when initializing the mongodb connection. This method takes as a parameter the primary collection name used to load enumerators.

mongo_io = Mentorhub_MongoIO.get_instance()
mongo_io.configure(config.MAIN_COLLECTION_NAME)

disconnect()

This Method will disconnect from the database in a graceful way. You should call this method when the server process is ending.

mongo_io = MentorHubMongoIO.get_instance()
mongo_io.disconnect()

get_documents(collection_name, match, project, order)

This is a convenience method to get a list of documents based on Mongo Match, project, and sort order parameters.

match = {"name": {"$regex": query}}
order = [('name', ASCENDING)]
project = {"_id":1,"name":1}
documents = mentorhub_mongoIO.get_documents("COLLECTION_NAME", match, project, order)

get_document(collection_name, string_id)

This is a convenience method to get a single document based on ID

document = mentorhub_mongoIO.get_document("COLLECTION_NAME", "_ID String")

create_document(collection_name, document)

This is a convenient method for creating a single document

document = {"foo":"bar"}
created = mentorhub_mongoIO.create_document("COLLECTION_NAME", document)

update_document(collection_name, _id, updates)

This is a convenience method for updating a single document based on ID

id = "24-byte-id"
patch = {"foo":"bar"}
updated = mentorhub_mongoIO.update_document("COLLECTION_NAME", id, patch)

delete_document(collection_name, string_id)

This is a convenience method for deleting a document based on ID. This is an actual live delete, not a soft delete.

id = "24-byte-id"
updated = mentorhub_mongoIO.delete_document("COLLECTION_NAME", id)

Contributing

If you want to contribute to this library, here are the instructions.

Prerequisites

Install Dependencies

pipenv install --dev

Run unit testing

pipenv run unit

Test setup.py package

pipenv run test

Clean package build path

pipenv run clean

Build the Package

pipenv run build

Twine check

To check if the package is ready to publish

pipenv run check

Publish the Package

You should successfully run clean, build and check before publishing.

pipenv run publish

NOTE: You will be prompted for PyPi authentication credentials. You should not need to use the command, it is used by the GitHub Actions CI.

Metadata

Release files for mentorhub-utils 1.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mentorhub-utils 1.1.0
File Size Uploaded
mentorhub_utils-1.1.0.tar.gz 20.6 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for mentorhub-utils 1.1.0
File Interpreter ABI Platform
mentorhub_utils-1.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 44.0 kB

Release files / mentorhub_utils-1.1.0.tar.gz

Download URL mentorhub_utils-1.1.0.tar.gz
Size 20.6 kB
Tags Source
SHA-256 checksum
How to use checksums
ccaaf78f6316acfc422db9c186679663f207fd4341ff5c78bb0e19c0b9ce15f2
BLAKE2b-256 checksum
How to use checksums
c14c2f99b52db2bc9dae81b539dd3c54101063a19fe1847a244ffb3ad7d528dd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.11

Release files / mentorhub_utils-1.1.0-py3-none-any.whl

Download URL mentorhub_utils-1.1.0-py3-none-any.whl
Size 23.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
648d3eb7183c252cf253ed5d700000acab0046e36a97f07dadbb8f0a3a95fb3b
BLAKE2b-256 checksum
How to use checksums
42b0acd99a0bdb1f764187b078e10dfb17d6dfaa44ee7ada8b69f79a4c2c12c2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.11

Release history Release notifications | RSS feed

This release

1.1.0 This release

2 release files

1.0.3

2 release files

1.0.2

2 release files

1.0.1

2 release files

1.0.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page