关于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>

其它模板

 {% extends "base.html" %}
{% block title %}
{{ title }}
{% endblock %}
{% block content %}
<div class="contentTitle">
<span style="color: green; ">{{title}}</span>
<table align="center">
{% for row in rows %}
<tr>
{% for col in row %}
<td>{{col}}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<p align="center">
<input type="button" name="Submit" class="button button1" onclick="history.back();" value="返回">
</p>
</div>
{% 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, Length

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下拉列表的值

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 = (['', ''], ['', ''])
form.user_type.default = ''
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)

对于多个提交的判断,我们可以这样写

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模板

<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>

Flask使用记录的更多相关文章

  1. [ZHUAN]Flask学习记录之Flask-SQLAlchemy

    From: http://www.cnblogs.com/agmcs/p/4445583.html 各种查询方式:http://www.360doc.com/content/12/0608/11/93 ...

  2. Flask学习记录之Flask-SQLAlchemy

    Flask-SQLAlchemy库让flask更方便的使用SQLALchemy,是一个强大的关系形数据库框架,既可以使用orm方式操作数据库,也可以使用原始的SQL命令. Flask-Migrate ...

  3. 部署一个flask服务记录

    最近使用flask写了一些简单的服务. 服务部署到服务器上进行使用,这个过程会有一些问题,需要进行记录一下. 说明运行的环境情况.使用的是python3.6的虚拟环境,系统是centos7,其他的有u ...

  4. flask 开发记录

    from flask import request 判断method方式 request.method  'POST', ‘GET’ 获取form内容 request.form['form_name' ...

  5. Flask学习记录之Flask-Login

    Flask-Loging 可以方便的管理用户会话,保护路由只让认证用户访问 http://flask-login.readthedocs.org/en/latest/ 一.初始化Flask-Login ...

  6. Flask学习记录之Flask-Admin

    相信用过Django框架的都不会忘记它强大的Admin功能,Flask-admin是一款能够与Django Admin所媲美的扩展,能够快速创建Web管理界面,实现了用户.文件增删改查等常用功能:也可 ...

  7. Flask学习记录之MarkDown编辑文本

    为了让网页支持markdown编辑文本,使用如下了4个库 PageDown : 在前端提供一个可以实时将markdown内容转换成html文本进行效果预览的编辑器 Flask-PageDown: 这个 ...

  8. Flask学习记录之Flask-Migrate

    一.配置Flask-Migrate from flask.ext.migrate import Migrate, MigrateCommand migrate = Migrate(app,db) #第 ...

  9. Flask学习记录之Flask-WTF

    Flask-wtf时Wtforms库的flask框架扩展,能够方便的处理Web表单 一.定义一个web表单 使用flask-wtf时,每个web表单都由一个继承自flask.ext.wtf.Form的 ...

  10. Flask学习记录之Flask-Moment

    Moment.js 是一个简单易用的轻量级JavaScript日期处理类库,提供了日期格式化.日期解析等功能.它支持在浏览器和NodeJS两种环境中运行.此类库能够 将给定的任意日期转换成多种不同的格 ...

随机推荐

  1. centos7搭建GitLab

    1.安装依赖 yum -y install policycoreutils openssh-server openssh-clients postfix policycoreutils-python ...

  2. Collection 和 Collections的区别。(转)

    Collection 和 Collections的区别. Collections是个java.util下的类,它包含有各种有关集合操作的静态方法. Collection是个java.util下的接口, ...

  3. Windows Unity ARKit发布到IOS相关设置及错误解决

    Windows 版Unity安装: 考虑到在虚拟机中运行Unity比较卡,所以采用在Windows Unity上将项目发布好然后再复制到Mac虚拟机中通过XCode进行编译的方式. Unity版本为 ...

  4. django框架使用mysql报错,及两种解决方法

    1.django框架 settings.py文件中部分代码: DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3' ...

  5. vue登录注册及token验证

    // router.jsimport Vue from 'vue'import VueRouter from 'vue-router' Vue.use(VueRouter) const routes ...

  6. idea 炫酷插件

    1.插件的安装 打开setting文件选择Plugins选项 Ctrl + Alt + S File -> Setting 分别是安装JetBrains插件,第三方插件,本地已下载的插件包.详情 ...

  7. java-框架-索引

    spring 整体了解 spring 入门demo Spring整体了解 spring梳理 Spring线程池的5个要素 spring的事务隔离级别以及传播性 事务4个隔离界别及脏读,不可重复读,幻读 ...

  8. js学习2

    1.打开新窗体 -window.open([URL], [窗口名称], [参数字符串]) - 窗口名称: _blank:在新窗口显示目标网页 _self:在当前窗口显示目标网页 _top:框架网页中在 ...

  9. install virtual enviroment on windows

    H:\>pip install virtualenv  --install virtualenvCollecting virtualenv Downloading https://files.p ...

  10. 在anaconda下安装已经下载好Opencv4的痛苦回忆

    来来回回装了很多回,今天终于一鼓作气把它安装好,记录一下过程. 准备: Opencv4的安装包,可以在官网上下载 anaconda——主要目的是在anaconda下的某个environment中安装最 ...