首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MySQL数据库连接的水瓶配置处理

问MySQL数据库连接的水瓶配置处理
EN

Stack Overflow用户
提问于 2021-12-28 14:42:49
回答 2查看 554关注 0票数 -1

我是新的瓶,目前探索官方教程可用的https://flask.palletsprojects.com/en/2.0.x/tutorial/factory/。

该示例基于SQLite数据库创建博客。数据库在以下语句中定义:

代码语言:javascript
复制
app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    )

程序代码

代码语言:javascript
复制
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

但是,我不想使用am SQLite数据库,而是使用MySQL数据库来存储信息。在这个阶段,我如何定义MySQL配置?

我在本教程的db.py文件中修改了以下代码:

https://flask.palletsprojects.com/en/2.0.x/tutorial/database/

代码语言:javascript
复制
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数据库连接的指导吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-01-02 14:53:54

我做了一些调查,发现不是强制在工厂函数中定义MySQL数据库连接才能让应用程序工作。我从app.config.from_mapping中删除了数据库参数值,并且只将数据库连接字符串保存在实际的db.py文件中。到目前为止,应用程序运行良好。

代码语言:javascript
复制
app=Flask(__name__, instance_relative_config=True)
    app.config.from_mapping(SECRET_KEY='development',)
票数 0
EN

Stack Overflow用户

发布于 2021-12-28 16:28:26

在这里,您可以使用pymysql来管理连接。下面是一个演示如何管理DB连接的示例。

代码语言:javascript
复制
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) 

你可以用它作为,

代码语言:javascript
复制
with DatabaseHandler() as db_conn:
     Any database operation with db_conn
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70508608

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档