连接到Flask的数据库,哪种方法更好? [英] Connect to a Database in Flask, Which Approach is better?

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

问题描述

方法一:使用 http://flask.pocoo.org/docs中的特殊对象/ tutorial / dbcon / http://flask.pocoo.org/docs/ patterns / sqlite3 /

  import sqlite3 $ b $ from flask import g 

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

def connect_db():
返回sqlite3.connect(DATABASE)

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

@ app.teardown_request
def teardown_request(例外):$ b $如果hasattr(g,' db'):
g.db.close()

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

  from sqlite3 import dbapi2 as sqlite3 $ b $ from flask flask Flask,request,session,g,redirect,url_for,abort,\ 
render_template,flash,_app_ctx_stack $ b $ def get_db():
如果还没有
当前应用程序上下文,则打开一个新的数据库连接。

top = _app_ctx_stack.top
如果不是hasattr(top,'sqlite_db'):
top.sqlite_db = sqlite3.connect(app.config ['DATABASE' ])
返回top.sqlite_db


@ app.teardown_appcontext
def close_db_connection(例外):
最后关闭数据库。
top = _app_ctx_stack.top $ b $如果hasattr(top,'sqlite_db'):
top.sqlite_db.close()

div>

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



如果比较两者, you>

  yourapp = Flask(__ name__)

#setup g.db or app_context here
#添加一个日志语句(打印将做)
#到get_db或before_request函数
#简单地说:获取数据库连接...
#然后访问/和/ 1
$ b $ @ yourapp.route(/)
def index():
返回没有数据库调用!

@ yourapp.route (/< int:post_id>)
def show_post(post_id):
#使用g.db或get_db获取帖子
return去数据库并得到{!r你会看到当你点击时, / 使用 @ app.before_request 设置( g.db ), ,当使用 _app_context 路由时,只有在调用 get_db时才能获得连接为了公平起见,你也可以添加一个描述符给 g 。 c>会执行相同的懒连接(或在现实生活中,从连接池获取连接)。在 两种情况下,您都可以使用更多的魔法( werkzeug.local.LocalProxy )来创建您自己的自定义线程本地,类似 g current_app 请求等)。

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()

Method Two: Using Mysterious _app_ctx_stack from https://github.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?

解决方案

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)

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.

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的数据库,哪种方法更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