flask介绍

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

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

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

werkzeug​
1
2
3
4
5
6
7
8
9
10
11
12
13
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from werkzeug.wrappers import Request, Response
 
@Request.application
def hello(request):
    return Response('Hello World!')
 
if __name__ == '__main__':
    from werkzeug.serving import run_simple
    run_simple('localhost', 4000, hello)
 
werkzeug

基本使用

1
2
3
4
5
6
7
8
9
from flask import Flask
app = Flask(__name__)
  
@app.route("/")
def hello():
    return "Hello World!"
  
if __name__ == "__main__":
    app.run()

具体介绍

一、路由系统

  • @app.route('/user/<username>')

  • @app.route('/post/<int:post_id>')

  • @app.route('/post/<float:post_id>')

  • @app.route('/post/<path:path>')

  • @app.route('/login', methods=['GET', 'POST'])

常用路由系统有以上五种,所有的路由系统都是基于一下对应关系来处理:

1
2
3
4
5
6
7
8
9
DEFAULT_CONVERTERS = {
    'default':          UnicodeConverter,
    'string':           UnicodeConverter,
    'any':              AnyConverter,
    'path':             PathConverter,
    'int':              IntegerConverter,
    'float':            FloatConverter,
    'uuid':             UUIDConverter,
}

注:对于Flask默认不支持直接写正则表达式的路由,不过可以通过自定义来实现,见:https://segmentfault.com/q/1010000000125259

二、模板

1、模板的使用

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

2、自定义模板方法

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

index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <h1>自定义函数</h1>
    {{ww()|safe}}
 
</body>
</html>
 
index.html
index.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Flask,render_template
app = Flask(__name__)
  
  
def wupeiqi():
    return '<h1>Wupeiqi</h1>'
  
@app.route('/login', methods=['GET', 'POST'])
def login():
    return render_template('login.html', ww=wupeiqi)
  
app.run()

三、公共组件

1、请求

对于Http请求,Flask会讲请求信息封装在request中(werkzeug.wrappers.BaseRequest),提供的如下常用方法和字段以供使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
request.method
request.args
request.form
request.values
request.files
request.cookies
request.headers
request.path
request.full_path
request.script_root
request.url
request.base_url
request.url_root
request.host_url
request.host
表单处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@app.route('/login', methods=['POST', 'GET'])
def login():
    error = None
    if request.method == 'POST':
        if valid_login(request.form['username'],
                       request.form['password']):
            return log_the_user_in(request.form['username'])
        else:
            error = 'Invalid username/password'
    # the code below is executed if the request method
    # was GET or the credentials were invalid
    return render_template('login.html', error=error)
 
表单处理Demo
上传文件
1
2
3
4
5
6
7
8
9
10
11
from flask import request
from werkzeug import secure_filename
 
@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['the_file']
        f.save('/var/www/uploads/' + secure_filename(f.filename))
    ...
 
上传文件Demo
cookie操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
from flask import request
 
@app.route('/setcookie/')
def index():
    username = request.cookies.get('username')
    # use cookies.get(key) instead of cookies[key] to not get a
    # KeyError if the cookie is missing.
 
 
 
 
from flask import make_response
 
@app.route('/getcookie')
def index():
    resp = make_response(render_template(...))
    resp.set_cookie('username', 'the username')
    return resp
 
Cookie操作

2、响应

当用户请求被开发人员的逻辑处理完成之后,会将结果发送给用户浏览器,那么就需要对请求做出相应的响应。

a.字符串
1
2
3
@app.route('/index/', methods=['GET''POST'])
def index():
    return "index"
b.模板引擎
1
2
3
4
5
6
7
8
from flask import Flask,render_template,request
app = Flask(__name__)
 
@app.route('/index/', methods=['GET''POST'])
def index():
    return render_template("index.html")
 
app.run()
c.重定向
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Flask, redirect, url_for
app = Flask(__name__)
 
@app.route('/index/', methods=['GET''POST'])
def index():
    # return redirect('/login/')
    return redirect(url_for('login'))
 
@app.route('/login/', methods=['GET''POST'])
def login():
    return "LOGIN"
 
app.run()
d.错误页面
指定URL,简单错误
1
2
3
4
5
6
7
8
9
from flask import Flask, abort, render_template
app = Flask(__name__)
 
@app.route('/e1/', methods=['GET', 'POST'])
def index():
    abort(404, 'Nothing')
app.run()
 
指定URL,简单错误
1
2
3
4
5
6
7
8
9
10
11
12
from flask import Flask, abort, render_template
app = Flask(__name__)
 
@app.route('/index/', methods=['GET''POST'])
def index():
    return "OK"
 
@app.errorhandler(404)
def page_not_found(error):
    return render_template('page_not_found.html'), 404
 
app.run()
e.设置相应信息

使用make_response可以对相应的内容进行操作

1
2
3
4
5
6
7
8
9
10
11
12
13
from flask import Flask, abort, render_template,make_response
app = Flask(__name__)
 
@app.route('/index/', methods=['GET''POST'])
def index():
    response = make_response(render_template('index.html'))
    # response是flask.wrappers.Response类型
    # response.delete_cookie
    # response.set_cookie
    # response.headers['X-Something'] = 'A value'
    return response
 
app.run()

3、Session​

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

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

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

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

Flask还有众多其他功能,更多参见:
    http://docs.jinkan.org/docs/flask/
    http://flask.pocoo.org/

