Closed leandrohmvieira closed 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?
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
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:
Thank you for the help guys, my boss decided to switch to FastAPI after all, sigh
I created an Database connection on the init_libs:
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?