Python开源Web框架Flask学习笔记

Flask是一个使用 Python 编写的轻量级 Web 应用框架。其 WSGI 工具箱采用 Werkzeug ,模板引擎则使用 Jinja2 。

简单环境搭建

  • 参考资料
    项目官网
    中文使用文档

  • 软件安装
    可以通过pip安装,确保机器已安装python-pip

    1
    pip install flask
  • 最小应用
    新建hello.py,代码如下,保存后执行python hello.py,在浏览器访问localhost:5000即可显示

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

其他技巧

运行参数

程序默认只能从本机访问,若要从其他机器远程访问,就需要使用参数启动程序

1
app.run(host='0.0.0.0')

若需要开启调试模式,可以使用参数:
1
app.run(debug=True)

路由与参数

  1. 路由方法:
    1
    2
    3
    4
    5
    6
    @app.route('/login', methods=['GET', 'POST'])
    def login():
    if request.method == 'POST':
    do_the_login()
    else:
    show_the_login_form()
  2. 参数获取:
    • form表单参数
      1
      2
      3
      if request.method == 'POST':
      name = request.form['username']
      passwd = request.form['password']
    • URL参数
      1
      2
      3
      4
      @app.route('/user/<username>')
      def show_user_profile(username):
      # show the user profile for that user
      return 'User %s' % username
    • GET参数
      1
      searchword = request.args.get('q', '')
    • 文件上传
      1
      2
      3
      4
      5
      6
      7
      8
      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))
  3. Cookies的读写:
    1
    2
    3
    username = request.cookies.get('username')
    resp = make_response(render_template(...))
    resp.set_cookie('username', 'the username')
  4. 模板使用:
    1
    2
    3
    4
    5
    from flask import render_template
    @app.route('/hello/')
    @app.route('/hello/<name>')
    def hello(name=None):
    return render_template('hello.html', name=name)
  5. 跨域支持:
    要支持跨域的话只需要做全局配置,安装flask_cors
    1
    pip install flask-cors
    加入以下代码:
    1
    2
    app = Flask(__name__)
    CORS(app, supports_credentials=True)
  6. 配合gevent实现并发访问
    之前的代码运行时只有单实例,如果一个请求还在执行,另一个请求就进不来,简单的使用gevent可以实现并发:
    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
    import time
    from flask import Flask
    from flask_cors import CORS
    from gevent import monkey
    from gevent.pywsgi import WSGIServer

    monkey.patch_all()

    app = Flask(__name__)
    CORS(app)


    @app.route('/index')
    def hello_world():
    time.sleep(10)
    return 'Hello World!'


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


    if __name__ == '__main__':
    http_server = WSGIServer(('0.0.0.0', 5000), app)
    http_server.serve_forever()
    访问/index时,加了个延时,请求十秒以后才会响应,但是访问/test1时不会被阻塞,说明请求可以并发了。

有了这些框架,搭建简单的web应用便可以非常迅速了。

当前网速较慢或者你使用的浏览器不支持博客特定功能,请尝试刷新或换用Chrome、Firefox等现代浏览器