2.Flask基础-1

Flask基础-Part 1

本章完成以下内容:

  1. 一个基本的App
  2. url路由与蓝图
  3. 模板与继承

一、一个基本的App

# hello.py
from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

在控制台输入命令:

$ python hello.py
 * Running on http://127.0.0.1:5000/

我们就可以访问提示中的地址,看到页面输出:Hello World!

二、路由与蓝图

2.1 路由

@app.route('/')
def index():
    return 'Index Page'

@app.route('/hello')
def hello():
    return 'Hello World'
@app.route('/user/<username>')
def show_user_profile(username):
    # show the user profile for that user
    return 'User %s' % username

@app.route('/post/<int:post_id>')
def show_post(post_id):
    # show the post with the given id, the id is an integer
    return 'Post %d' % post_id

# 通过Method指定http请求的类型,默认只有GET
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        do_the_login()
    else:
        show_the_login_form()

路由可以将一个或多个地址绑定到某个指定的函数上,其中<converter:variable_name> 指定一个可选的转换器,它有下面几种:

类型解释
int接受整数
float同 int ,但是接受浮点数
path和默认的相似,但也接受斜线

为了确保URL的唯一性,访问一个结尾不带斜线的 URL 会被 Flask 重定向到带斜线的规范 URL 去。

给静态文件生成 URL ,使用特殊的 ‘static’ 端点名:url_for('static', filename='style.css')

2.2 蓝图

在单独的Web应用中,所有的页面公用一个根路径,一般没有此需求。但是为了考虑多个Web程序公用一个域名,通过不同的根区分不同的应用,此时,每个单独Web需要指定不同的根路径,但是,根据URL规则,根是固定的,此时,为了为不同的模块APP动态产生不同的URL,需要使用到蓝图的概念。

Flask 中的蓝图不是即插应用,因为它实际上并不是一个应用——它是可以注册,甚至可以多次注册到应用上的操作集合。为什么不使用多个应用对象?你可以做到那样 (见 应用调度 ),但是你的应用的配置是分开的,并在 WSGI 层管理。

一个使用蓝图的例子:

from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound

app = Flask(__name__)

simple_page = Blueprint('simple_page', __name__,
                        template_folder='templates')
app.register_blueprint(simple_page)

@simple_page.route('/', defaults={'page': 'index'})
@simple_page.route('/<page>')
def show(page):
    try:
        return render_template('pages/%s.html' % page)
    except TemplateNotFound:
        abort(404)
  • 当我们使用 @simple_page.route 装饰器绑定函数时,在蓝图之后被注册时它会记录把 show 函数注册到应用上的意图。此外,它会给函数的端点加上由 Blueprint 的构造函数中给出的蓝图的名称作为前缀(在此例中是 simple_page )。
  • 我们访问这个两个页面时就可以直接访问 / 和 /xxx 。
  • 为了模块之间的区分,我们可以给每个模块添加前缀 app.register_blueprint(simple_page, url_prefix='/pages')
  • 此时,我们访问的路径就变为了: /pages/ 和 /pages/xxxx。
  • 一个蓝图可以通过 static_folder 关键字参数提供一个指向文件系统上文件夹的路径,来暴露一个带有静态文件的文件夹。这可以是一个绝对路径,也可以是相对于蓝图文件夹的路径 admin = Blueprint('admin', __name__, static_folder='static'), 它会在蓝图 + /static 的位置上可用。也就是说,蓝图为 /admin 把静态文件夹注册到 /admin/static 。
  • 命名的 blueprint_name.static ,这样你可以生成它的 URL ,就像你对应用的静态文件夹所做的那样: url_for('admin.static', filename='style.css')
  • simple_page.root_path 可以访问蓝图根目录.
  • 如果你想要蓝图暴露模板,你可以提供 Blueprint 构造函数中的 template_folder 参数来实现:admin = Blueprint('admin', __name__, template_folder='templates')像对待静态文件一样,路径可以是绝对的或是相对蓝图资源文件夹的。
  • 当你想要从一个页面链接到另一个页面,你可以像通常一个样使用 url_for() 函数,只是你要在 URL 的末端加上蓝图的名称和一个点( . )作为前缀:url_for('admin.index')此外,如果你在一个蓝图的视图函数或是模板中想要从链接到同一蓝图下另一个端点, 你可以通过对端点只加上一个点作为前缀来使用相对的重定向:url_for('.index')这个案例中,它实际上链接到 admin.index ,假如请求被分派到任何其它的 admin 蓝图端点。

三、模板与继承

Flask 使用 Jinja 2 作为模板引擎。当然,你也可以自由使用其它的模板引擎,但运行 Flask 本身仍然需要 Jinja2 依赖 ,这对启用富扩展是必要的,扩展可以依赖 Jinja2 存在。

