Skip to content

Instantly share code, notes, and snippets.

@tomdewildt
Created January 9, 2023 15:04
Show Gist options
  • Save tomdewildt/72c3df326593dae10107d2bc0e91bff2 to your computer and use it in GitHub Desktop.
Save tomdewildt/72c3df326593dae10107d2bc0e91bff2 to your computer and use it in GitHub Desktop.
Common constructs for the python programming language
# Resources
resources = Blueprint("api", __name__, url_prefix="/api")
def example_interactions():
return ExampleInteractions(**flask.current_app.repositories)
@resources.route("/list/", methods=["GET"])
def example_db_list_endpoint():
return jsonify(example_interactions().list())
@resources.route("/store/", methods=["POST"])
def example_db_store_endpoint():
return example_interactions().store(flask.request.json)
# Interactions
class ExampleInteractions:
def __init__(self, **repositories):
self._database_repository = repositories["database_repository"]
def list(self):
return [m.to_dict() for m in self._database_repository.list_models()]
def store(self, data):
model = Model(input=data["input"], output=data["output"])
return self._database_repository.store_model(model).to_dict()
# Repositories
class ExampleDatabaseRepository:
def __init__(self, session):
self._session = session
def list_models(self):
return self._session.query(Model)
def store_model(self, model):
self._session.add(model)
self._session.commit()
return model
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment