Flask

官网:http://flask.pocoo.org/

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

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

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

安装

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

werkzeug

一、第一次

  1. from flask import Flask
  2. app = Flask(__name__)
  3.  
  4. @app.route("/")
  5. def hello():
  6. return "Hello World!"
  7.  
  8. if __name__ == "__main__":
  9. 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. DEFAULT_CONVERTERS = {
  2. 'default': UnicodeConverter,
  3. 'string': UnicodeConverter,
  4. 'any': AnyConverter,
  5. 'path': PathConverter,
  6. 'int': IntegerConverter,
  7. 'float': FloatConverter,
  8. 'uuid': UUIDConverter,
  9. }

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

三、模板

1、模板的使用

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

2、自定义模板方法

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

  1. <!DOCTYPE html>
  2. <html>
  3. <head lang="en">
  4. <meta charset="UTF-8">
  5. <title></title>
  6. </head>
  7. <body>
  8. <h1>自定义函数</h1>
  9. {{ww()|safe}}
  10.  
  11. </body>
  12. </html>

index.html

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. from flask import Flask,render_template
  4. app = Flask(__name__)
  5.  
  6. def myfunc():
  7. return '<h1>Redhat</h1>'
  8.  
  9. @app.route('/login', methods=['GET', 'POST'])
  10. def login():
  11. return render_template('index.html', ww=myfunc)
  12.  
  13. app.run()

四、公共组件

1、请求

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

  1. request.method
  2. request.args
  3. request.form
  4. request.values
  5. request.files
  6. request.cookies
  7. request.headers
  8. request.path
  9. request.full_path
  10. request.script_root
  11. request.url
  12. request.base_url
  13. request.url_root
  14. request.host_url
  15. request.host
  1. @app.route('/login', methods=['POST', 'GET'])
  2. def login():
  3. error = None
  4. if request.method == 'POST':
  5. if valid_login(request.form['username'],
  6. request.form['password']):
  7. return log_the_user_in(request.form['username'])
  8. else:
  9. error = 'Invalid username/password'
  10. # the code below is executed if the request method
  11. # was GET or the credentials were invalid
  12. return render_template('login.html', error=error)

表单处理

  1. from flask import request
  2. from werkzeug import secure_filename
  3.  
  4. @app.route('/upload', methods=['GET', 'POST'])
  5. def upload_file():
  6. if request.method == 'POST':
  7. f = request.files['the_file']
  8. f.save('/var/www/uploads/' + secure_filename(f.filename))
  9. ...

上传文件

  1. from flask import request
  2.  
  3. @app.route('/setcookie/')
  4. def index():
  5. username = request.cookies.get('username')
  6. # use cookies.get(key) instead of cookies[key] to not get a
  7. # KeyError if the cookie is missing.
  8.  
  9. from flask import make_response
  10.  
  11. @app.route('/getcookie')
  12. def index():
  13. resp = make_response(render_template(...))
  14. resp.set_cookie('username', 'the username')
  15. return resp

cookie处理

2、响应

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

a.字符串

  1. @app.route('/index/', methods=['GET', 'POST'])
  2. def index():
  3. return "index"

b.模板引擎

  1. from flask import Flask,render_template,request
  2. app = Flask(__name__)
  3.  
  4. @app.route('/index/', methods=['GET', 'POST'])
  5. def index():
  6. return render_template("index.html")
  7.  
  8. app.run()

c.重定向

  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. from flask import Flask, redirect, url_for
  4. app = Flask(__name__)
  5.  
  6. @app.route('/index/', methods=['GET', 'POST'])
  7. def index():
  8. # return redirect('/login/')
  9. return redirect(url_for('login'))
  10.  
  11. @app.route('/login/', methods=['GET', 'POST'])
  12. def login():
  13. return "LOGIN"
  14.  
  15. app.run()

d.错误页面

  1. from flask import Flask, abort, render_template
  2. app = Flask(__name__)
  3.  
  4. @app.route('/e1/', methods=['GET', 'POST'])
  5. def index():
  6. abort(404, 'Nothing')
  7. app.run()

指定URL,简单错误

  1. from flask import Flask, abort, render_template
  2. app = Flask(__name__)
  3.  
  4. @app.route('/index/', methods=['GET', 'POST'])
  5. def index():
  6. return "OK"
  7.  
  8. @app.errorhandler(404)
  9. def page_not_found(error):
  10. return render_template('page_not_found.html'), 404
  11.  
  12. app.run()

e.设置相应信息

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

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

3、Session

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

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

  • 删除:session.pop('username', None)
  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'

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

