flask-sqlalchemy为啥连接数据库

Posted

tags:

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

参考技术A 总算找到答案了。
db.session.execute("select xxx",bind=db.get_engine(current_app,bind="sqlite_test")).fetchall()本回答被提问者和网友采纳

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)

以上是关于flask-sqlalchemy为啥连接数据库的主要内容,如果未能解决你的问题,请参考以下文章

Flask-SQLAlchemy 和 Gevent 没有关闭 mysql 连接

在多租户应用程序中动态设置 Flask-SQLAlchemy 数据库连接

Flask-SQLAlchemy中解决数据库连接1366报错

Flask 学习-12.Flask-SQLAlchemy 连接 mysql 数据库

Flask-SQLAlchemy:在回滚无效事务之前无法重新连接

3---Flask-SQLAlchemy