本文介绍了在 Flask 中连接数据库,哪种方法更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方法一:使用来自 http://flask.pocoo.org/docs 的特殊 g 对象/tutorial/dbcon/http://flask.pocoo.org/docs/模式/sqlite3/

Method One: Using special g object from http://flask.pocoo.org/docs/tutorial/dbcon/ and http://flask.pocoo.org/docs/patterns/sqlite3/

import sqlite3
from flask import g

DATABASE = '/path/to/database.db'

def connect_db():
    return sqlite3.connect(DATABASE)

@app.before_request
def before_request():
    g.db = connect_db()

@app.teardown_request
def teardown_request(exception):
    if hasattr(g, 'db'):
        g.db.close()

方法二:使用来自https://github的神秘_app_ctx_stack.com/mitsuhiko/flask/blob/master/examples/flaskr/flaskr.py

from sqlite3 import dbapi2 as sqlite3
from flask import Flask, request, session, g, redirect, url_for, abort,
     render_template, flash, _app_ctx_stack
def get_db():
    """Opens a new database connection if there is none yet for the
    current application context.
    """
    top = _app_ctx_stack.top
    if not hasattr(top, 'sqlite_db'):
        top.sqlite_db = sqlite3.connect(app.config['DATABASE'])
    return top.sqlite_db


@app.teardown_appcontext
def close_db_connection(exception):
    """Closes the database again at the end of the request."""
    top = _app_ctx_stack.top
    if hasattr(top, 'sqlite_db'):
        top.sqlite_db.close()

哪种方法更好?有什么区别?

Which method is better? What is the difference?

推荐答案

两者的区别在于方法一在g.db上创建连接不管你是否需要,而方法二只有当您在该应用程序上下文中第一次调用 get_db 时创建连接.

The difference between the two is that method one creates a connection on g.db whether you need it or not while method two only creates the connection when you call get_db for the first time in that application context.

如果你比较两者,使用这个设置:

If you compare the two, using this setup:

yourapp = Flask(__name__)

# setup g.db or app_context here
# Add a logging statement (print will do)
# to the get_db or before_request functions
# that simply says "Getting the db connection ..."
# Then access / and /1

@yourapp.route("/")
def index():
    return "No database calls here!"

@yourapp.route("/<int:post_id>")
def show_post(post_id):
    # get a post using g.db or get_db
    return "Went to the DB and got {!r}".format(post)

您会看到,当您使用 @app.before_request 设置 (g.db) 点击 / 时,您会获得一个连接无论你是否使用它,在使用 _app_context 路由时,你只会在调用 get_db 时获得连接.

You'll see that when you hit / using the @app.before_request setup (g.db) you get a connection whether you use it or not, while using the _app_context route you only get a connection when you call get_db.

公平地说,您还可以向 g 添加一个描述符,该描述符将执行相同的延迟连接(或在现实生活中,从连接池获取连接).在两种情况下,您可以使用更多魔法(werkzeug.local.LocalProxy 准确地说)来创建自己的自定义线程本地,其作用类似于 gcurrent_app请求(等等).

To be fair, you can also add a descriptor to g that will do the same lazy connecting (or in real life, acquiring a connection from a connection pool). And in both cases you can use a bit more magic (werkzeug.local.LocalProxy to be precise) to create your own custom thread local that acts like g, current_app and request (among others).

这篇关于在 Flask 中连接数据库,哪种方法更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 19:20