Python自动化运维之30、Flask框架的更多相关文章

  1. Python自动化运维:技术与最佳实践 PDF高清完整版|网盘下载内附地址提取码|

    内容简介: <Python自动化运维:技术与最佳实践>一书在中国运维领域将有“划时代”的重要意义:一方面,这是国内第一本从纵.深和实践角度探讨Python在运维领域应用的著作:一方面本书的 ...

  2. python自动化运维之CMDB篇-大米哥

    python自动化运维之CMDB篇 视频地址:复制这段内容后打开百度网盘手机App,操作更方便哦 链接:https://pan.baidu.com/s/1Oj_sglTi2P1CMjfMkYKwCQ  ...

  3. Day1 老男孩python自动化运维课程学习笔记

    2017年1月7日老男孩python自动化运维课程正式开课 第一天学习内容: 上午 1.python语言的基本介绍 python语言是一门解释型的语言,与1989年的圣诞节期间,吉多·范罗苏姆为了在阿 ...

  4. python自动化运维学习第一天--day1

    学习python自动化运维第一天自己总结的作业 所使用到知识:json模块,用于数据转化sys.exit 用于中断循环退出程序字符串格式化.format字典.文件打开读写with open(file, ...

  5. 【目录】Python自动化运维

    目录:Python自动化运维笔记 Python自动化运维 - day2 - 数据类型 Python自动化运维 - day3 - 函数part1 Python自动化运维 - day4 - 函数Part2 ...

  6. python自动化运维篇

    1-1 Python运维-课程简介及基础 1-2 Python运维-自动化运维脚本编写 2-1 Python自动化运维-Ansible教程-Ansible介绍 2-2 Python自动化运维-Ansi ...

  7. Python自动化运维的职业发展道路(暂定)

    Python职业发展之路 Python自动化运维工程 Python基础 Linux Shell Fabric Ansible Playbook Zabbix Saltstack Puppet Dock ...

  8. Python自动化运维 技术与最佳实践PDF高清完整版免费下载|百度云盘|Python基础教程免费电子书

    点击获取提取码:7bl4 一.内容简介 <python自动化运维:技术与最佳实践>一书在中国运维领域将有"划时代"的重要意义:一方面,这是国内第一本从纵.深和实践角度探 ...

  9. python自动化运维之路~DAY5

    python自动化运维之路~DAY5 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.模块的分类 模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数 ...

随机推荐

  1. Centos 6.4 openNebula4

    我们实验室的 OpenNebula 3.2 已经很稳定的运行了两年,除了开头一个月不熟悉这套云计算软件有点乱.容易犯错外接下来的时间里都很稳定,期间还包括一次防火演习(突然拉闸似断电)和安全检查(计划 ...

  2. Spark 中的join方式(pySpark)

    spark基础知识请参考spark官网:http://spark.apache.org/docs/1.2.1/quick-start.html 无论是mapreduce还是spark ,分布式框架的性 ...

  3. Broken line - SGU 124(判断点与多边形的关系)

    题目大意:RT 分析:构造一条射线,如果穿越偶数条边,那么就在多边形外面,如果穿越奇数条边,那么就在多边形里面. 代码如下: ===================================== ...

  4. SQL string类型的数据按int类型排序 分类: SQL Server 2014-12-08 16:56 393人阅读 评论(0) 收藏

    说明: 我在做wms进销存软件时,发现一个问题:一张入库单(T_OutIn_BoxTop),入库扫描时要分成多箱,箱号(BoxTop_No)可以是数字也可以是字符串,所以箱号只能是字符串类型的,问题来 ...

  5. 推荐一个网站——聚合了微软的文件的Knowledge Base下载地址

    Microsoft Files是一个微软的文件数据库,从这里可以很方便的找到各个文件版本对应的下载链接. 比如今天debug需要找一个特定版本的sos.dll,从这个网站就很方便的给出了这个sos.d ...

  6. HDU 2069 Coin Change

    Coin Change Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total S ...

  7. QT+QT creator+OpenCV图像灰度化

    1).pro文件 #------------------------------------------------- # # Project created by QtCreator 2014-05 ...

  8. Android中Style和Theme的使用

    Style: Style是View中一些属性的集合,包括height,padding,font color,background等等,Style单独定义在xml文件中,类似与web页面中css的角色, ...

  9. android 17 activity生命周期

    手机指南针传感器处于手机头部. Activity生命周期: 启动. onCreat()方法:初始化布局对象,设置监听器. onstart()方法:注册监听器. onResume():activity已 ...

  10. 实现 Castor 数据绑定--转

    第 1 部分: 安装和设置 Castor 数据绑定风靡一时 在 XML 新闻组.邮件列表和网站的讨论论坛中(在 参考资料 中可以找到这些内容的链接),最常见的一个主题就是数据绑定.Java 和 XML ...