前言:
Flask简介:Flask是一个使用 Python 编写的轻量级 Web 应用框架,基于 WerkzeugWSGI工具箱和 Jinja2模板引擎。
想要学习flask,又非常迷茫,不知如何下手,终于写下第一个项目,分享给大家,希望能对刚刚入门的你有所帮助。
flask+flask_bootstrap+flask_wtf+mysql
一、项目目录
static目录:存放静态文件
templates目录:用来存放响应的html文件
forms.py:存放表单定义
model.py:定义数据模型
app.py:视图函数
![](http://upload-images.jianshu.io/upload_images/7116457-a0ab6b9502d2fa7c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/642)
二、数据库部分
本次使用的数据库是MySQL,需要安装flask-sqlalchemy来管理数据库
>>>pip install flask-sqlalchemy
1、使用URL制定数据库
mysql://username:password@hostname/database
![](http://upload-images.jianshu.io/upload_images/7116457-326ebf99ee1535cb.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
2、执行sql语句
进入mysql命令行:(sql文件的目录根据自己的真实路径来修改)
mysql> . /Users/workpace/flask-1/sql_flask.sql
![](http://upload-images.jianshu.io/upload_images/7116457-fd8077f1074eb2f4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
3、定义数据模型
![](http://upload-images.jianshu.io/upload_images/7116457-6132843c9af00b1c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
4、插入行db.session.add()
![](http://upload-images.jianshu.io/upload_images/7116457-b4e837e652dfd353.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
5、删除行db.session.deleted()
![](http://upload-images.jianshu.io/upload_images/7116457-98ada34ad519def2.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
6、查询行Role.query
查询全部:Role.query.all()
条件查询(使用过滤器):User.query.filter_by(role=user_role).all()
![](http://upload-images.jianshu.io/upload_images/7116457-bf7d29b8b415e428.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
三、表单定义
需要安装flask_wtf,WTForms
>>>pip install flask_wtf
>>>pip install WTForms
![](http://upload-images.jianshu.io/upload_images/7116457-80794610f3c2e7b8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
四、视图函数
使用程序实例提供的app.route修饰器,把修饰的函数注册为路由,添加的methods参数告诉Flask在URL映射中把这个视图函数注册为GET和POST请求的处理程序。
最后一行调用render_template()函数渲染模板。
需要安装flask_bootstrap
>>>pip install flask_bootstrap
![](http://upload-images.jianshu.io/upload_images/7116457-3b7cc6ec69687463.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
五、运行页面
![](http://upload-images.jianshu.io/upload_images/7116457-1022fea2a7cd3e6c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
![](http://upload-images.jianshu.io/upload_images/7116457-9f4ad725bb7f6946.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
![](http://upload-images.jianshu.io/upload_images/7116457-1fbd5a866ed52592.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/700)
6、开源代码
链接: https://github.com/wangxiaoxi3/Flask_test_1
以上,希望能对你有所帮助~~