Reputation: 2215
i use Flask
framework in Python
.I wrote this code:
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")
When i run this code.It says
ReferenceError: weakly-referenced object no longer exists
with the traceback:
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
How can i fix this issue?
Upvotes: 2
Views: 4410
Reputation: 5161
The connection object you create here is being picked up by garbage collection at the end of the function, and no longer exists when the cursor refers to it later:
def connect_db():
db = mysql.connector.Connect(host='***',user='***',password='**',database='***')
return db.cursor()
You can return it or store it in g
so it exists for the lifetime of the request.
Upvotes: 2