我正在尝试使用Flask_SQLAlchemy在我的app.config['SQLALCHEMY_DATABASE_URI']
外部数据库是用户输入,因此我无法猜测每个用户的数据库结构
我已允许
在用户数据库和我的系统之间建立连接@app.route('/test')
def test():
engine = db.create_engine(USER_DB)
Session = db.sessionmaker(bind=engine)
session = db.scoped_session(engine)
#after that i was able to get the table name's and structure using
x = {table:db.Table(table,db.metadata,autoload=True,autoload_with=engine)
for table in engine.table_names()}
print(f'\n\n x = {x} \n\n')
findme = session.query(test1.filter_by(id=1).first())
控制台:
x = {'test1': Table('test1', MetaData(bind=None), Column('id', INTEGER(), table=<test1>, nullable=False, server_default=DefaultClause(<sqlalchemy.sql.elements.TextClause object at 0x000001F83BCAEC50>, for_update=False)), Column('name', VARCHAR(), table=<test1>, nullable=False), schema=None), 'test2': Table('test2', MetaData(bind=None), Column('id2', INTEGER(), table=<test2>, nullable=False, server_default=DefaultClause(<sqlalchemy.sql.elements.TextClause object at 0x000001F83BCCEA58>, for_update=False)), Column('name2', VARCHAR(length=200), table=<test2>, nullable=False), schema=None)}
您可以看到它可以读取其中的列的结构
然后其余的输出:
(追溯)
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1997, in __call__
return self.wsgi_app(environ, start_response)
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1985, in wsgi_app
response = self.handle_exception(e)
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1540, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1982, in wsgi_app
response = self.full_dispatch_request()
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\_compat.py", line 33, in reraise
raise value
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
rv = self.dispatch_request()
File "C:\ProgramData\Anaconda3\lib\site-packages\flask\app.py", line 1598, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "D:\app1\app.py", line 181, in test
cc = session.query(test1.filter_by(id=1).first())
NameError: name 'test1' is not defined
如何允许 SQLALCHEMY 自动定义结构?有那些
*自动映射/反射/ python包“ sqlacodegen” * 在这种情况下很有用,如果可以,我如何从中受益?