1. 程式人生 > >Flask Web開發筆記-02

Flask Web開發筆記-02

Web表單,(easy_install.exe  flask-wtf 安裝該擴充套件包)

檔案結構


hello.py

from flask import Flask, render_template, request
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from datetime import datetime
# -*- coding: UTF-8 -*-
from flask import Flask, render_template, redirect, session, url_for, flash
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_wtf import Form
from wtforms import SubmitField, StringField
from wtforms.validators import DataRequired

app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string' #設定祕鑰
bootstrap = Bootstrap(app)
moment = Moment(app)

#定義表單類,一個文字欄位和一個提交按鈕
class NameForm(Form):
    name = StringField('What is your name?', validators=[DataRequired()])
    submit = SubmitField('Submit')


@app.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        old_name = session.get('name') # 從會話中獲取名字
        if old_name is not None and old_name != form.name.data:
            flash('Looks like you have changed your name!')
        session['name'] = form.name.data
        return redirect(url_for('index'))
    return render_template('index.html', form=form, name=session.get('name'))


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

index.html

<!DOCTYPE html>
<html lang="en">
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %}Flasky{% endblock %}
{% block page_content %}
<div class="page-header">
    <h1>Hello, {% if name %}{{ name }}{% else %}Stranger{% endif %}!</h1>
</div>
{{ wtf.quick_form(form) }}
{% endblock %}
</html>

base.html

 <!-- extends指令從Flask-Bootstrap中匯入base.html,實現繼承 -->
 <!-- 三個塊title navbar content都是基模板提供的,在該衍生模組中重新定義-->
{% extends "bootstrap/base.html "%}
{% block title %}Flasky{% endblock %}
{% block navbar %}
<div class="navbar navbar-inverse" role="navigation">
	<div class="container">
		<div class="navbar-header">
			<button type="button" class="navbar-toggle"
			data-toggle="collapse" data-target=".navbar-collapse">
				<span class="sr-only">Toggle navigation</span>
				<span class="icon-bar"></span>
				<span class="icon-bar"></span>
				<span class="icon-bar"></span>
			</button>
			<a class="navbar-brand" href="/">Flasky</a>
		</div>
		<div class="navbar-collapse collappse">
			<ul class="nav navbar-nav">
				<li><a href="/">Home</a></li>
			</ul>
		</div>
	</div>
</div>
{% endblock %}

{% block content %}
<div class="container">
	{% for message in get_flashed_messages() %}
		{% if message %}
			<div class="alter alter-warining">
				<button type="button" class="close" data-dismiss="alter">×</button>
				{{ message }}
			</div>
		{% endif %}
	{% endfor %}
	{% block page_content %}{% endblock %}
</div>
{% endblock%}

效果