1

我正在尝试在服务器上部署基于烧瓶的应用程序,但是我遇到了问题。基本处理程序似乎工作正常,但是我连接到 MySQL 的处理程序给了我错误 500。

我使用 apache 和 mod_wsgi 将这个应用程序部署为 Debian linux 上的用户烧瓶。我以该用户身份登录并尝试在不同的端口上手动运行该应用程序,然后它运行得非常好。

我检查了烧瓶日志,这是我看到的错误:

[Sun Jan 13 14:33:27 2013] [error] [20130113-14:33PM] [susyapi] [ERROR] Exception on /1/product [GET]
[Sun Jan 13 14:33:27 2013] [error] Traceback (most recent call last):
[Sun Jan 13 14:33:27 2013] [error]   File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 1687, in wsgi_app
[Sun Jan 13 14:33:27 2013] [error]     response = self.full_dispatch_request()
[Sun Jan 13 14:33:27 2013] [error]   File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 1360, in full_dispatch_request
[Sun Jan 13 14:33:27 2013] [error]     rv = self.handle_user_exception(e)
[Sun Jan 13 14:33:27 2013] [error]   File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 1358, in full_dispatch_request
[Sun Jan 13 14:33:27 2013] [error]     rv = self.dispatch_request()
[Sun Jan 13 14:33:27 2013] [error]   File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 1344, in dispatch_request
[Sun Jan 13 14:33:27 2013] [error]     return self.view_functions[rule.endpoint](**req.view_args)
[Sun Jan 13 14:33:27 2013] [error]   File "/home/pisarzp/susyapi/susyapi.py", line 36, in product_search
[Sun Jan 13 14:33:27 2013] [error]     cur = db.cursor()
[Sun Jan 13 14:33:27 2013] [error] NameError: global name 'db' is not defined

该应用程序的代码如下:

from flask import Flask, url_for, session, redirect, escape, request
from subprocess import Popen, PIPE
import socket
import MySQLdb
import urllib
import json
from datetime import datetime
import decimal
import settings
import logging

@app.route('/')
def api_root():
    return '200 OK test'

@app.route('/version')
def version():
    return '200 OK <BR>Version 0.1'

@app.route('/1/product')
def product_search():
    #get the request parameters
    product_code = request.args.get('code')
    product_code = urllib.unquote(product_code)

    #Fetching all product code from database
    cur = db.cursor() #This is where I get error
    query = "SELECT code from %s GROUP BY 1;" % (settings.DB_PRODUCTS_TABLE)
    cur.execute(query)
    rows = cur.fetchall()

    #Not important part which I cut out
    #...
    # End of cut

    #returning JSON with best matching products info
    products_json = []
    for code in best_matching_codes:
        cur = db.cursor()
        query = "SELECT * FROM %s WHERE code LIKE '%s'" % (settings.DB_PRODUCTS_TABLE, code)

        cur.execute(query)
        columns = [desc[0] for desc in cur.description]
        rows = cur.fetchall()
        for row in rows:
            products_json.append(dict((k,v) for k,v in zip(columns,row)))   

    return json.dumps(products_json, default = date_handler)


logging.basicConfig(
    level=logging.DEBUG,
    format='[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s',
    datefmt='%Y%m%d-%H:%M%p',
)
if __name__ == '__main__':
    app.debug = False
    db=MySQLdb.connect(host=settings.DB_HOST, user=settings.DB_USER, passwd=settings.DB_PASSWD, db=settings.DB_NAME)
    app.run()

-----已编辑----

我在反馈后添加了以下更改:

def connect_db():
    db_conn = MySQLdb.connect(host=settings.DB_HOST,user=settings.DB_USER,passwd=settings.DB_PASSWD,db=settings.DB_NAME)
    return db_conn

@app.before_request
def db_connect():
    g.db = connect_db()
@app.teardown_request
def db_disconnect(exception=None):
    g.db.close()

但我仍然收到错误:

File "/Users/pisarzp/Desktop/SusyChoosy/susyAPI/susyapi.py", line 84, in db_disconnect
g.db.close()
NameError: global name 'g' is not defined

尝试谷歌搜索,但找不到任何东西。有什么建议吗?

4

1 回答 1

4

mod_wsgi 忽略条件后的代码块if __name__ == '__main__',您需要在其他地方设置数据库连接。一个好地方是before_requestteardown_request处理程序,所以你的连接是为每个请求建立和处理的,否则你会遇到麻烦,因为 MySQL 会丢弃长期存在的连接:

from flask import g

@app.before_request
def db_connect():
    g.db_conn = MySQLdb.connect(host=settings.DB_HOST,
                                user=settings.DB_USER,
                                passwd=settings.DB_PASSWD,
                                db=settings.DB_NAME)

@app.teardown_request
def db_disconnect(exception=None):
    g.db_conn.close()
于 2013-01-14T10:43:45.410 回答