简体   繁体   中英

Trouble Implementing Database Connection states with Python/Flask/MySQL

I'm building a web site with Python/Flask/MySQL on the PythonAnywhere platform. I've had this working with the DB previously (read: db connections are not the ask here, it's the setup/configuration and calling), however I want to change this to be more in-line with Web Development (ie Application/Request Contexts).

I've had few attempts at different configurations based on the documentation and other posts (such as this one: Connect to a Database in Flask, Which Approach is better? ). Although very informative, I'm still having trouble implementing this successfully and hoping someone can point out why it's not working.

I'm trying to keep things simple so have everything at the moment in one MyApp.py file, which looks like this:

from flask import Flask, render_template, session, request, redirect, url_for, g
from flask.ext.mysql import MySQL

app = Flask(__name__, static_url_path='')
app.config["DEBUG"] = True

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

@app.teardown_appcontext
def teardown_db(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        db.close()

def connect_to_database():
    mysql = MySQL()
    app.config['MYSQL_DATABASE_USER'] = '{db_user}'
    app.config['MYSQL_DATABASE_PASSWORD'] = '{db_password}'
    app.config['MYSQL_DATABASE_DB'] = '{db}'
    app.config['MYSQL_DATABASE_HOST'] = '{dbhost}'
    dbcon = mysql.connect()
    return dbcon

@app.route('/', methods=["GET", "POST"])
def index():
    db_conn = get_db()
    cursor = db_conn.cursor()
    #... do my SQL stuff here ...#
    return render_template("home_guest.html")

It fails when it reaches the mysql.connect() function and I can't work out why. Here is the error logs from the Python Anywhere server:

2017-06-20 02:03:23,228: Error running WSGI application
2017-06-20 02:03:23,230: AttributeError: 'NoneType' object has no attribute 'config'
2017-06-20 02:03:23,230:   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 2000, in __call__
2017-06-20 02:03:23,230:     return self.wsgi_app(environ, start_response)
2017-06-20 02:03:23,231: 
2017-06-20 02:03:23,231:   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1991, in wsgi_app
2017-06-20 02:03:23,231:     response = self.make_response(self.handle_exception(e))
2017-06-20 02:03:23,231: 
2017-06-20 02:03:23,231:   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1567, in handle_exception
2017-06-20 02:03:23,232:     reraise(exc_type, exc_value, tb)
2017-06-20 02:03:23,232: 
2017-06-20 02:03:23,232:   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1988, in wsgi_app
2017-06-20 02:03:23,232:     response = self.full_dispatch_request()
2017-06-20 02:03:23,232: 
2017-06-20 02:03:23,232:   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1641, in full_dispatch_request
2017-06-20 02:03:23,232:     rv = self.handle_user_exception(e)
2017-06-20 02:03:23,232: 
2017-06-20 02:03:23,232:   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1544, in handle_user_exception
2017-06-20 02:03:23,233:     reraise(exc_type, exc_value, tb)
2017-06-20 02:03:23,233: 
2017-06-20 02:03:23,233:   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1639, in full_dispatch_request
2017-06-20 02:03:23,233:     rv = self.dispatch_request()
2017-06-20 02:03:23,233: 
2017-06-20 02:03:23,233:   File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1625, in dispatch_request
2017-06-20 02:03:23,233:     return self.view_functions[rule.endpoint](**req.view_args)
2017-06-20 02:03:23,233: 
2017-06-20 02:03:23,233:   File "/home/WazzalJohn/mysite/flask_app.py", line 83, in login
2017-06-20 02:03:23,234:     conn = get_db()
2017-06-20 02:03:23,234: 
2017-06-20 02:03:23,234:   File "/home/WazzalJohn/mysite/flask_app.py", line 15, in get_db
2017-06-20 02:03:23,234:     db = g._database = connect_to_database()
2017-06-20 02:03:23,234: 
2017-06-20 02:03:23,234:   File "/home/WazzalJohn/mysite/flask_app.py", line 40, in connect_to_database
2017-06-20 02:03:23,234:     dbcon = mysql.connect()
2017-06-20 02:03:23,234: 
2017-06-20 02:03:23,235:   File "/home/WazzalJohn/.local/lib/python2.7/site-packages/flaskext/mysql.py", line 39, in connect
2017-06-20 02:03:23,235:     if self.app.config['MYSQL_DATABASE_HOST']:

Any suggestions or help would be appreciated, thank you.

You have to call init_app to initialize the app for use with MySQL class. Then access the connection from the extension. This does not go in a function.

mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = '{db_user}'
app.config['MYSQL_DATABASE_PASSWORD'] = '{db_password}'
app.config['MYSQL_DATABASE_DB'] = '{db}'
app.config['MYSQL_DATABASE_HOST'] = '{dbhost}'
mysql.init_app(app)

@app.route('/')
def index():
    c = mysql.connection.cursor()
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM