python 测试Flask-SQLAlchemy的MySQL数据库连接

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 测试Flask-SQLAlchemy的MySQL数据库连接相关的知识,希望对你有一定的参考价值。

#!/Users/username/Documents/python/projectname/env/bin/python

#   change username and projectname above to match yours - the path must match the path in YOUR virtualenv

"""
edit line 1 to match what YOU get when you are in YOUR virtualenv and type:
which python

# NO SPACES in first 3 chars in line 1:  #!/
# make sure env is activated!
# make sure you have "started all" in XAMPP!
# code below works for a MySQL database in XAMPP on Mac OS
# pymysql can be installed with pip: pip install pymysql
"""

import pymysql
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

# this userpass assumes you did not create a password for your database
# and the database username is the default, 'root'
userpass = 'mysql+pymysql://root:@'
basedir  = '127.0.0.1'
# change to YOUR database name, with a slash added as shown
dbname   = '/sockmarket'
# this socket is going to be very different on a Windows computer
socket   = '?unix_socket=/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock'
dbname   = dbname + socket

# put them all together as a string that shows SQLAlchemy where the database is
app.config['SQLALCHEMY_DATABASE_URI'] = userpass + basedir + dbname

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

# this variable, db, will be used for all SQLAlchemy commands
db = SQLAlchemy(app)

# this route will test the database connection and nothing more
@app.route('/')
def testdb():
    try:
        db.session.query("1").from_statement("SELECT 1").all()
        return '<h1>It works.</h1>'
    except:
        return '<h1>Something is broken.</h1>'

if __name__ == '__main__':
    app.run(debug=True)

以上是关于python 测试Flask-SQLAlchemy的MySQL数据库连接的主要内容,如果未能解决你的问题,请参考以下文章

Python flask-sqlalchemy初级解析

Flask SQL性能测试:使用flask-sqlalchemy检测慢SQL语句

python flask-sqlalchemy외래키구현

python Flask-SQLAlchemy按请求隔离级别设置

python Flask-SQLAlchemy的一个方便的SQL调试功能

在python3下怎样用flask-sqlalchemy对mysql数据库操作