Flaask Web開発入門(二)のFlashk-lognを使用します.


前の章ではFlashkを使って基本的なWebアプリケーションを開発し、sessionを使って基本的な登録認証を行います.次にFlashk-lognを使ってセッション管理を行います.私たちの「登録・登録」問題を処理します.
Flashk-logn provides user session magement for Flaask.It handles the common task of loging in,loging out,and rememberging your users'sessions over exted periods of time.
It will:
  • Store the active user's ID in the session,and let you logs them in and out easition.
  • Let you restict view to logged-in(or logged-out)users.
  • Handle the normally-tricky“remember me”functionlity.
  • Help protect your users'sessions from being stolen by cookie thieves.
  • Possibly integrate with Flash-Plincipal or other authorization extens later on.
  • However,it does not:
  • Impose a particular database or other storge method on you.You are entirely in charge of how the user is loaded.
  • Restict you to using usernames and passwords、OpenIDs、or any other method of authenticating.
  • Handle permissions beyond“logged in or not.”
  • Handle user registration or account recovery.
  • 前の章のWebアプリケーションですか?
  • まず、Loginager.init_を通じてアプリは私達のアプリケーションを作成し、login_を通じてviewはデフォルトの登録ページを指定しています.ユーザがログインしていない場合、自動的にログインページにジャンプします.
  • app = Flask(__name__)
    login_manager = LoginManager()
    login_manager.init_app(app)
    
    login_manager.login_view = 'login'
    login_manager.login_message = 'please login!'
    login_manager.session_protection = 'strong'
    logger = flask_logger.get_logger(__name__)
    flash_logger.get_loggerは私達がカスタマイズしたログモジュールです.後で紹介します.
  • ルーティング方法login
  • を修正する.
    @app.route('/login', methods=['GET', 'POST'])
    def login():
        if request.method == 'POST':
            logger.debug("login post method")
            username = request.form['username']
            password = request.form['password']
    
            user = flask_db.get_user_engine(username)
            logger.debug('db user id is %s, detail is %s' % (user.username, user))
    
            next_url = request.args.get("next")
            logger.debug('next is %s' % next_url)
    
            if password == 'admin123' and username == user.username:
                # set login user
                user = User()
                user.id = username
                flask_login.login_user(user)
    
                resp = make_response(render_template('index.html', name=username))
                resp.set_cookie('username', username)
                if not is_safe_url(next_url):
                    return abort(400)
                return redirect(next_url or url_for('index'))
            else:
                return abort(401)
    
        logger.debug("login get method")
        return render_template('login.html')
    
    注意して、ユーザーは検証した後、login_を使用します.ユーザー登録のためのuser方法、flashk_db.get_アメリカ.ユーザーがカスタマイズしてデータベースを取得する方法については、ユーザーがログインビューにリダイレクトすることを要求すると、その要求文字列の中にnext変数があり、その値はユーザーが以前に訪問したページになりますので、検証が完了したら、request.args.get(「next」)を通じてユーザーの前に訪問したページアドレスを取得し、リダイレクトします.注意このパラメータに対してセキュリティチェックを行い、リダイレクト攻撃を避けることを提案します.
  • login_を使用する.required装飾器はトップページの許可を確保して
  • にアクセスします.
    @app.route('/', methods=['GET', 'POST'])
    @app.route('/index', methods=['GET', 'POST'])
    @flask_login.login_required
    def index():
        logger.debug("index page, method is %s" % request.method)
        return render_template('index.html', name=flask_login.current_user.id)
    
    
  • ここで、フロントエンドの登録ページを少し修正します.
    
    <html lang="zh">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>    title>
        <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/styles.css') }}"/>
        <link rel="shortcut icon" href="{{ url_for('static', filename='images/wd_favicon.ico')}}"/>
    head>
    <body>
    <div class="htmleaf-container">
        <div class="wrapper">
            <div class="container">
                <h1>Welcomeh1>
                
                <form class="form" method="post" action="">
                    <input type="text" placeholder="Username" name="username" id="username">
                    <input type="password" placeholder="Password" name="password" id="password">
                    <button type="submit" id="login-button">Loginbutton>
                form>
            div>
    
            <ul class="bg-bubbles">
                <li>li>
                <li>li>
                <li>li>
                <li>li>
                <li>li>
                <li>li>
                <li>li>
                <li>li>
                <li>li>
                <li>li>
            ul>
        div>
    div>
    
    <script src="{{ url_for('static', filename='js/jquery-2.1.1.min.js') }} " type="text/javascript">script>
    
    <div style="text-align:center;margin:50px 0; font:normal 14px/24px 'MicroSoft YaHei';color:#000000">
        <h1>    h1>
    div>
    body>
    html>
  • デフォルトのトップページindex.は、部分的にジニアテンプレートを使用し、部分的にはLayui
  • を使用しています.
    
    <html lang="zh">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>  title>
        <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='js/layui/css/layui.css') }}"/>
        <script src="{{ url_for('static', filename='js/jquery-2.1.1.min.js') }}" type="text/javascript">script>
        <script src="{{ url_for('static', filename='js/layui/layui.js') }}" type="text/javascript">script>
        <link rel="shortcut icon" href="{{ url_for('static', filename='images/favicon.ico')}}"/>
    head>
    <body>
    <div style="width: 80%; float:left; margin: 10px 5px;font-family: Consolas;font-size: 20px;">
        {% if name %}
        Hello {{ name }}!
        {% else %}
        Hello World!
        {% endif %}
    div>
    <div style="float:right; width: 10%;margin: 10px 5px;font-family: Consolas;font-size: 20px;">
        <a href="#" onclick="javascript:logout();">logouta>
    div>
    <table class="layui-table">
        <colgroup>
            <col width="150">
            <col width="200">
            <col>
        colgroup>
        <thead>
        <tr>
            <th>  th>
            <th>    th>
            <th>  th>
        tr>
        thead>
        <tbody>
        <tr>
            <td>  td>
            <td>2016-11-29td>
            <td>layuitd>
        tr>
        <tr>
            <td>   td>
            <td>2016-11-28td>
            <td>tabletd>
        tr>
        tbody>
    table>
    <script type="text/javascript">
        var logout = function () {
            window.location.href = '/logout';
        }
    script>
    body>
    html>
  • ルーティング方法logout
  • を登録する.
    @app.route('/logout')
    @flask_login.login_required
    def logout():
        # remove the username from the session if it's there
        logger.debug("logout page")
        flask_login.logout_user()
        return redirect(url_for('login'))
    
    ここで、Flashk-lognを使ったログイン、ログイン管理を完了しました.次に、Request Loaderを使ってカスタマイズ登録を紹介します.
    http://www.pythondoc.com/flask-login/
    http://flask-login.readthedocs.io/en/latest/#login-example
    ソースの参考:https://github.com/ypmc/flask-sqlalchemy-web