python-microservices / pyms

Library of utils to create REST Python Microservices
https://python-microservices.github.io/home/
GNU General Public License v3.0
265 stars 45 forks source link

How do I get the database after the application is ready? #224

Closed leandrohmvieira closed 3 years ago

leandrohmvieira commented 3 years ago

I created an Database connection on the init_libs:

    def init_libs(self) -> None:
        with self.application.test_request_context():
            self.db_client = db.get_db_client()

I see on the debugger that this object is stored on the app.ms.db_client

But now I don't know how to get this object from my API folder, current_app and g give me a "localproxy unbound", and I don't see anyway to get the application context or the app instance itself from elsewhere. Can I have a little bit help on this?

alexppg commented 3 years ago

It's not available on your app class? For example:

from flask_babel import Babel
from pyms.flask.app import Microservice

class MyMicroservice(Microservice):
    def init_libs(self):
        with self.application.test_request_context():
            self.db_client = db.get_db_client()

ms = MyMicroservice()
app = ms.create_app()
# Do stuff with app.db_client

As far as I understand, db_client should be available on app.db_client. Isn't it?

leandrohmvieira commented 3 years ago

After some work, I was able to get through it, but I don't think this is the best solution yet.

I'm building my ms on top of the scaffold pyms project, so I want to access my db_client from the views files, so at the start, I was trying to get the db_client from the __init__.py and put it in a constant, so every view could access it by import the module, but looks like the application context is not there yet when I start the server, so I have worked around like this:

import json
from flask import current_app as app

def get_datasets() -> json:

    datasets = app.ms.db_client.get_datasets()

    return json.dumps(datasets)

Is this right? I've tried the flask init_app(app) thing, but I don't find my get_db() function on the g object after

avara1986 commented 3 years ago

Hi @leandrohmvieira The Flask instance is in self.application. If you want to initialize a lib like a tipical flask app, you can create db_client in self.application like this:

    def init_libs(self) -> None:
        with self.application.test_request_context():
            self.application.db_client = db.get_db_client() # <!----

By this way, you could find db_client in app

There is an other example: https://github.com/python-microservices/microservices-scaffold/blob/master/project/app.py#L31

I hope this help you :smile:

leandrohmvieira commented 3 years ago

Thank you for the help guys, my boss decided to switch to FastAPI after all, sigh