web框架--flask的更多相关文章

  1. 用Python手把手教你搭建一个web框架-flask微框架!

    在之前的文章当中,小编已经教过大家怎么搭建一个Django框架,今天我们来探索另外的一种框架的搭建,这个框架就是web框架-flask微框架啦!首先我们带着以下的几个问题来阅读本文: 1.flask是 ...

  2. python web框架Flask——csrf攻击

    CSRF是什么? (Cross Site Request Forgery, 跨站域请求伪造)是一种网络的攻击方式,它在 2007 年曾被列为互联网 20 大安全隐患之一,也被称为“One Click ...

  3. Python超级明星WEB框架Flask

    Flask简介 Flask是一个相对于Django而言轻量级的Web框架. 和Django大包大揽不同,Flask建立于一系列的开源软件包之上,这其中 最主要的是WSGI应用开发库Werkzeug和模 ...

  4. 【Flask】微型web框架flask大概介绍

    Flask Flask是一个基于python的,微型web框架.之所以被称为微型是因为其核心非常简单,同时具有很强的扩展能力.它几乎不给使用者做任何技术决定. 安装flask时应该注意其必须的几个支持 ...

  5. pthon web框架flask(一)

    pthon web框架优劣: 知乎上有一个讨论Python 有哪些好的 Web 框架?,从这个讨论中最后我选择了flask,原因是: Django,流行但是笨重,还麻烦,人生苦短,肯定不选 web.p ...

  6. Python轻量Web框架Flask使用

    http://blog.csdn.net/jacman/article/details/49098819 目录(?)[+] Flask安装 Python开发工具EclipsePyDev准备 Flask ...

  7. Python Web框架——Flask

    简介 Flask是一个基于Python开发并且依赖jinja2模板和Werkzeug WSGI服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收http请求并对请求进行预处理 ...

  8. Web 框架 Flask

    Flask是一个基于Python开发并且依赖jinja2模板和Werkzeug WSGI服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收http请求并对请求进行预处理,然后 ...

  9. Python web框架 flask

    Flask是一个基于Python开发并且依赖jinja2模板和Werkzeug WSGI服务的一个微型框架,对于Werkzeug本质是Socket服务端,其用于接收http请求并对请求进行预处理,然后 ...

随机推荐

  1. 实现IBatisNet的Dialect分页

    Hibernate有其独有的Dialect,对不同的数据库实现sql的分页. 用过MyBatis for Java,它可以拦截SQL语句,通过Interceptor对原始的sql语句进行修改,也就是可 ...

  2. C#使用Timer.Interval指定时间间隔与指定时间执行事件

    C#中,Timer是一个定时器,它可以按照指定的时间间隔或者指定的时间执行一个事件. 指定时间间隔是指按特定的时间间隔,如每1分钟.每10分钟.每1个小时等执行指定事件: 指定时间是指每小时的第30分 ...

  3. MVC中调用Public_Class时,VS2012老提示:当前上下文中不存在名称“Json”的解决方法

    TMD,老TMD困扰我,每次新建MVC项目后就提示这个,原因在此: public class Public_Class   <==此处应为:Public_Class : Controller { ...

  4. Oracle expdp/impdp导出导入命令及数据库备份

    使用EXPDP和IMPDP时应该注意的事项: EXP和IMP是客户端工具程序,它们既可以在客户端使用,也可以在服务端使用. EXPDP和IMPDP是服务端的工具程序,他们只能在ORACLE服务端使用, ...

  5. Windows Phone App的dump文件实例分析- System.ExecutionEngineException

    前言 在开始这篇文章之前我们先来讲讲如何从高度优化的Release版的Dump中找到正确的异常上下文地址,并手动恢复异常发生的第一现场. 1. 什么是异常上下文 简单来说,在windows体系的操作系 ...

  6. jenkins + Git 搭建持续集成环境

    持续集成通过自动化构建.自动化测试以及自动化部署加上较高的集成频率保证了开发系统中的问题能迅速被发现和修复,降低了集成失败的风险,使得系统在开发中始终保持在一个稳定健康的集成状态.jenkins是目前 ...

  7. 每周一书-编写高质量代码:改善C程序代码的125个建议

    首先说明,本周活动有效时间为2016年8月28日到2016年9月4日.本周为大家送出的书是由机械工业出版社出版,马伟编著的<编写高质量代码:改善C程序代码的125个建议>. 编辑推荐 10 ...

  8. Fluxion 实战答疑

    实战文章<实战-Fluxion与wifi热点伪造.钓鱼.中间人攻击.wifi破解>发布之后,大家响应热烈,不过也遇到了很多问题.微信后台被各种提问挤爆了,于是抓紧时间出了这篇答疑. 0x0 ...

  9. .net开发笔记(十八) winform中的等待框

    winform中很多任务是需要在后台线程(或类似)中完成的,也就是说,经常容易涉及到UI界面与后台工作线程之间的交互.比如UI界面控制后台工作的执行(启动.暂停.停止等),后台工作进度在UI界面上的显 ...

  10. Android 综合揭秘 —— 全面剖释 Service 服务

    引言 Service 服务是 Android 系统最常用的四大部件之一,Android 支持 Service 服务的原因主要目的有两个,一是简化后台任务的实现,二是实现在同一台设备当中跨进程的远程信息 ...