@Dukebf
2017-07-11T16:01:02.000000Z
字数 2701
阅读 1825
python Flask
这是来自《python web 开发实践》以及一些网上教程的笔记.
# python -m pip install Flask
入门资料:
# -*- coding:utf-8 -*-from flask import Flaskapp = Flask(__name__)@app.route("/")def hello_world():return 'hello world'if __name__ = '__main__':app.run(host='0.0.0.0',port=9000,debug=True)
其中:
- host 如果不设置,浏览器默认是 127.0.0.1
- port 默认是 5000
- debug 默认不开启
可以通过配置文件,管理大量的配置设置,设置一个配置文件 config.py
# config.pydebug = True
在需要配置的文件中,如index.py 导入config.py
# index.pyimport config.pyapp.config.from_object(settings)# 或者 直接通过文件名导入app.config.from_pyfile('config.py',silent=True)
动态参数 id :
@app.route("/item/<id>/")def item(id):return 'Item:{}'.format(id)
其中, 使用了特殊的字段标记 <variable_name> ,默认类型是字符串.
如果需要指定参数类型,需要标记 <converter:variable_name> 这样的格式,converter有以下几种类型:
- string 接受任何没有斜杠 '/'的文本
- int
- float
- path 和string 类似,但接受斜杠
- uuid 只接受uuid字符串
- any 可以指定多种路径,但需要传入参数
@app.route('/<any(a,b):page_name>/')
可以修改默认的 GET请求
@app.route("/login",method=['GET','POST'])
通过 url_for()构造动态的URL,避免写死路径
url_for('item',id='1') # /item/?id=1url_for('item',id='1',next='/') # /item/?id=1&next=%2Furl_for('static',filename='style.css') # /static/style.css
- 跳转(301) :有页面被永久性移走的概念
- 重定向(302): 暂时性的转移
它们都是通过 flask.redirect 实现,默认是 302
redirect(location)
redirect(location,code=301)
蓝图(Blueprint) 实现了应用模块化,使用蓝图可以让应用层次清晰.
蓝图通常用于相同的URL前缀, 比如 /user/id, /user/profile 这样的地址
_# user.pyfrom flask import Blueprintbp = Blueprint('user',__name__,url_prefix='/user')@bp.route('/')def index():return "User's Index page "
调用蓝图的页面
# app_bp.pyfrom flask import Flaskimport userapp = Flask(__name__)appp.register_blueprint(user.bp)if __name__ = '__main__':app.run()
基本语法:
- {# ... #} 末班注释
- {% .. %} 用于执行如for 循环或赋值语句
- {{ ... }} 用于将表达式的结果输出到模板上
- trim 过滤器,通过管道符号(|)将变量和过滤器分开
- striptags 也是过滤器
例子:
<body>{# This is a comment #}<ul>{% for item in items %}<li> <a href="{{item.href}}"> {{ item['content'] }} </a></li>{% endfor %}</ul><h1> {{ title | trim | striptags }}</body>
通过 {% block XXX %} ... {% endblock %}进行继承
例子中 index.html 继承了 base.html
# base.html<head>{% block head %}<link rel="stylesheet" href="style.css" /><title> {% block title %} {% endblock %} - My Webpage </title>{% endblock %}</head><div id="content">{% block content %}{% endblock %}</div><div id="footer">{% block footer %}{% endblock %}</div>
# index.html{% extends "base.html" %}{% block title %} Index {% endblock %}{% block head %}{{ super() }}<style type="css">.demo { color:red }</style>{% endblock %}{# 下面是重载base.html 中 id="content" 的内容 #}{% block content %}<h1> Index </h1><p class="demo"> This is a demo </p>{% endblcok content %}
上面的子模板的细节如下:
- index.html 继承了 base.html 里面的内容.
extends要放在模板开始- 标题被重载
- head 块被重载, 但是首先使用了
super(), 表示先使用 base.html的head块内容,再基于此添加内容- content 被重载,在结束标签加入名称,增加可读性
- footet 没有被重载,所以什么都不显示
使用 set 标签赋值
{% set a = 1 %}<p> {{ a }} </p>
include 用于包含一个模板
{% include 'header.html' %}body{% inclde 'footer.html' %}