1. /login 에서 GET, POST 받아오기

# app/routes.py
from app import app
from flask import render_template, flash, redirect
from app.forms import LoginFrom

@app.route('/login', methods=['GET', 'POST'])
def login():
    testform = LoginForm()
    if testform.validate_on_submit():
        flash('Login requested for user {}, remember_me={}'.format(
            testform.username.data, testform.remember_me.data))
        return redirect('/index')
    return render_template('login.html', title='Sign In', form=testform)

 

 

 

2. 기본 템플릿에서 깜빡이는 메시지 flash

<!-- vim app/templates/base.html -->

<html>
    <head>
      {% if title %}
      <title>{{ title }} - Microblog</title>
      {% else %}
      <title>Welcome to Microblog</title>
      {% endif %}
    </head>
    <body>
        <div>
            Microblog:
            <a href="/index">Home</a>
            <a href="/login">Login</a>
        </div>
        <hr>
        {% with messages = get_flashed_messages() %}
        {% if mwssages %}
        <ul>
            {% for message in messages %}
            <li>{{ message }}</li>
            {% endfor %}
        </ul>
        {% endif %}
        {% endwith %}
        {% block content %}{% endblock %}
    </body>
</html>

 

 

 

3. 로그인 양식 템플릿의 유효성 검증 오류

<!-- vim app/tesmplates/login.html -->

{% extends "base.html" %}

{% block content %}
    <h1>Sign In</h1>
    <form action="" method="post" novalidate>
        {{ form.hidden_tag() }}
        <p>
            {{ form.username.label }}<br>
            {{ form.username(size=32) }}
            {% for error in form.username.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>
            {{ form.password.label }}<br>
            {{ form.password(size=32) }}<br>
            {% for error in form.password.errors %}
             <span style="color: red;">[{{ error }}]</span>
            {% endfor %}
        </p>
        <p>{{ form.remember_me() }} {{ form.remember_me.label }}</p>
        <p>{{ form.submit() }}</p>
    </form>
{% endblock %}

비어있는 상태로 Sign in 버튼 클릭시 위와 같이 잘 출력됩니다.

 

 

 

4. url_for 사용하여 링킹 관리 간소화하기

# app/routes.py
from app import app
from flask import render_template, flash, redirect, url_for
from app.forms import LoginFrom

@app.route('/login', methods=['GET', 'POST'])
def login():
    testform = LoginForm()
    if testform.validate_on_submit():
        flash('Login requested for user {}, remember_me={}'.format(
            testform.username.data, testform.remember_me.data))
        return redirect(url_for('index'))
    return render_template('login.html', title='Sign In', form=testform)
<!-- vim app/templates/base.html -->
<html>
<!-- ... -->
        <div>
            Microblog:
            <a href="{{ url_for('index') }}">Home</a>
            <a href="{{ url_for('login') }}">Login</a>
        </div>
<!-- ... -->
</html>

 

 

 

+ Recent posts