Flask 入门基础python
Flask是一个轻量级的后台框架,用Flask做为Web框架的公司有Netfix,Reddit等,国内豆瓣,果壳等。使用flask的公司列表。Flask 有主要的两个依赖,一个是WSGI(web server gateway Interface)web服务器网关接口,工具集-Werkzeug。另外一个是Jinjia2模板引擎web
python3.4以上版本pip已经自动安装好了sql
# 检查pip是否已经安装 $: pip --version # 安装某个包,例如安装flask $: pip install <包的名称> $: pip install flask # 安装pipenv(全局) $: pip install pipenv # 检查pipenv是否安装 $: pipenv --version
虚拟环境一般用virtulenv来建立,为了更方便的关联虚拟环境和依赖包数据库
$: pipenv install
$: mkdir demo/helloflask $: cd demo/helloflask $: mkdir hello.py $: pip install flask $: vim hello.py # 代码清单 from flask import Flask app = Flask(__name__) @app.route('/') def hello(): return "hello flask" if __name__ = '__main__': app.run() # 运行 $: python hello.py
from flask import Flask app = Flask(__name__)
# 这一系列都是由Flask完成,咱们只须要在函数上面添加一个装饰器app.route(),并传入url规则做为参数。可让函数与url创建一个链接,这个过程叫作注册路由,函数称为视图函数 @app.route('/') def hello(): return "hello flask"
if __name__ = '__main__': app.run()
在启动的时候能够添加参数,在run()中flask
@app.route('/index') @app.route('/hello') def index(): return 'hello, Flask!'
@app.route('/hello/<name>') def index(name): return 'hello %s' % name
@app.route('/hello' , defaults={'name':'param'}) @app.route('/hello/<name>') def index(name): return 'hello %s' % name
@app.route('/hello/<int:name_id>') def index(name): return 'hello %d' % name_id
@app.route('/hello',methods = ['GET','POST']) def index(): return 'hello flask'
from flask import Flask, redirect @app.route('/index') def index(): return redirect('http://www.example.com')
from flask import Flask, redirect, url_for @app.route('/index') def index(): return redirect(url_for('login')) @app.route('/') def login(): return "登入成功"
from flask import Flask, abort @app.route('/404') def not_found(): abort(404)
helloflask/ - static/ - templates/ - app.py
{% if %}..{% else %}..{% endif %} {% for i in message %}..{% endfor %}
{{ }}
{% include "index.html" %}
{% from 'bootstrap/form.html' import render_form %} {{ render_form(form) }}
{% extends 'base.html' %}
{% block content %}{% endblock %}
- templates/ index.html @app.route('/') def index(): return render_template('index.html')
{{ name|title }}
{{ movies|length }}
过滤器名 | 说明 |
---|---|
upper | 字母大写 |
lower | 字母小写 |
capitalize | 首字母大写 |
truncate(6,True) | 当前字符长度超过6显示...,默认是第二个参数是false |
default() | 默认字符串名 |
trim | 去除先后空格 |
safe | 关闭自动转义 |
round | 四舍五入取整 |
abs | 绝对值 |
first | 取第一个元素 |
last | 取最后一个元素 |
sum | 求和 |
sort | 排序默认升序 |
join | 合并为字符串 |
from flask import Flask, render_template, flash, redirect, url_for app = Flask(__name__) app.secret_key = 'secret' @app.route('/flash/') def flask(): flash("闪现") return redirect(url_for('hello_world'))
<div> {% for message in get_flashed_messages() %} <div class="alert">{{ message }}</div> {% endfor %} </div>
$:pip install flask-sqlalchemy 对app对象初始化 db = SQLAlchemy() db.init_app(app)
db = SQLAlchemy() class User(db.Model): __tablename__ == 'user' name = db.Column(db.String(100)) no = db.Column(db.Integer(20))
字段 | 说明 |
---|---|
String | 字符串 |
Integer | 整型 |
Text | 文本 |
Date | 日期对象 Datetime.date |
Time | 时间对象 Datetime.time |
DateTime | 时间日期 |
Interval | 时间间隔 |
Float | 浮点数 |
Boolean | 布尔值 |
参数名 | 说明 |
---|---|
primary_key | 若是为True 该字段为主键 |
unique | 若是为True 该字段不容许重复 |
index | 若是为True 该字段建立索引 |
nullable | 该字段能否为空 |
default | 字段设置默认值 |
__tablename__ = ''
db.create_all()
db.drop_all()
# 调用add()方法将新建立的对象添加到数据库会话中 db.session.add(user) # 提交会话 db.session.commit()
<模型类> .query. <过滤方法> . <查询方法> bootstrap
https://docs.sqlalchemy.org/en/13/orm/query.html
查询方法 | 说明
---|---
all() | 查询包含全部的记录列表
first() | 查询第一条数据,若是没有返回None
get(ident) | 传入主键值为参数,返回猪圈记录
count() | 返回查询的数量
first_or_404() | 查询第一条记录,未找到返回404错误
with_paernt() | 传入模型做为参数,返回和这个实例相关联的对象
paginate() | 返回Pagination对象,对记录进行分页操做vim
https://docs.sqlalchemy.org/en/13/orm/query.htmlapi
过滤方法 | 说明 |
---|---|
filter() | 使用指定的规则过滤,返回新产生的对象 |
filter_by() | 使用指定的规则过滤(以关键字为对象),返回新产生的对象 |
order_by | 排序 |
group_by() | 根据查询的记录进行分组 |
offset() | 偏移查询结果 |
class Author(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(70), unique=True) phone = db.Column(db.String(20)) class Article(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(50), index=True) body = db.Column(db.Text)
class Article(db.Model): id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(50), index=True) body = db.Column(db.Text) author_id = db.Column(db.Integer, db.ForeignKey('author.id'))
class Author(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(70), unique=True) phone = db.Column(db.String(20)) articles = db.relationship('Article')
参数书籍:Flask开发实战浏览器