MySQL 数据库连接在 Flask 中的配置处理
Configuration handling in Flask for MySQL database connection
我是 Flask 的新手,目前正在探索 https://flask.palletsprojects.com/en/2.0.x/tutorial/factory/ 中提供的官方教程。
该示例创建了一个基于 SQLite 数据库的博客。数据库在以下语句中定义:
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
程序代码
flaskr/__init__.py
import os
from flask import Flask
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
# a simple page that says hello
@app.route('/hello')
def hello():
return 'Hello, World!'
return app
但是,我想使用 MySQL 数据库来存储信息,而不是 SQLite 数据库。在此阶段如何定义 MySQL 配置?
我在教程的db.py文件中修改了以下代码:
https://flask.palletsprojects.com/en/2.0.x/tutorial/database/
import mysql.connector
import click
from flask import current_app, g
from flask.cli import with_appcontext
# Function to create a database connection.
def get_db():
if 'db' not in g:
g.db=mysql.connector.connect(host="localhost",user="dbuser",password="database123",database="testdb")
return g.db
# Function to close an existing database connection.
def close_db(e=None):
db=g.pop('db',None)
if db is not None:
db.close()
# Function to initialize the database from a script.
def init_db():
db = get_db()
with open('schema.sql', 'r') as f:
with db.cursor() as cursor:
cursor.execute(f.read(), multi=True)
db.commit()
@click.command('init-db')
@with_appcontext
def init_db_command():
# Delete existing data and re-create tables.
init_db()
click.echo('Initialized the database.')
# Register with the application.
def init_app(app):
app.teardown_appcontext(close_db)
app.cli.add_command(init_db_command)
有人可以提供一些关于如何设置 MySQL 数据库连接的指导吗?
在这里您可以使用pymysql
来管理您的连接。下面的示例显示了如何管理数据库连接。
import pymysql
def db_connect():
conn = pymysql.connect(user='Your user',
password="Your password",
host="Your host",
database="Your database",
cursorclass=pymysql.cursors.DictCursor)
return conn
def db_close(conn):
if conn and conn.open:
conn.close()
class DatabaseHandler(object):
def __init__(self):
self.conn = None
def __enter__(self):
self.conn = db_connect()
return self.conn
def __exit__(self, exc_type, exc_val, exc_tb):
db_close(self.conn)
您可以将其用作,
with DatabaseHandler() as db_conn:
Any database operation with db_conn
我进行了一些深入研究,发现 不是强制性的 在工厂函数中定义 MySQL 数据库连接以使应用程序正常工作。我从 app.config.from_mapping
中删除了数据库参数值,只将数据库连接字符串保留在实际的 db.py 文件中。到目前为止,该应用程序运行良好。
app=Flask(__name__, instance_relative_config=True)
app.config.from_mapping(SECRET_KEY='development',)
我是 Flask 的新手,目前正在探索 https://flask.palletsprojects.com/en/2.0.x/tutorial/factory/ 中提供的官方教程。
该示例创建了一个基于 SQLite 数据库的博客。数据库在以下语句中定义:
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
程序代码
flaskr/__init__.py
import os
from flask import Flask
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile('config.py', silent=True)
else:
# load the test config if passed in
app.config.from_mapping(test_config)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
# a simple page that says hello
@app.route('/hello')
def hello():
return 'Hello, World!'
return app
但是,我想使用 MySQL 数据库来存储信息,而不是 SQLite 数据库。在此阶段如何定义 MySQL 配置?
我在教程的db.py文件中修改了以下代码:
https://flask.palletsprojects.com/en/2.0.x/tutorial/database/
import mysql.connector
import click
from flask import current_app, g
from flask.cli import with_appcontext
# Function to create a database connection.
def get_db():
if 'db' not in g:
g.db=mysql.connector.connect(host="localhost",user="dbuser",password="database123",database="testdb")
return g.db
# Function to close an existing database connection.
def close_db(e=None):
db=g.pop('db',None)
if db is not None:
db.close()
# Function to initialize the database from a script.
def init_db():
db = get_db()
with open('schema.sql', 'r') as f:
with db.cursor() as cursor:
cursor.execute(f.read(), multi=True)
db.commit()
@click.command('init-db')
@with_appcontext
def init_db_command():
# Delete existing data and re-create tables.
init_db()
click.echo('Initialized the database.')
# Register with the application.
def init_app(app):
app.teardown_appcontext(close_db)
app.cli.add_command(init_db_command)
有人可以提供一些关于如何设置 MySQL 数据库连接的指导吗?
在这里您可以使用pymysql
来管理您的连接。下面的示例显示了如何管理数据库连接。
import pymysql
def db_connect():
conn = pymysql.connect(user='Your user',
password="Your password",
host="Your host",
database="Your database",
cursorclass=pymysql.cursors.DictCursor)
return conn
def db_close(conn):
if conn and conn.open:
conn.close()
class DatabaseHandler(object):
def __init__(self):
self.conn = None
def __enter__(self):
self.conn = db_connect()
return self.conn
def __exit__(self, exc_type, exc_val, exc_tb):
db_close(self.conn)
您可以将其用作,
with DatabaseHandler() as db_conn:
Any database operation with db_conn
我进行了一些深入研究,发现 不是强制性的 在工厂函数中定义 MySQL 数据库连接以使应用程序正常工作。我从 app.config.from_mapping
中删除了数据库参数值,只将数据库连接字符串保留在实际的 db.py 文件中。到目前为止,该应用程序运行良好。
app=Flask(__name__, instance_relative_config=True)
app.config.from_mapping(SECRET_KEY='development',)