我在Flask
中使用Python
框架。我写了这段代码:
from flask import *
import mysql.connector
def connect_db():
db = mysql.connector.Connect(host='***',user='***',password='**',database='***')
return db.cursor()
def query_db(query, args=(), one=False):
cur = g.db
cur.execute(query, args)
rv = [dict((cur.description[idx][0], value)
for idx, value in enumerate(row)) for row in cur.fetchall()]
return (rv[0] if rv else None) if one else rv
@app.before_request
def before_request():
g.db = connect_db()
blogOptions = query_db('select * from tbl_options',None)
@app.route("/")
def index():
return render("index.html")
当我运行此代码时。它说
ReferenceError: weakly-referenced object no longer exists
带回溯:
Traceback (most recent call last):
File "/Users/ozcan/Documents/python/venv/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "/Users/ozcan/Documents/python/venv/lib/python2.7/site-packages/flask/app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/Users/ozcan/Documents/python/venv/lib/python2.7/site-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/Users/ozcan/Documents/python/venv/lib/python2.7/site-packages/flask/app.py", line 1360, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/ozcan/Documents/python/venv/lib/python2.7/site-packages/flask/app.py", line 1356, in full_dispatch_request
rv = self.preprocess_request()
File "/Users/ozcan/Documents/python/venv/lib/python2.7/site-packages/flask/app.py", line 1539, in preprocess_request
rv = func()
File "/Users/ozcan/Documents/python/app.py", line 124, in before_request
blogOptions = query_db('select * from tbl_options',None)
File "/Users/ozcan/Documents/python/app.py", line 47, in query_db
cur.execute(query, args)
File "/Users/ozcan/Documents/python/venv/lib/python2.7/site-packages/mysql/connector/cursor.py", line 364, in execute
if self._have_unread_result():
File "/Users/ozcan/Documents/python/venv/lib/python2.7/site-packages/mysql/connector/cursor.py", line 193, in _have_unread_result
return self._connection.unread_result
ReferenceError: weakly-referenced object no longer exists
我该如何解决这个问题?
答案 0 :(得分:1)
您在此处创建的连接对象正在函数末尾的垃圾收集中被拾取,并且在光标稍后引用它时不再存在:
def connect_db():
db = mysql.connector.Connect(host='***',user='***',password='**',database='***')
return db.cursor()
您可以将其退回或存储在g
中,以便在请求的生命周期内存在。