Flask学习之基础知识与功能

Posted chenjunkan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Flask学习之基础知识与功能相关的知识,希望对你有一定的参考价值。

一:flask的背景介绍

Flask是一个基于Python开发并且依赖jinja2模板和Werkzeug WSGI服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收http请求并对请求进行预处理,然后触发Flask框架,开发人员基于Flask框架提供的功能对请求进行相应的处理,并返回给用户,如果要返回给用户复杂的内容时,需要借助jinja2模板来实现对模板的处理,即:将模板和数据进行渲染,将渲染后的字符串返回给用户浏览器。

“微”(micro) 并不表示你需要把整个 Web 应用塞进单个 Python 文件(虽然确实可以 ),也不意味着 Flask 在功能上有所欠缺。微框架中的“微”意味着 Flask 旨在保持核心简单而易于扩展。Flask 不会替你做出太多决策——比如使用何种数据库。而那些 Flask 所选择的——比如使用何种模板引擎——则很容易替换。除此之外的一切都由可由你掌握。如此,Flask 可以与您珠联璧合。

默认情况下,Flask 不包含数据库抽象层、表单验证,或是其它任何已有多种库可以胜任的功能。然而,Flask 支持用扩展来给应用添加这些功能,如同是 Flask 本身实现的一样。众多的扩展提供了数据库集成、表单验证、上传处理、各种各样的开放认证技术等功能。Flask 也许是“微小”的,但它已准备好在需求繁杂的生产环境中投入使用。

二:基本功能使用

1.补充:学习flask首先要了解装饰器的使用方式

a:不带参数的装饰器

技术分享图片
 1 定义一个装饰器函数:
 2 def wrapper(func):
 3     def inner(*args, **kwargs):
 4         return func(*args, **kwargs)
 5     return inner
 6 
 7 用装饰器wrapper函数装饰index函数
 8 @wrapper
 9 def index(request):
10     pass
11 
12 说明:执行@wrapper装饰器等价于:index = wrapper(index),返回值是inner
View Code

b:带参数的装饰器

技术分享图片
 1 定义一个带参数的装饰器函数:
 2 def route(option): 
 3     def inner(func,*args, **kwargs):
 4         url_map[option[path]] = func
 5     return inner
 6 
 7 用route函数装饰index函数,并传入参数
 8 @route({path:/index})
 9 def index(request):
10 
11 说明:
12 1.首先会执行route函数,将对应的参数{path:/index}传入,得到route函数的返回值inner
13 2.执行@inner等价于:inner = inner(index),此时:inner函数中的func = index;*args, **kwarg里面的参数值等于我们传入的值{path:/index},因为是参数是字典的格式,因此是通过**kwargs传入的。
14 3.执行url_map[option[path]] = func,等价于下面的路由关系
15 url_map = {
16             /index: index
17         }
View Code

c:设置元信息

技术分享图片
 1 mport functools
 2 
 3 def wapper(func):
 4 
 5 @functools.wraps(func) # 帮助我们设置函数的元信息
 6 def inner(*args,**kwargs):
 7   return func(*args,**kwargs)
 8 
 9 return inner
10 
11 @wapper
12   def f1():
13   pass
14 
15 @wapper
16   def f2():
17   pass
18 
19 print(f1.__name__)
20 print(f2.__name__)
View Code

2.三大python主流的框架对比:

Django:重武器,内部包含了非常多组件:ORM、Form、ModelForm、缓存、Session、中间件、信号等...
Flask:短小精悍,内部没有太多组件。第三方组件非常丰富。路由比较特殊:基于装饰器来实现,但是究其本质还是通过add_url_rule来实现。
Tornado:异步非阻塞框架(node.js)

3.安装:pip3 install flask

4.本质:Werkzeug WSGI

技术分享图片
 1 werkzeug示例:
 2     from werkzeug.wrappers import Request, Response
 3         @Request.application
 4         def hello(request):
 5         return Response(Hello World!)
 6 
 7         if __name__ == __main__:
 8         from werkzeug.serving import run_simple
 9         run_simple(localhost, 4000, hello)
