0

我有 2 个 py 文件。database.pymyapp.py。从 开始myapp.py,我想调用database.py以创建连接,并执行 mysql 查询,但我不希望关闭与数据库的连接,因为我需要重用它。这是我的代码。

谁能给我一些建议?

数据库.py

import mysql.connector
from flask import g

def connect_db():
    return mysql.connector.connect(user='root', password='password', database='test')

def get_db():
    db = getattr(g, '_database', None)
    if db is None:
        #db = g._database = connect_to_database()
        db = g._database = connect_db()
    return db    

def query_db(query, args=(), one=False):
    cur = get_db().execute(query, args)
    rv = cur.fetchall()
    cur.close()
    return (rv[0] if rv else None) if one else rv

我的应用程序.py

from flask import g
from database import connect_db, query_db

for user in query_db('select * from users'):
    print(user['userid'], 'has the password', user['password'])

这是完整的跟踪

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    for user in query_db('select * from users'):
  File "/root/projects/test2/database.py", line 15, in query_db
    cur = get_db().execute(query, args)
  File "/root/projects/test2/database.py", line 8, in get_db
    db = getattr(g, '_database', None)
  File "/opt/python3/lib/python3.3/site-packages/werkzeug/local.py", line 338, in __getattr__
    return getattr(self._get_current_object(), name)
  File "/opt/python3/lib/python3.3/site-packages/werkzeug/local.py", line 297, in _get_current_object
    return self.__local()
  File "/opt/python3/lib/python3.3/site-packages/flask/globals.py", line 27, in _lookup_app_object
    raise RuntimeError('working outside of application context')
RuntimeError: working outside of application context
4

1 回答 1

0

您应该为您的 query_db 函数创建一个应用程序上下文。另请参阅: 如何在不发布的情况下从 Flask 修改数据库?

于 2013-09-26T12:03:28.640 回答