[关闭]
@Dukebf 2017-07-11T16:01:02.000000Z 字数 2701 阅读 1538

python之Flask基础

python Flask


目录

前言

这是来自《python web 开发实践》以及一些网上教程的笔记.

安装

  1. # python -m pip install Flask

入门资料:

Hello World

  1. # -*- coding:utf-8 -*-
  2. from flask import Flask
  3. app = Flask(__name__)
  4. @app.route("/")
  5. def hello_world():
  6. return 'hello world'
  7. if __name__ = '__main__':
  8. app.run(host='0.0.0.0',port=9000,debug=True)

其中:

  • host 如果不设置,浏览器默认是 127.0.0.1
  • port 默认是 5000
  • debug 默认不开启

配置管理

可以通过配置文件,管理大量的配置设置,设置一个配置文件 config.py

  1. # config.py
  2. debug = True

在需要配置的文件中,如index.py 导入config.py

  1. # index.py
  2. import config.py
  3. app.config.from_object(settings)
  4. # 或者 直接通过文件名导入
  5. app.config.from_pyfile('config.py',silent=True)

动态URL规则

动态参数 id :

  1. @app.route("/item/<id>/")
  2. def item(id):
  3. 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>/')

HTTP 方法

可以修改默认的 GET请求
@app.route("/login",method=['GET','POST'])

构造 URL

通过 url_for()构造动态的URL,避免写死路径

  1. url_for('item',id='1') # /item/?id=1
  2. url_for('item',id='1',next='/') # /item/?id=1&next=%2F
  3. url_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 这样的地址

  1. _# user.py
  2. from flask import Blueprint
  3. bp = Blueprint('user',__name__,url_prefix='/user')
  4. @bp.route('/')
  5. def index():
  6. return "User's Index page "

调用蓝图的页面

  1. # app_bp.py
  2. from flask import Flask
  3. import user
  4. app = Flask(__name__)
  5. appp.register_blueprint(user.bp)
  6. if __name__ = '__main__':
  7. app.run()

Jinja2 模板

基本语法:

  • {# ... #} 末班注释
  • {% .. %} 用于执行如for 循环或赋值语句
  • {{ ... }} 用于将表达式的结果输出到模板上
  • trim 过滤器,通过管道符号(|)将变量和过滤器分开
  • striptags 也是过滤器

例子:

  1. <body>
  2. {# This is a comment #}
  3. <ul>
  4. {% for item in items %}
  5. <li> <a href="{{item.href}}"> {{ item['content'] }} </a></li>
  6. {% endfor %}
  7. </ul>
  8. <h1> {{ title | trim | striptags }}
  9. </body>

模板

模板继承

通过 {% block XXX %} ... {% endblock %}进行继承
例子中 index.html 继承了 base.html

  1. # base.html
  2. <head>
  3. {% block head %}
  4. <link rel="stylesheet" href="style.css" />
  5. <title> {% block title %} {% endblock %} - My Webpage </title>
  6. {% endblock %}
  7. </head>
  8. <div id="content">
  9. {% block content %}
  10. {% endblock %}
  11. </div>
  12. <div id="footer">
  13. {% block footer %}
  14. {% endblock %}
  15. </div>
  1. # index.html
  2. {% extends "base.html" %}
  3. {% block title %} Index {% endblock %}
  4. {% block head %}
  5. {{ super() }}
  6. <style type="css">
  7. .demo { color:red }
  8. </style>
  9. {% endblock %}
  10. {# 下面是重载base.html 中 id="content" 的内容 #}
  11. {% block content %}
  12. <h1> Index </h1>
  13. <p class="demo"> This is a demo </p>
  14. {% endblcok content %}

上面的子模板的细节如下:

  • index.html 继承了 base.html 里面的内容. extends 要放在模板开始
  • 标题被重载
  • head 块被重载, 但是首先使用了super(), 表示先使用 base.html的head块内容,再基于此添加内容
  • content 被重载,在结束标签加入名称,增加可读性
  • footet 没有被重载,所以什么都不显示

赋值

使用 set 标签赋值

  1. {% set a = 1 %}
  2. <p> {{ a }} </p>

include

include 用于包含一个模板

  1. {% include 'header.html' %}
  2. body
  3. {% inclde 'footer.html' %}

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注