GridtNetwork / gridtlib

Core library for the gridt network
0 stars 0 forks source link

Session management #9

Open Drvanon opened 4 years ago

Drvanon commented 4 years ago

The repetition of session creation is unhealthy, the responsibility should be moved to the caller. A new class needs to be created that stores both the session as well as any configuration. It should provide a context in which the session could be worked with. All controllers should accept this ControllerManager and should find the session in it. Here is a mock up:

# custom-resource.py
from flask import current_app
from gridtlib import Controller
from gridtlib.custom_mod import query_func, write_func

class CustomResource(Resource):
    def post(self):
        with Controller(config=current_app.config) as cont:
            q = query_funct(arg1, arg2, cont)
            resp = write_func(arg3, q.arg4, cont)
            return resp

# gridtlib.py
from contextlib import AbstractContextManager
from .helpers import session_scope

class Controller(ContextDecorator):
    session = None
    config = None

    def __init__(self, config: dict = config):
        self.config = config

    def __enter__(self):
        self.session = Session()

    def __exit__(self, *exc_details):
        if exc_details[0]:
            self.session.rollback()
        else:
            self.session.commit()
        self.session.close()

def query_func(arg1, arg2, cont):
    return cont.session.query(Model).filter_by(arg=arg1, other=arg2).all()

def write_func(arg3, cont):
    mod = Model(arg3, cont.config["some_option"])
    cont.session.add(mod)
    cont.session.commit()
    return mod.id