【问题标题】:Configuration handling in Flask for MySQL database connectionFlask 中用于 MySQL 数据库连接的配置处理
【发布时间】:2021-12-28 14:42:49
【问题描述】:

我是 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 数据库连接的指导吗?

【问题讨论】:

    标签: python mysql python-3.x flask


    【解决方案1】:

    您可以在这里使用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
    

    【讨论】:

      【解决方案2】:

      我进行了一些挖掘,并认为在工厂函数中定义 MySQL 数据库连接以使应用程序工作是不是强制性的。我从app.config.from_mapping 中删除了数据库参数值,只将数据库连接字符串保留在实际的db.py 文件中。到目前为止,该应用程序运行良好。

      app=Flask(__name__, instance_relative_config=True)
          app.config.from_mapping(SECRET_KEY='development',)
      

      【讨论】:

        猜你喜欢
        • 2014-12-22
        • 1970-01-01
        • 1970-01-01
        • 2018-06-13
        • 2014-11-10
        • 1970-01-01
        • 2013-12-25
        • 1970-01-01
        • 2021-08-17
        相关资源
        最近更新 更多