Flask 框架

发布时间: 更新时间: 总字数:332 阅读时间:1m 作者: IP上海 分享 网址

Flask 框架介绍

介绍

安装

pip install flask
  • main.py
from flask import Flask

app = Flask(__name__)


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


# if __name__ == '__main__':
#     app.run()
# app.run(host="unix:///tmp/app.sock")
# FLASK_APP=app.py flask run --host=unix:///tmp/app.sock
  • 使用 gunicorn 运行
$ gunicorn main:app
[8267] [INFO] Starting gunicorn 19.10.0
[8267] [INFO] Listening at: http://127.0.0.1:8000 (8267)
[8267] [INFO] Using worker: sync
[8272] [INFO] Booting worker with pid: 8272

# gunicorn -w 4 package:app --bind unix:/tmp/app.sock
  • 访问
$ curl http://127.0.0.1:8000
Hello World!

其他

F&Q

RuntimeError: Working outside of application context

// app = Flask(__name__)
with app.app_context():
    ...

使用 uwsgi 发布 request.files 为空

request.files 返回值为 ImmutableMultiDict([])

解决方式:

  • 通过 nginx 代理(测试可用)
  • form 表单配置 enctype="multipart/form-data"
  • 配置 MAX_CONTENT_LENGTH
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024  # 10MB
  • uwsgi.ini 配置
[uwsgi]
...
http = :8000
http-timeout = 120
http-keepalive = true
http-auto-chunked = true
http-write-timeout = 120
http-sendfile = true
http-chunked-request = true
post-buffering = 8192
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数