2017年4月10日月曜日

開発環境

Head First Python (Paul Barry (著)、O'Reilly Media)のChapter 10.(Function Decorators: Wrapping Functions) の SHARPEN YOUR PENCIL(No. 7523) を取り組んでみる。

SHARPEN YOUR PENCIL(No. 7523)

コード(Emacs)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from flask import Flask, session

app = Flask(__name__)

app.secret_key = 'YouWillNeverGuess'


@app.route('/login')
def do_login() -> str:
    session['logged_in'] = True
    return 'You are now logged in'


@app.route('/logout')
def do_logout() -> str:
    if 'logged_in' in session:
        del session['logged_in']
    return 'You are now logged out'


@app.route('/status')
def check_status() -> str:
    if 'logged_in' in session:
        return 'You are currently logged in'
    return 'You are NOT logged in'


def check_logged_in(func):
    def wrapper():
        if 'logged_in' in session:
            return func()
        return 'You are NOT logged in'
    return wrapper

if __name__ == '__main__':
    app.run(debug=True)

入出力結果(Terminal, IPython)

$ ./sample4.py
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 873-014-066
127.0.0.1 - - [10/Apr/2017 15:31:46] "GET /logout HTTP/1.1" 200 -
127.0.0.1 - - [10/Apr/2017 15:31:47] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [10/Apr/2017 15:31:47] "GET /search4 HTTP/1.1" 404 -
127.0.0.1 - - [10/Apr/2017 15:31:47] "GET /status HTTP/1.1" 200 -
127.0.0.1 - - [10/Apr/2017 15:31:47] "GET /status HTTP/1.1" 200 -
127.0.0.1 - - [10/Apr/2017 15:31:50] "GET / HTTP/1.1" 404 -
127.0.0.1 - - [10/Apr/2017 15:31:51] "GET /login HTTP/1.1" 200 -
127.0.0.1 - - [10/Apr/2017 15:31:51] "GET /login HTTP/1.1" 200 -
127.0.0.1 - - [10/Apr/2017 15:31:54] "GET /search4 HTTP/1.1" 404 -
127.0.0.1 - - [10/Apr/2017 15:31:54] "GET /status HTTP/1.1" 200 -
127.0.0.1 - - [10/Apr/2017 15:31:54] "GET /status HTTP/1.1" 200 -
127.0.0.1 - - [10/Apr/2017 15:31:57] "GET /search4 HTTP/1.1" 404 -
127.0.0.1 - - [10/Apr/2017 15:31:57] "GET /login HTTP/1.1" 200 -
127.0.0.1 - - [10/Apr/2017 15:31:58] "GET /logout HTTP/1.1" 200 -
127.0.0.1 - - [10/Apr/2017 15:31:58] "GET /logout HTTP/1.1" 200 -
127.0.0.1 - - [10/Apr/2017 15:32:00] "GET /status HTTP/1.1" 200 -
127.0.0.1 - - [10/Apr/2017 15:32:01] "GET /status HTTP/1.1" 200 -
$

0 コメント:

コメントを投稿

Comments on Google+: