2

私は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

この問題を解決するにはどうすればよいですか?

4

1 に答える 1

2

ここで作成する接続オブジェクトは、関数の最後でガベージ コレクションによって取得され、カーソルが後で参照すると存在しなくなります。

def connect_db():   
        db = mysql.connector.Connect(host='***',user='***',password='**',database='***')
        return db.cursor()

gリクエストの有効期間中存在するように、それを返すか保存することができます。

于 2013-03-08T17:34:24.323 に答える