Jinja 2 默认配置如下:
1. 所有扩展名为 .html 、 .htm 、 .xml 以及 .xhtml 的模板会开启自动转义
2. 模板可以利用 {% autoescape %} 标签选择自动转义的开关。
3. Flask 在 Jinja2 上下文中插入了几个全局函数和助手,另外还有一些目前默认的值

3.1 标准上下文

  • config -> flask.config, 当前的配置对象。
  • request -> flask.request, 当前的请求对象。
  • session -> flask.session, 当前的会话对象.
  • g -> flask.g, 请求相关的全局变量。
  • url_for() -> flask.url_for()函数
  • get_flashed_message() -> flask.get_flashed_message() 函数.

3.2 Jinja 上下文行为

这些变量被添加到了请求的上下文中,而非全局变量。区别在于,他们默认不会在导入模板的上下文中出现。这样做,一方面是考虑到性能,另一方面是为了让事情显式透明。

如果你想要导入一个需要访问请求对象的宏,有两种可能的方法:

  1. 显式地传入请求或请求对象的属性作为宏的参数。
  2. 与上下文一起(with context)导入宏。

与上下文中一起(with context)导入的方式如下:{% from '_helpers.html' import my_macro with context %}

3.3 标准过滤器

内建的标准过滤器

  • abs(number) -> Return the absolute value of the argument.
  • attr(obj, name) -> Get an attribute of an object. foo|attr(“bar”) works like foo.bar just that always an attribute is returned and items are not looked up.
  • batch(value, linecount, fill_with=None)-> A filter that batches items. It works pretty much like slice just the other way round.
  • capitalize(s) -> Capitalize a value. The first character will be uppercase, all others lowercase.
  • center(value, width=80) -> Centers the value in a field of a given width.
  • default(value, default_value=u”, boolean=False) -> If the value is undefined it will return the passed default value, otherwise the value of the variable
  • dictsort(value, case_sensitive=False, by=’key’) -> Sort a dict and yield (key, value) pairs. Because python dicts are unsorted you may want to use this function to order them by either key or value
  • escape(s) -> Convert the characters &, <, >, ‘, and ” in string s to HTML-safe sequences. Use this
  • filesizeformat(value, binary=False) -> Format the value like a ‘human-readable’ file size (i.e. 13 kB, 4.1 MB, 102 Bytes, etc).
  • first(seq) -> Return the first item of a sequence.
  • float(value, default=0.0) -> Convert the value into a floating point number. If the conversion doesn’t work it will return 0.0.
  • forceescape(value) -> Enforce HTML escaping. This will probably double escape variables.
  • format(value, *args, **kwargs) -> Apply python string formatting on an object
  • groupby(value, attribute) -> Group a sequence of objects by a common attribute
  • indent(s, width=4, indentfirst=False) -> Return a copy of the passed string, each line indented by 4 spaces.
  • int(value, default=0, base=10) -> Convert the value into an integer. If the conversion doesn’t work it will return 0.
  • join(value, d=u”, attribute=None) -> Return a string which is the concatenation of the strings in the sequence.
  • last(seq) -> Return the last item of a sequence.
  • length(object) -> Return the number of items of a sequence or mapping.
  • list(value) -> Convert the value into a list. If it was a string the returned list will be a list of characters.
  • lower(s) -> Convert a value to lowercase.
  • map() -> Applies a filter on a sequence of objects or looks up an attribute. This is useful when dealing with lists of objects but you are really only interested in a certain value of it.
  • pprint(value, verbose=False) -> Pretty print a variable. Useful for debugging.
  • random(seq) -> Return a random item from the sequence.
  • reject() -> Filters a sequence of objects by applying a test to each object, and rejecting the objects with the test succeeding.
  • rejectattr() -> Filters a sequence of objects by applying a test to the specified attribute of each object, and rejecting the objects with the test succeeding.
  • replace(s, old, new, count=None) -> Return a copy of the value with all occurrences of a substring replaced with a new one.
  • reverse(value) -> Reverse the object or return an iterator that iterates over it the other way round.
  • round(value, precision=0, method=’common’) -> Round the number to a given precision. common/ceil/floor
  • safe(value) -> Mark the value as safe which means that in an environment with automatic escaping enabled this variable will not be escaped.
  • select() -> Filters a sequence of objects by applying a test to each object, and only selecting the objects with the test succeeding.
  • selectattr() -> Filters a sequence of objects by applying a test to the specified attribute of each object, and only selecting the objects with the test succeeding.
  • slice(value, slices, fill_with=None) -> Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three ul tags that represent columns
  • sort(value, reverse=False, case_sensitive=False, attribute=None) -> Sort an iterable. Per default it sorts ascending, if you pass it true as first argument it will reverse the sorting.
  • string(object) -> Make a string unicode if it isn’t already. That way a markup string is not converted back to unicode.
  • striptags(value) -> Strip SGML/XML tags and replace adjacent whitespace by one space.
  • sum(iterable, attribute=None, start=0) -> Returns the sum of a sequence of numbers plus the value of parameter ‘start’ (which defaults to 0). When the sequence is empty it returns start.
  • title(s) -> Return a titlecased version of the value. I.e. words will start with uppercase letters, all remaining characters are lowercase.
  • trim(value) -> Strip leading and trailing whitespace.
  • truncate(s, length=255, killwords=False, end=’…’) -> Return a truncated copy of the string. The length is specified with the first parameter which defaults to 255. If the second parameter is true the filter will cut the text at length.
  • upper(s) -> Convert a value to uppercase.
  • urlencode(value) -> Escape strings for use in URLs (uses UTF-8 encoding). It accepts both dictionaries and regular strings as well as pairwise iterables.
  • urlize(value, trim_url_limit=None, nofollow=False, target=None) -> Converts URLs in plain text into clickable links.
  • wordcount(s) -> Count the words in that string.
  • wordwrap(s, width=79, break_long_words=True, wrapstring=None) -> Return a copy of the string passed to the filter wrapped after 79 characters.
  • xmlattr(d, autospace=True) -> Create an SGML/XML attribute string based on the items in a dict. All values that are neither none nor undefined are automatically escaped