10                     
11 wsgiref示例:
12     from wsgiref.simple_server import make_server         
13         def runserver(environ, start_response):
14             start_response(200 OK, [(Content-Type, text/html)])
15         return [bytes(<h1>Hello, web!</h1>,encoding=utf-8), ]     
16                  
17     if __name__ == __main__:
18         # obj = WSGIHandler()
19         httpd = make_server(‘‘, 8000, runserver)
20         httpd.serve_forever()
View Code

本质的本质:Werkzeug本质是Socket服务端

技术分享图片
 1 import socket
 2                   
 3 def handle_request(client):
 4     buf = client.recv(1024)
 5     client.send("HTTP/1.1 200 OK

")
 6     client.send("Hello, Seven")
 7                   
 8 def main():
 9     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
10     sock.bind((localhost,8000))
11     sock.listen(5)
12                   
13     while True:
14         connection, address = sock.accept()
15         handle_request(connection)
16         connection.close()
17                   
18 if __name__ == __main__:
19     main()
View Code

5.基本使用

技术分享图片
 1 from flask import Flask
 2 
 3 # 实例化Flask对象app
 4 
 5 app = Flask(__name__)
 6 
 7 # 设置路由关系
 8 
 9 {
10 
11   /:index
12 
13 }
14 
15 @app.route("/")
16 
17 def hello_world():
18   return "hello world"
19 if __name__=="__main__":
20   app.run()
View Code
6.配置文件
技术分享图片
 1 flask中的配置文件是一个flask.config.Config对象(继承字典),默认配置为:
 2     {
 3         DEBUG:                                get_debug_flag(default=False),  是否开启Debug模式
 4         TESTING:                              False,                          是否开启测试模式
 5         PROPAGATE_EXCEPTIONS:                 None,                          
 6         PRESERVE_CONTEXT_ON_EXCEPTION:        None,
 7         SECRET_KEY:                           None,
 8         PERMANENT_SESSION_LIFETIME:           timedelta(days=31),
 9         USE_X_SENDFILE:                       False,
10         LOGGER_NAME:                          None,
11         LOGGER_HANDLER_POLICY:               always,
12         SERVER_NAME:                          None,
13         APPLICATION_ROOT:                     None,
14         SESSION_COOKIE_NAME:                  session,
15         SESSION_COOKIE_DOMAIN:                None,
16         SESSION_COOKIE_PATH:                  None,
17         SESSION_COOKIE_HTTPONLY:              True,
18         SESSION_COOKIE_SECURE:                False,
19         SESSION_REFRESH_EACH_REQUEST:         True,
20         MAX_CONTENT_LENGTH:                   None,
21         SEND_FILE_MAX_AGE_DEFAULT:            timedelta(hours=12),
22         TRAP_BAD_REQUEST_ERRORS:              False,
23         TRAP_HTTP_EXCEPTIONS:                 False,
24         EXPLAIN_TEMPLATE_LOADING:             False,
25         PREFERRED_URL_SCHEME:                 http,
26         JSON_AS_ASCII:                        True,
27         JSON_SORT_KEYS:                       True,
28         JSONIFY_PRETTYPRINT_REGULAR:          True,
29         JSONIFY_MIMETYPE:                     application/json,
30         TEMPLATES_AUTO_RELOAD:                None,
31     }
32  
33 方式一:
34     app.config[DEBUG] = True
35  
36     PS: 由于Config对象本质上是字典,所以还可以使用app.config.update(...)
37  
38 方式二:
39     app.config.from_pyfile("python文件名称")
40         如:
41             settings.py
42                 DEBUG = True
43  
44             app.config.from_pyfile("settings.py")
45  
46     app.config.from_envvar("环境变量名称")
47         环境变量的值为python文件名称名称,内部调用from_pyfile方法
48  
49  
50     app.config.from_json("json文件名称")
51         JSON文件名称,必须是json格式,因为内部会执行json.loads
52  
53     app.config.from_mapping({DEBUG:True})
54         字典格式
55  
56 一般的情况下使用对象的情况较多
57     app.config.from_object("python类或类的路径")
58  
59         app.config.from_object(pro_flask.settings.TestingConfig)
60  
61         settings.py
62  
63             class Config(object):
64                 DEBUG = False
65                 TESTING = False
66                 DATABASE_URI = sqlite://:memory:
67  
68             class ProductionConfig(Config):
69                 DATABASE_URI = mysql://[email protected]/foo
70  
71             class DevelopmentConfig(Config):
72                 DEBUG = True
73  
74             class TestingConfig(Config):
75                 TESTING = True
76  
77         PS: 从sys.path中已经存在路径开始写
78      
79  
80     PS: settings.py文件默认路径要放在程序root_path目录,如果instance_relative_config为True,则就是instance_path目录
View Code
代码示例:
写一个setting.py的文件用来项目所需要的配置:
技术分享图片
 1 class Config(object):
 2     DEBUG = False
 3     TESTING = False
 4     DATABASE_URI = sqlite://:memory:
 5 
 6 # 生产环境
 7 class ProductionConfig(Config):
 8     DATABASE_URI = mysql://[email protected]/foo
 9 
10 #开发环境
11 class DevelopmentConfig(Config):
12     DEBUG = True
13 
14 #测试环境
15 class TestingConfig(Config):
16     TESTING = True
View Code

使用:

技术分享图片
 1 from flask import Flask
 2 
 3 app = Flask(__name__)
 4 app.debug = True
 5 app.secret_key = "asdfasdf"
 6 
 7 # 通过app.confgi.from_object
 8 app.config.from_object("settings.DevelopmentConfig")
 9 
10 @app.route(/)
11 def index():
12     return Hello World!
13 
14 if __name__ == __main__:
15     app.run()
View Code

7.路由系统

  • @app.route(‘/user/<username>‘) # 带字符串的参数
  • @app.route(‘/post/<int:post_id>‘)# 带int类型的参数
  • @app.route(‘/post/<float:post_id>‘)# 带float类型的参数
  • @app.route(‘/post/<path:path>‘)# 带其他的路径
  • @app.route(‘/login‘, methods=[‘GET‘, ‘POST‘]) # 带提交请求的方式

a.路由的源码:

技术分享图片
 1 源码:
 2     def route(self, rule, **options):
 3         def decorator(f):
 4             endpoint = options.pop(endpoint, None)
 5             self.add_url_rule(rule, endpoint, f, **options)
 6             return f
 7         return decorator
 8 
 9 说明:1.当视图函数被app.route函数执行的时候,实际上视图函数被route装饰器装饰,返回的值为decorator;相当于decorator = app.route(/,methods=[GET,POST],endpoint=n1)
10 
11 2.然后再执行@decorator,将参数传进去
View Code

b.示例代码:

技术分享图片
 1 from flask import Flask
 2 
 3 app = Flask(__name__)
 4 app.debug = True
 5 app.secret_key = "asdfasdf"
 6 
 7 """
 8 1. decorator = app.route(‘/‘,methods=[‘GET‘,‘POST‘],endpoint=‘n1‘)
 9     def route(self, rule, **options):
10         # self:app对象
11         # rule= /
12         # options = {methods=[‘GET‘,‘POST‘],endpoint=‘n1‘}
13         def decorator(f):
14             endpoint = options.pop(‘endpoint‘, None)
15             self.add_url_rule(rule, endpoint, f, **options)
16             return f
17         return decorator
18 2. @decorator
19     decorator(index)
20 """
21 @app.route(/,methods=[GET,POST],endpoint=n1)
22 def index():
23     return Hello World!
24 
25 
26 def login():
27     return 登录
28 
29 app.add_url_rule(/login, n2, login, methods=[GET,"POST"])
30 
31 
32 if __name__ == __main__:
33     app.run()
View Code

c.注册路由的基本原理与路由用到的参数

技术分享图片
 1 1.基于CBV的路由:
 2 def auth(func):
 3             def inner(*args, **kwargs):
 4                 print(before)
 5                 result = func(*args, **kwargs)
 6                 print(after)
 7                 return result
 8 
 9         return inner
10 
11         class IndexView(views.View):
12             methods = [GET]
13             decorators = [auth, ]
14 
15             def dispatch_request(self):
16                 print(Index)
17                 return Index!
18 
19         app.add_url_rule(/index, view_func=IndexView.as_view(name=index))  # name=endpoint
20 
21 2.路由的基本参数:
22 @app.route和app.add_url_rule参数:
23             rule,                       URL规则
24             view_func,                  视图函数名称
25             defaults=None,              默认值,当URL中无参数,函数需要参数时,使用defaults={k:v}为函数提供参数
26             endpoint=None,              名称,用于反向生成URL,即: url_for(名称)
27             methods=None,               允许的请求方式,如:["GET","POST"]
28             
29 
30             strict_slashes=None,        对URL最后的 / 符号是否严格要求,
31                                         如:
32                                             @app.route(/index,strict_slashes=False),
33                                                 访问 http://www.xx.com/index/ 或 http://www.xx.com/index均可
34                                             @app.route(/index,strict_slashes=True)
35                                                 仅访问 http://www.xx.com/index 
36             redirect_to=None,           重定向到指定地址
37                                         如:
38                                             @app.route(/index/<int:nid>, redirect_to=/home/<nid>)
39 40                                             def func(adapter, nid):
41                                                 return "/home/888"
42                                             @app.route(/index/<int:nid>, redirect_to=func)
43             subdomain=None,             子域名访问
44                                                 from flask import Flask, views, url_for
45 
46                                                 app = Flask(import_name=__name__)
47                                                 app.config[SERVER_NAME] = wupeiqi.com:5000
48 
49 
50                                                 @app.route("/", subdomain="admin")
51                                                 def static_index():
52                                                     """Flask supports static subdomains
53                                                     This is available at static.your-domain.tld"""
54                                                     return "static.your-domain.tld"
55 
56 
57                                                 @app.route("/dynamic", subdomain="<username>")
58                                                 def username_index(username):
59                                                     """Dynamic subdomains are also supported
60                                                     Try going to user1.your-domain.tld/dynamic"""
61                                                     return username + ".your-domain.tld"
62 
63 
64                                                 if __name__ == __main__:
65                                                     app.run()
66         
View Code

d.CVB示例代码:

技术分享图片
 1 from flask import Flask,views
 2 
 3 app = Flask(__name__)
 4 app.debug = True
 5 app.secret_key = "asdfasdf"
 6 
 7 
 8 def auth(func):
 9     def inner(*args, **kwargs):
10         result = func(*args, **kwargs)
11         return result
12     return inner
13 
14 class IndexView(views.MethodView):
15     methods = [GET]
16     decorators = [auth, ]
17 
18     def get(self):
19         return Index.GET
20 
21     def post(self):
22         return Index.POST
23 
24 app.add_url_rule(/index, view_func=IndexView.as_view(name=index))  # name=endpoint
25 
26 
27 if __name__ == __main__:
28     app.run()
View Code

e.路由参数中redirect_to与defaults的示例代码:

技术分享图片
 1 from flask import Flask
 2 
 3 app = Flask(__name__)
 4 app.debug = True
 5 app.secret_key = "asdfasdf"
 6 
 7 
 8 # @app.route(‘/‘,methods=[‘GET‘,‘POST‘],endpoint=‘n1‘,defaults={‘nid‘:888})
 9 # def index(nid):
10 #     print(nid)
11 #     return ‘Hello World!‘
12 #
13 #
14 # def login():
15 #     return ‘登录‘
16 # app.add_url_rule(‘/login‘, ‘n2‘, login, methods=[‘GET‘,"POST"])
17 
18 
19 @app.route(/index, methods=[GET, POST], endpoint=n1, redirect_to="/index2")
20 def index():
21     return 公司老首页
22 
23 
24 @app.route(/index2, methods=[GET, POST], endpoint=n2)
25 def index2():
26     return 公司新首页
27 
28 
29 if __name__ == __main__:
30     app.run()
View Code

f:路由参数中subdomain的示例代码:

技术分享图片
 1 from flask import Flask, views, url_for
 2 
 3 app = Flask(import_name=__name__)
 4 app.config[SERVER_NAME] = chenjunkan.com:5000
 5 
 6 
 7 @app.route("/", subdomain="admin")
 8 def static_index():
 9     """Flask supports static subdomains
10     This is available at static.your-domain.tld"""
11     return "xxxxxx.your-domain.tld"
12 
13 
14 @app.route("/dynamic", subdomain="<username>")
15 def username_index(username):
16     """Dynamic subdomains are also supported
17     Try going to user1.your-domain.tld/dynamic"""
18     return username + ".your-domain.tld"
19 
20 
21 if __name__ == __main__:
22     app.run()
View Code

g:自定义正则路由匹配

技术分享图片
 1 from flask import Flask, views, url_for
 2             from werkzeug.routing import BaseConverter
 3 
 4             app = Flask(import_name=__name__)
 5 
 6 
 7             class RegexConverter(BaseConverter):
 8                 """
 9                 自定义URL匹配正则表达式
10                 """
11                 def __init__(self, map, regex):
12                     super(RegexConverter, self).__init__(map)
13                     self.regex = regex
14 
15                 def to_python(self, value):
16                     """
17                     路由匹配时,匹配成功后传递给视图函数中参数的值
18                     :param value: 
19                     :return: 
20                     """
21                     return int(value)
22 
23                 def to_url(self, value):
24                     """
25                     使用url_for反向生成URL时,传递的参数经过该方法处理,返回的值用于生成URL中的参数
26                     :param value: 
27                     :return: 
28                     """
29                     val = super(RegexConverter, self).to_url(value)
30                     return val
31 
32             # 添加到flask中
33             app.url_map.converters[regex] = RegexConverter
34 
35 
36             @app.route(/index/<regex("d+"):nid>)
37             def index(nid):
38                 print(url_for(index, nid=888))
39                 return Index
40 
41 
42             if __name__ == __main__:
43                 app.run()
View Code

8.模板

1、模板的使用

Flask使用的是Jinja2模板,所以其语法和Django无差别

2、自定义模板方法

Flask中自定义模板方法的方式和Bottle相似,创建一个函数并通过参数的形式传入render_template

注意:Markup等价django的mark_safe

9.请求跟响应

技术分享图片
 1   from flask import Flask
 2     from flask import request
 3     from flask import render_template
 4     from flask import redirect
 5     from flask import make_response
 6 
 7     app = Flask(__name__)
 8 
 9 
10     @app.route(/login.html, methods=[GET, "POST"])
11     def login():
12 
13         # 请求相关信息
14         # request.method
15         # request.args
16         # request.form
17         # request.values
18         # request.cookies
19         # request.headers
20         # request.path
21         # request.full_path
22         # request.script_root
23         # request.url
24         # request.base_url
25         # request.url_root
26         # request.host_url
27         # request.host
28         # request.files
29         # obj = request.files[‘the_file_name‘]
30         # obj.save(‘/var/www/uploads/‘ + secure_filename(f.filename))
31 
32         # 响应相关信息
33         # return "字符串"
34         # return render_template(‘html模板路径‘,**{})
35         # return redirect(‘/index.html‘)
36 
37         # response = make_response(render_template(‘index.html‘))
38         # response是flask.wrappers.Response类型
39         # response.delete_cookie(‘key‘)
40         # response.set_cookie(‘key‘, ‘value‘)
41         # response.headers[‘X-Something‘] = ‘A value‘
42         # return response
43 
44 
45         return "内容"
46 
47     if __name__ == __main__:
48         app.run()
View Code

10:session的使用

除请求对象之外,还有一个 session 对象。它允许你在不同请求间存储特定用户的信息。它是在 Cookies 的基础上实现的,并且对 Cookies 进行密钥签名要使用会话,你需要设置一个密钥。

  • 设置:session[‘username‘] = ‘xxx‘

  • 删除:session.pop(‘username‘, None)

a.基本使用

技术分享图片
 1 from flask import Flask, session, redirect, url_for, escape, request
 2  
 3 app = Flask(__name__)
 4  
 5 @app.route(/)
 6 def index():
 7     if username in session:
 8         return Logged in as %s % escape(session[username])
 9     return You are not logged in
10  
11 @app.route(/login, methods=[GET, POST])
12 def login():
13     if request.method == POST:
14         session[username] = request.form[username]
15         return redirect(url_for(index))
16     return ‘‘‘
17         <form action="" method="post">
18             <p><input type=text name=username>
19             <p><input type=submit value=Login>
20         </form>
21     ‘‘‘
22  
23 @app.route(/logout)
24 def logout():
25     # remove the username from the session if it‘s there
26     session.pop(username, None)
27     return redirect(url_for(index))
28  
29 # set the secret key.  keep this really secret:
30 app.secret_key = A0Zr98j/3yX R~XHH!jmN]LWX/,?RT
View Code

