Flask使用記錄

關於FLASK框架的使用

使用pycharm建立工程

在默認的templates中新增模板頁面

在默認的app.py中定義路由並引用模板

@app.route("/add", methods=["GET", "POST"])
def add():
    if request.method != 'POST':
        return render_template("login.html",info="請先登陸系統")
    else:
     username = request.form.get('username') return render_template(
"add.html")

關於日誌,能夠使用FLASK自帶的LOG模塊

from flask import current_app

current_app.logger.info("登陸用戶名:" + account) 

 

 關於模板的使用

我建立了一個base.html基礎模板用於繼承

<!DOCTYPE html>
<html lang="en">
<head>
    {% block head %}
        <meta charset="UTF-8">
        <link rel="stylesheet" href="../static/css/page.css"/>
        <script type="text/javascript" src="../static/js/jquery.min.js"></script>
        <script type="text/javascript" src="../static/js/index.js"></script>
        <title>{% block title %}{% endblock %} - 操做平臺</title>
    {% endblock %}
</head>
<body>
<div class="left">
    <div class="bigTitle">CA操做平臺</div>
    <div class="lines">
        {% for menu in menu_list %}
            {% if choice==loop.index0 %}
                <div onclick="pageClick(this,{{ loop.index0 }})" class="active"><img
                        src="static/img/icon-{{ loop.index }}.png"/>
                    {{ menu }}
                </div>
            {% else %}
                <div onclick="pageClick(this,{{ loop.index0 }})"><img src="static/img/icon-{{ loop.index }}.png"/>
                    {{ menu }}
                </div>
            {% endif %}
        {% endfor %}
    </div>
</div>
<div class="top">
    <div class="leftTitle" id="flTitle">{{ menu_list[choice] }}</div>
    <div class="thisUser">{{ user_info }}</div>
</div>
<div class="main">
    <div class="mainForm">
        {% block content %}
            {% with messages = get_flashed_messages(with_categories=true) %} {# 對應:flash("請選擇商品類型!", 'error') #}
                {% if messages %}
                    {% for category,message in messages %}
                        <span class={{ category }}>{{ message }}</span>
                    {% endfor %}
                {% else %}
                    &nbsp;
                {% endif %}
            {% endwith %}
        {% endblock %}
    </div>
</div>
<!--<div id="footer">-->
<!--{% block footer %}-->
    <!--&copy; Copyright 2008 by <a href="http://domain.invalid/">Keyba</a>.-->
    <!--{% endblock %}-->
<!--</div>-->
</body>
</html>

 

其它模板

 1 {% extends "base.html" %}
 2 {% block title %}
 3 {{ title }}
 4 {% endblock %}
 5 {% block content %}
 6 <div class="contentTitle">
 7     <span style="color: green; ">{{title}}</span>
 8     <table align="center">
 9         {% for row in rows %}
10         <tr>
11             {% for col in row %}
12             <td>{{col}}</td>
13             {% endfor %}
14         </tr>
15         {% endfor %}
16     </table>
17     <p align="center">
18         <input type="button" name="Submit" class="button button1" onclick="history.back();" value="返回">
19     </p>
20 </div>
21 {% endblock %}

 關於FORM

創建MyForm類,這裏使用了DataRequired, Email, Length三種校驗方式,這裏的role(下拉列表SelectField)沒有設置choices屬性值是爲了後面能夠動態from flask_wtf import FlaskFormfrom wtforms import StringField, TextAreaField, SubmitField, SelectFieldfrom wtforms.validators import DataRequired, Email, Lengthjavascript

class MyForm(FlaskForm):
    new_user = StringField(label='新帳號:', validators=[DataRequired("請輸入新的後臺帳號"), Length(6, 20, '帳號長度爲6到20位')],
                           description="請輸入新的後臺帳號", render_kw={"required": "required"})
    email = StringField(label='郵箱:', validators=[DataRequired("請輸入郵箱"), Email('郵箱格式錯誤')], description="請輸入郵箱",
                        render_kw={"required": "required"})
    role = SelectField(label='角色:')
    label = '用戶類型:'
    user_type = RadioField(label=label)
    submit = SubmitField('註冊後臺帳號', render_kw={"class": "button button1"})

配置路由,並更新role下拉列表的值css

from forms import MyForm

app.config['SECRET_KEY'] = 'string' # 經過csrf @app.route('/add/', methods=("GET", "POST")) def add(): form = MyForm() # 這裏的form只會進行一次賦值,POST請求過來時,不會更新,便可以重用。 roles_list = [(str(d.get('roleId')), str(d.get("roleName"))) for d in all_roles] oc_form.role.choices = roles_list # 這裏咱們對以前的role進行從新賦值 form.user_type.choices = (['1', '11'], ['2', '22']) form.user_type.default = '1' form.process() # 這裏咱們刷新form,以使用戶類型這個radioButton更新 if request.method == 'POST' and form.validate_on_submit(): return render_template("success.html", title="新增用戶成功") # return redirect(url_for('pageTo', page=1) return render_template('add.html', form=form)

對於多個提交的判斷,咱們能夠這樣寫html

add_user = SubmitField('註冊', render_kw={"class": "button button1"})
auth_user = SubmitField('認證', render_kw={"class": "button button1"})
add_something = SubmitField('發佈', render_kw={"class": "button button1"})

 

form = MallUserForm()
    if request.method == 'POST':
        if form.add_user.data:
            return add_mall_user(form)
        elif form.auth_user.data:
            return auth_user(form)
        elif form.add_something.data:
            if form.mall_type.data != 'None':
                return add_goods(form)
            else:
                flash("請選擇商品類型!", 'error')
                return redirect(url_for('mall_index'))

 

HTML模板java

<form name="baseForm" action="" role="form" method="post">
    <div class="contentTitle">後臺帳號操做</div>
    {% for item in form %}
        {% if item!=form.submit %}
            {% if item!=form.role %}
                <div>
                    {{ item.label }}{{ item(size=20) }} <!-- 定義size -->
                </div>
            {% else %}
                    {{ item.label }}{{ item }} <!-- 下拉列表框 -->
            {% endif %}
        {% else %}
            <div class="center">
                {{ item }} <!-- 提交按鈕 -->
            </div>
        {% endif %}
    {% endfor %}
</form>
相關文章
相關標籤/搜索