在没有Nginx的情况下运行Flask应用程序

时间:2020-06-03 09:23:21

标签: python-3.x nginx flask uwsgi

正在运行没有Nginx或其他Web服务器的Flask应用程序?

uWSGI可以同时作为Web服务器和应用程序服务器吗?

例如,独立WSGI容器 https://flask.palletsprojects.com/en/1.1.x/deploying/wsgi-standalone/ 但是,再次建议使用HTTP服务器。为什么? uWSGI无法处理HTTP请求吗?

我阅读了有关部署Flask应用程序的不同文章。他们说,我需要uWSGI和nginx-一种流行的选择。

https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uswgi-and-nginx-on-ubuntu-18-04

https://uwsgi-docs.readthedocs.io/en/latest/tutorials/Django_and_nginx.html

https://flask.palletsprojects.com/en/1.1.x/deploying/uwsgi/#uwsgi

我的Flask应用程序。 app_service.py

import json
import os

from flask import Flask, Response, redirect


portToUse = 9401


@app.route("/app/people")
def get_service_people():
    print("Get people")
    people_str = "{ \"John\", \"Alex\" }"
    return Response(people_str, mimetype="application/json;charset=UTF-8")


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=portToUse)

uwsgi配置 uwsgi.ini

[uwsgi]
chdir = $(APPDIR)
wsgi-file = app_service.py
callable = app
uid = psc-user
gid = psc-user
master = true

processes = 1
threads = 1
http-timeout = 300
socket-timeout = 300
harakiri = 300

http = 0.0.0.0:9401
socket = /tmp/uwsgi.socket
chmod-sock = 664
vacuum = true
die-on-term = true

; Images serving: https://github.com/unbit/uwsgi/issues/1126#issuecomment-166687767
wsgi-disable-file-wrapper = true

log-date = %%Y-%%m-%%d %%H:%%M:%%S
logformat-strftime = true
logformat = %(ftime) | uWSGI    | %(addr) (%(proto) %(status)) | %(method) %(uri) | %(pid):%(wid) | Returned %(size) bytes in %(msecs) ms to %(uagent)

requirements.txt

# Web framework for python app.
Flask==1.1.1

# JWT tocket utils to retrieve the tocken from HTTP request header.
# It is used for retrieving optional permissions from gateway.
# https://pypi.org/project/PyJWT/
PyJWT==1.7.1

# Eureka API client library to implement service discovery pattern
py_eureka_client==0.7.4

# Python application server
uWSGI==2.0.18

它似乎正在工作。我正在docker-compose的虚拟机中运行所有这些程序。

我的问题,为什么我这里需要nginx ? python开发人员是否在没有Web服务器的情况下使用uWSGI?

更新

我不会在生产环境中运行dev默认的WSGI服务器,因为这里要求 Are a WSGI server and HTTP server required to serve a Flask app?

WSGI服务器碰巧具有HTTP服务器,但不如专用的生产HTTP服务器(Nginx,Apache等)

来自 https://stackoverflow.com/a/38982989/1839360

为什么会这样?

我要问的是为什么uWSGI服务器不能很好地处理HTTP,因此我需要在Internet和uWSGI之间放置HTTP服务器。为什么传入的HTTP请求可以直接进入uWSGI(它不在开发或调试模式下运行)。

1 个答案:

答案 0 :(得分:2)

对于正在运行的烧瓶,您不需要nginx,只需选择一个Web服务器,但是使用nginx的生活就更轻松了。如果您使用的是Apache,则要考虑使用WSGI

我记得在Flask文档的某处读过answer to "Are a WSGI server and HTTP server required to serve a Flask app?"所说的

对于“我应该使用Web服务器”,答案是相似的。 WSGI服务器恰好具有HTTP服务器,但不如专用的生产HTTP服务器(Nginx,Apache等)好。

背后的主要思想是分层的架构原理,以简化调试并提高安全性,类似于您拆分内容和结构(HTML和CSS,UI与API)的概念:< / p>

更新

我看到客户端仅运行带有集成HTTP支持的WSGI服务器。使用额外的Web服务器和/或代理只是一种好的做法,但IMHO并非绝对必要。

参考文献