b.自定义session,后续的请求上下文中会详细介绍Flask-Session

技术分享图片
  1 pip3 install Flask-Session
  2         
  3         run.py
  4             from flask import Flask
  5             from flask import session
  6             from pro_flask.utils.session import MySessionInterface
  7             app = Flask(__name__)
  8 
  9             app.secret_key = A0Zr98j/3yX R~XHH!jmN]LWX/,?RT
 10             app.session_interface = MySessionInterface()
 11 
 12             @app.route(/login.html, methods=[GET, "POST"])
 13             def login():
 14                 print(session)
 15                 session[user1] = alex
 16                 session[user2] = alex
 17                 del session[user2]
 18 
 19                 return "内容"
 20 
 21             if __name__ == __main__:
 22                 app.run()
 23 
 24         session.py
 25             #!/usr/bin/env python
 26             # -*- coding:utf-8 -*-
 27             import uuid
 28             import json
 29             from flask.sessions import SessionInterface
 30             from flask.sessions import SessionMixin
 31             from itsdangerous import Signer, BadSignature, want_bytes
 32 
 33 
 34             class MySession(dict, SessionMixin):
 35                 def __init__(self, initial=None, sid=None):
 36                     self.sid = sid
 37                     self.initial = initial
 38                     super(MySession, self).__init__(initial or ())
 39 
 40 
 41                 def __setitem__(self, key, value):
 42                     super(MySession, self).__setitem__(key, value)
 43 
 44                 def __getitem__(self, item):
 45                     return super(MySession, self).__getitem__(item)
 46 
 47                 def __delitem__(self, key):
 48                     super(MySession, self).__delitem__(key)
 49 
 50 
 51 
 52             class MySessionInterface(SessionInterface):
 53                 session_class = MySession
 54                 container = {}
 55 
 56                 def __init__(self):
 57                     import redis
 58                     self.redis = redis.Redis()
 59 
 60                 def _generate_sid(self):
 61                     return str(uuid.uuid4())
 62 
 63                 def _get_signer(self, app):
 64                     if not app.secret_key:
 65                         return None
 66                     return Signer(app.secret_key, salt=flask-session,
 67                                   key_derivation=hmac)
 68 
 69                 def open_session(self, app, request):
 70                     """
 71                     程序刚启动时执行,需要返回一个session对象
 72                     """
 73                     sid = request.cookies.get(app.session_cookie_name)
 74                     if not sid:
 75                         sid = self._generate_sid()
 76                         return self.session_class(sid=sid)
 77 
 78                     signer = self._get_signer(app)
 79                     try:
 80                         sid_as_bytes = signer.unsign(sid)
 81                         sid = sid_as_bytes.decode()
 82                     except BadSignature:
 83                         sid = self._generate_sid()
 84                         return self.session_class(sid=sid)
 85 
 86                     # session保存在redis中
 87                     # val = self.redis.get(sid)
 88                     # session保存在内存中
 89                     val = self.container.get(sid)
 90 
 91                     if val is not None:
 92                         try:
 93                             data = json.loads(val)
 94                             return self.session_class(data, sid=sid)
 95                         except:
 96                             return self.session_class(sid=sid)
 97                     return self.session_class(sid=sid)
 98 
 99                 def save_session(self, app, session, response):
100                     """
101                     程序结束前执行,可以保存session中所有的值
102                     如:
103                         保存到resit
104                         写入到用户cookie
105                     """
106                     domain = self.get_cookie_domain(app)
107                     path = self.get_cookie_path(app)
108                     httponly = self.get_cookie_httponly(app)
109                     secure = self.get_cookie_secure(app)
110                     expires = self.get_expiration_time(app, session)
111 
112                     val = json.dumps(dict(session))
113 
114                     # session保存在redis中
115                     # self.redis.setex(name=session.sid, value=val, time=app.permanent_session_lifetime)
116                     # session保存在内存中
117                     self.container.setdefault(session.sid, val)
118 
119                     session_id = self._get_signer(app).sign(want_bytes(session.sid))
120 
121                     response.set_cookie(app.session_cookie_name, session_id,
122                                         expires=expires, httponly=httponly,
123                                         domain=domain, path=path, secure=secure)
View Code

c:第三方的session

技术分享图片
 1 """
 2 pip3 install redis
 3 pip3 install flask-session
 4 
 5 """
 6 
 7 
 8 from flask import Flask, session, redirect
 9 from flask.ext.session import Session
10 
11 
12 app = Flask(__name__)
13 app.debug = True
14 app.secret_key = asdfasdfasd
15 
16 
17 app.config[SESSION_TYPE] = redis
18 from redis import Redis
19 app.config[SESSION_REDIS] = Redis(host=192.168.0.94,port=6379)
20 Session(app)
21 
22 
23 @app.route(/login)
24 def login():
25     session[username] = alex
26     return redirect(/index)
27 
28 
29 @app.route(/index)
30 def index():
31     name = session[username]
32     return name
33 
34 
35 if __name__ == __main__:
36     app.run()
View Code

11:Blueprint

  • 蓝图URL前缀:xxx = Blueprint(‘account‘, __name__,url_prefix=‘/xxx‘)
  • 蓝图子域名:xxx = Blueprint(‘account‘, __name__,subdomain=‘admin‘)

示例代码:

12:message

message是一个基于Session实现的用于保存数据的集合,其特点是:使用一次就删除。

技术分享图片
 1 from flask import Flask, flash, redirect, render_template, request, get_flashed_messages
 2 
 3         app = Flask(__name__)
 4         app.secret_key = some_secret
 5 
 6 
 7         @app.route(/)
 8         def index1():
 9             messages = get_flashed_messages()
10             print(messages)
11             return "Index1"
12 
13 
14         @app.route(/set)
15         def index2():
16             v = request.args.get(p)
17             flash(v)
18             return ok
19 
20 
21         if __name__ == "__main__":
22             app.run()
View Code

13:中间件

技术分享图片
 1 from flask import Flask, flash, redirect, render_template, request
 2  
 3 app = Flask(__name__)
 4 app.secret_key = some_secret
 5  
 6 @app.route(/)
 7 def index1():
 8     return render_template(index.html)
 9  
10 @app.route(/set)
11 def index2():
12     v = request.args.get(p)
13     flash(v)
14     return ok
15  
16 class MiddleWare:
17     def __init__(self,wsgi_app):
18         self.wsgi_app = wsgi_app
19  
20     def __call__(self, *args, **kwargs):
21  
22         return self.wsgi_app(*args, **kwargs)
23  
24 if __name__ == "__main__":
25     app.wsgi_app = MiddleWare(app.wsgi_app)
26     app.run(port=9999)
View Code

14:请求扩展

技术分享图片
 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 from flask import Flask, Request, render_template
 4 
 5 app = Flask(__name__, template_folder=templates)
 6 app.debug = True
 7 
 8 
 9 @app.before_first_request
10 def before_first_request1():
11     print(before_first_request1)
12 
13 
14 @app.before_first_request
15 def before_first_request2():
16     print(before_first_request2)
17 
18 
19 @app.before_request
20 def before_request1():
21     Request.nnn = 123
22     print(before_request1)
23 
24 
25 @app.before_request
26 def before_request2():
27     print(before_request2)
28 
29 
30 @app.after_request
31 def after_request1(response):
32     print(before_request1, response)
33     return response
34 
35 
36 @app.after_request
37 def after_request2(response):
38     print(before_request2, response)
39     return response
40 
41 
42 @app.errorhandler(404)
43 def page_not_found(error):
44     return This page does not exist, 404
45 
46 
47 @app.template_global()
48 def sb(a1, a2):
49     return a1 + a2
50 
51 
52 @app.template_filter()
53 def db(a1, a2, a3):
54     return a1 + a2 + a3
55 
56 
57 @app.route(/)
58 def hello_world():
59     return render_template(hello.html)
60 
61 
62 if __name__ == __main__:
63     app.run()
View Code

15:flask插件

http://flask.pocoo.org/extensions/

 



以上是关于Flask学习之基础知识与功能的主要内容,如果未能解决你的问题,请参考以下文章

Python面向对象学习之八,装饰器

Python框架学习之Flask中的常用扩展包

Flask Web开发学习之“HelloWorld”

Flask Web开发学习之“HelloWorld”

flask学习之配置文件的加载和动态url的使用

大数据学习之MapReduce基础与Yarn集群安装09