简体   繁体   中英

Use connection to db in another file

How can I use initialized connection in python to database in one file and use in another file

For example,
db_connect.py

from sqlalchemy import create_engine, Column
from clickhouse_sqlalchemy import get_declarative_base, types, make_session

def get_connection(uri):
    engine = create_engine(uri)
    session = make_session(engine)
    return session

main.py

from db_connect import get_connection

uri = 'clickhouse://default:@*.*.*.*:8123/my_table'
session = get_connection(uri)

connection_use.py

# Here I want to use my initialized conneciton `session` 
a = session.query(...).filter_by(...)

I want to do it, because init process takes a lot of time, and I do queries many times in different places. May be use this connection as a class? But I still init it in main.py

Move session = get_connection(uri) into db_connect.py (the end). This way session is initialized when db_connect is imported for the first time.

in connection_use.py:

from .db_connect import session

a = session.query(...)

Note: This is not the prettiest pythoniest way to do it, just the minimal changes to make your example work. Also the import statement assumes python 3 and db_connect in the same directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM