[英]How do I configure mysql the same way as sqlite in flask?
This is the suggested configuration from the Doc for sqlite.这是 sqlite 文档中的建议配置。 How would it be for mysql?
mysql 会怎样?
import sqlite3
import click
from flask import current_app, g
from flask.cli import with_appcontext
def get_db():
if 'db' not in g:
g.db = sqlite3.connect(
current_app.config['DATABASE'],
detect_types=sqlite3.PARSE_DECLTYPES
)
g.db.row_factory = sqlite3.Row
return g.db
def close_db(e=None):
db = g.pop('db', None)
if db is not None:
db.close()
def init_db():
db = get_db()
with current_app.open_resource('schema.sql') as f:
db.executescript(f.read().decode('utf8'))
I would like to use the same command init-db to initialize the mysql我想使用相同的命令 init-db 来初始化 mysql
@click.command('init-db')
@with_appcontext
def init_db_command():
"""Clear the existing data and create new tables."""
init_db()
click.echo('Initialized the database.')
In ext.py
:在
ext.py
:
import pymysql
db = None
def get_db():
global db
if db is None:
db = pymysql.connect("localhost","testuser","test123","TESTDB")
return db
In other module, if you want to execute sql:在其他模块中,如果要执行 sql:
from ext import get_db
db = get_db()
db.cursor.execute(sql)
db
is the singleton object. db
是 singleton object。 I suggest to use the sqlalchemy in Flask.我建议在 Flask 中使用 sqlalchemy。
I would def.我会定义。 recommend you to use Flask-SQLAlchemy , so you do not have to deal with low level SQL problems.
建议您使用Flask-SQLAlchemy ,这样您就不必处理低级 SQL 问题。
As a plus, you could use eg SQLite
locally for testing, and MySQL
or Postgresql
in production, without changed your code (only your config).另外,您可以在本地使用例如
SQLite
进行测试,并在生产中使用MySQL
或Postgresql
,而无需更改您的代码(仅您的配置)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.