Step 4: データベースの利用

DBへの接続は以下のスクリプトで可能です。

flaskは、DB処理の前後で別処理をするには以下のようなデコレータを利用することで可能になります。 before_request() もしくわ after_request()

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

@app.after_request
def after_request(response):
    g.db.close()
    return response

Functions marked with before_request() are called before a request and passed no arguments, functions marked with after_request() are called after a request and passed the response that will be sent to the client. They have to return that response object or a different one. In this case we just return it unchanged.

We store our current database connection on the special g object that flask provides for us. This object stores information for one request only and is available from within each function. Never store such things on other objects because this would not work with threaded environments. That special g object does some magic behind the scenes to ensure it does the right thing.

Step 5: View関数.

Related Topics

This Page