3.4 内建测试指令:

  • callable(object) -> Return whether the object is callable (i.e., some kind of function). Note that classes are callable, as are instances with a call() method.
  • defined(value) -> Return true if the variable is defined
  • divisibleby(value, num) -> Check if a variable is divisible by a number.
  • equalto(value, other) -> Check if an object has the same value as another object
  • escaped(value) -> Check if the value is escaped.
  • even(value) -> Return true if the variable is even.
  • iterable(value) -> Check if it’s possible to iterate over an object.
  • lower(value) -> Return true if the variable is lowercased.
  • mapping(value) -> Return true if the object is a mapping (dict etc.)
  • none(value) -> Return true if the variable is none.
  • number(value) -> Return true if the variable is a number.
  • odd(value) -> Return true if the variable is odd.
  • sameas(value, other) -> Check if an object points to the same memory address than another object
  • sequence(value) -> Return true if the variable is a sequence. Sequences are variables that are iterable.
  • string(value) -> Return true if the object is a string.
  • undefined(value) -> Like defined() but the other way round.
  • upper(value) -> Return true if the variable is uppercased.

3.5 全局函数列表

  • range([start, ]stop[, step]) -> Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, …, j-1]; start (!) defaults to 0.
  • lipsum(n=5, html=True, min=20, max=100) -> Generates some lorem ipsum for the template. By default, five paragraphs of HTML are generated with each paragraph between 20 and 100 words.
  • dict(**items) -> A convenient alternative to dict literals. {‘foo’: ‘bar’} is the same as dict(foo=’bar’).
  • class cycler(*items) -> The cycler allows you to cycle among values similar to how loop.cycle works. Unlike loop.cycle, you can use this cycler outside of loops or over multiple loops.
  • reset() -> Resets the cycle to the first item.
  • next() -> Goes one item ahead and returns the then-current item.
  • current -> Returns the current item.
  • class joiner(sep=’, ‘) -> A tiny helper that can be used to “join” multiple sections. A joiner is passed a string and will return that string every time it’s called, except the first time (in which case it returns an empty string).

3.6 扩展

  • i18n -> If the i18n extension is enabled, it’s possible to mark parts in the template as translatable. To mark a section as translatable, you can use trans:<p>{% trans %}Hello {{ user }}!{% endtrans %}</p>
{% autoescape true %}
    Autoescaping is active within this block
{% endautoescape %}

{% autoescape false %}
    Autoescaping is inactive within this block
{% endautoescape %}

3.7 注册过滤器

如果你要在 Jinja2 中注册你自己的过滤器,你有两种方法。你可以把它们手动添加到应用的 jinja_env 或者使用 template_filter() 装饰器。

@app.template_filter('reverse')
def reverse_filter(s):
    return s[::-1]

def reverse_filter(s):
    return s[::-1]
app.jinja_env.filters['reverse'] = reverse_filter

3.8 模板继承

假设有一个基础模板 layout.html

<!doctype html>
<html>
  <head>
    {% block head %}
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
    <title>{% block title %}{% endblock %} - My Webpage</title>
    {% endblock %}
  </head>
<body>
  <div id="content">{% block content %}{% endblock %}</div>
  <div id="footer">
    {% block footer %}
    &copy; Copyright 2010 by <a href="http://domain.invalid/">you</a>.
    {% endblock %}
  </div>
</body>

我们需要在这个的基础上进行继承:

{% extends "layout.html" %}
{% block title %}Index{% endblock %}
{% block head %}
  {{ super() }}
  <style type="text/css">
    .important { color: #336699; }
  </style>
{% endblock %}
{% block content %}
  <h1>Index</h1>
  <p class="important">
    Welcome on my awesome homepage.
{% endblock %}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值