I have a project with FastAPI but I don't want to use SQLAlchemy or another ORM because I think it's not necessary to install extra dependencies for my queries, these are simple SELECT
operations. I have my routes in separated files, I want to know how to use my connection object returned by psycopg2 in a way that I can use it for executing my SQL statements in my different files (something like a global object). I have read about ContextVars but I don't know if this can work. For now, I have a solution, I create my connection object in a separate file and then, I import the object in my route files but maybe there is another way I can do it.
Asked
Active
Viewed 3,971 times
2

Carmoreno
- 1,271
- 17
- 29
1 Answers
4
That's the exact way of doing it.
Create an instance of a connection (or connection pool) at application startup in a module and share it with the rest of your app by importing it whenever needed.

lsabi
- 3,641
- 1
- 14
- 26
-
Thanks Isabi, I'm new with FastAPI, I see you have more experience than me with this framework. So I'm going to follow with this approach, thank you. – Carmoreno Jan 15 '21 at 15:33
-
1That's a typical approach that is used with also other frameworks for such kind of things. Though my suggestion is to use this approach for small things and an ORM for bigger things. Also, be sure that the shared connection (or pool) has been already awaited if it's an async connection – lsabi Jan 15 '21 at 17:23