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

Yan*_*ski 5 nginx flask uwsgi python-3.x

在没有 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

我的烧瓶应用程序。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)
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

要求.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
Run Code Online (Sandbox Code Playgroud)

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

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

更新

我不会在生产中运行 dev 默认的 WSGI 服务器,因为它被问到这里 是否需要 WSGI 服务器和 HTTP 服务器来为 Flask 应用程序提供服务?

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

来自 /sf/answers/2728809261/

为什么会这样?

我要问的是为什么 uWSGI 服务器不能像 HTTP 处理一样好,所以我需要将 HTTP 服务器放在互联网和 uWSGI 之间。为什么传入的 HTTP 请求可以直接进入 uWSGI(它不在开发或调试模式下运行)。

B--*_*ian 4

为了运行 Flask,你不需要 nginx,只需要你选择的网络服务器,但使用 nginx 的生活会更容易。如果您使用 Apache,则需要考虑使用WSGI

我记得在 Flask 文档中的某个地方读过“为 Flask 应用程序提供服务需要 WSGI 服务器和 HTTP 服务器吗?”的答案。作为

答案与“我应该使用网络服务器吗”类似。WSGI 服务器恰好有 HTTP 服务器,但它们不如专用的生产 HTTP 服务器(Nginx、Apache 等)。

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

更新

我见过客户端仅单独运行 WSGI 服务器,并具有集成的 HTTP 支持。使用额外的网络服务器和/或代理只是一个很好的做法,但恕我直言,这并不是绝对必要的。

参考