标签归档:wsgi

一个Flask进程接收多少个并发请求?

问题:一个Flask进程接收多少个并发请求?

我正在用Flask构建一个应用程序,但是我对WSGI并不太了解,它是基于HTTP的Werkzeug。当我开始使用gunicorn和4个工作进程处理Flask应用程序时,这是否意味着我可以处理4个并发请求?

我的意思是并发请求,而不是每秒的请求或其他任何请求。

I’m building an app with Flask, but I don’t know much about WSGI and it’s HTTP base, Werkzeug. When I start serving a Flask application with gunicorn and 4 worker processes, does this mean that I can handle 4 concurrent requests?

I do mean concurrent requests, and not requests per second or anything else.


回答 0

在运行开发服务器时(这是通过运行获得的)app.run(),您将获得一个同步过程,这意味着一次最多处理一个请求。

通过将Gunicorn保留在其默认配置中并简单地增加Gunicorn的数量--workers,您所获得的实际上是一些流程(由Gunicorn管理),每个流程的行为都类似于app.run()开发服务器。4个工作人员== 4个并发请求。这是因为Gunicorn sync默认使用其包含的工作程序类型。

重要的是要注意,Gunicorn还包含异步工作程序,即eventletgevent(以及tornado,但似乎最好在Tornado框架中使用)。通过使用--worker-class标志指定这些异步工作程序之一,您将获得Gunicorn管理多个异步进程的信息,每个进程管理自己的并发性。这些进程不使用线程,而是协程。基本上,在每个进程中,一次只能发生1件事(1个线程),但是当对象等待外部进程完成(例如数据库查询或等待网络I / O)时,它们可以被“暂停”。

这意味着,如果您使用的是Gunicorn的异步工作程序之一,则每个工作程序一次最多可以处理多个请求。多少工人才是最好的,取决于您的应用程序的性质,其环境,运行的硬件等。有关更多详细信息,请参见Gunicorn的设计页面,并在其介绍页面上介绍gevent的工作方式

When running the development server – which is what you get by running app.run(), you get a single synchronous process, which means at most 1 request is being processed at a time.

By sticking Gunicorn in front of it in its default configuration and simply increasing the number of --workers, what you get is essentially a number of processes (managed by Gunicorn) that each behave like the app.run() development server. 4 workers == 4 concurrent requests. This is because Gunicorn uses its included sync worker type by default.

It is important to note that Gunicorn also includes asynchronous workers, namely eventlet and gevent (and also tornado, but that’s best used with the Tornado framework, it seems). By specifying one of these async workers with the --worker-class flag, what you get is Gunicorn managing a number of async processes, each of which managing its own concurrency. These processes don’t use threads, but instead coroutines. Basically, within each process, still only 1 thing can be happening at a time (1 thread), but objects can be ‘paused’ when they are waiting on external processes to finish (think database queries or waiting on network I/O).

This means, if you’re using one of Gunicorn’s async workers, each worker can handle many more than a single request at a time. Just how many workers is best depends on the nature of your app, its environment, the hardware it runs on, etc. More details can be found on Gunicorn’s design page and notes on how gevent works on its intro page.


回答 1

当前,存在比已提供的解决方案简单得多的解决方案。运行应用程序时,只需将threaded=True参数传递给app.run()调用,例如:

app.run(host="your.host", port=4321, threaded=True)

根据在werkzeug文档中可以看到的另一种选择是使用processes参数,该参数接收的数字> 1表示要处理的最大并发进程数:

  • 线程化–进程应在单独的线程中处理每个请求吗?
  • 进程–如果大于1,则将处理新进程中的每个请求,直到最大并发进程数。

就像是:

app.run(host="your.host", port=4321, processes=3) #up to 3 processes

关于更多信息run()方法在这里,和博客文章,导致我找到解决方案和API引用。


注意:在Flask文档中,关于run()方法的方法表明不鼓励在生产环境中使用它,因为(quote):“虽然Flask轻巧易用,但其内置服务器不适合生产,因为它的扩展性不好”。

但是,他们确实指向其“ 部署选项”页面,以了解在投入生产时执行此操作的推荐方法。

Currently there is a far simpler solution than the ones already provided. When running your application you just have to pass along the threaded=True parameter to the app.run() call, like:

app.run(host="your.host", port=4321, threaded=True)

Another option as per what we can see in the werkzeug docs, is to use the processes parameter, which receives a number > 1 indicating the maximum number of concurrent processes to handle:

  • threaded – should the process handle each request in a separate thread?
  • processes – if greater than 1 then handle each request in a new process up to this maximum number of concurrent processes.

Something like:

app.run(host="your.host", port=4321, processes=3) #up to 3 processes

More info on the run() method here, and the blog post that led me to find the solution and api references.


Note: on the Flask docs on the run() methods it’s indicated that using it in a Production Environment is discouraged because (quote): “While lightweight and easy to use, Flask’s built-in server is not suitable for production as it doesn’t scale well.”

However, they do point to their Deployment Options page for the recommended ways to do this when going for production.


回答 2

Flask将同时为每个线程处理一个请求。如果您有2个进程,每个进程有4个线程,则是8个并发请求。

Flask不会产生或管理线程或进程。这就是WSGI网关(例如gunicorn)的责任。

Flask will process one request per thread at the same time. If you have 2 processes with 4 threads each, that’s 8 concurrent requests.

Flask doesn’t spawn or manage threads or processes. That’s the responsability of the WSGI gateway (eg. gunicorn).


回答 3

不,您绝对可以处理更多。

重要的是要记住,假设您正在运行一台单核计算机,那么CPU实际上一次只能运行一条指令*。

也就是说,CPU只能执行非常有限的一组指令,并且每个时钟周期不能执行多个指令(许多指令甚至需要1个周期以上)。

因此,我们在计算机科学中谈论的大多数并发是软件并发。换句话说,有一些软件实现层从我们这里提取底层CPU,并使我们认为我们正在同时运行代码。

这些“事物”可以是进程,它们是代码单元,它们在每个进程都认为其在自己的世界中使用自己的非共享内存在运行时可以并发运行。

另一个示例是线程,线程是进程内部的代码单元,也允许并发。

您的4个辅助进程能够处理4个以上请求的原因是,它们将触发线程以处理越来越多的请求。

实际的请求限制取决于所选择的HTTP服务器,I / O,操作系统,硬件,网络连接等。

祝好运!

*说明是CPU可以运行的最基本的命令。示例-加两个数字,从一条指令跳转到另一条指令

No- you can definitely handle more than that.

Its important to remember that deep deep down, assuming you are running a single core machine, the CPU really only runs one instruction* at a time.

Namely, the CPU can only execute a very limited set of instructions, and it can’t execute more than one instruction per clock tick (many instructions even take more than 1 tick).

Therefore, most concurrency we talk about in computer science is software concurrency. In other words, there are layers of software implementation that abstract the bottom level CPU from us and make us think we are running code concurrently.

These “things” can be processes, which are units of code that get run concurrently in the sense that each process thinks its running in its own world with its own, non-shared memory.

Another example is threads, which are units of code inside processes that allow concurrency as well.

The reason your 4 worker processes will be able to handle more than 4 requests is that they will fire off threads to handle more and more requests.

The actual request limit depends on HTTP server chosen, I/O, OS, hardware, network connection etc.

Good luck!

*instructions are the very basic commands the CPU can run. examples – add two numbers, jump from one instruction to another


普通英语的WSGI和CGI是什么?

问题:普通英语的WSGI和CGI是什么?

每次阅读WSGI或CGI时,我都会感到畏缩。我尝试过阅读它,但没有任何卡住。

普通英语到底是什么?

它只是将请求通过管道传输到终端并重定向输出吗?

Every time I read either WSGI or CGI I cringe. I’ve tried reading on it before but nothing really has stuck.

What is it really in plain English?

Does it just pipe requests to a terminal and redirect the output?


回答 0

WSGI在Web服务器启动时(作为Web服务器进程的一部分(嵌入式模式)或作为单独的进程(守护程序模式))运行Python解释器,并将脚本加载到其中。每个请求都会导致调用脚本中的特定功能,并将请求环境作为参数传递给该功能。

CGI将脚本作为每个请求的单独进程运行,并使用环境变量,stdin和stdout与之“通信”。

WSGI runs the Python interpreter on web server start, either as part of the web server process (embedded mode) or as a separate process (daemon mode), and loads the script into it. Each request results in a specific function in the script being called, with the request environment passed as arguments to the function.

CGI runs the script as a separate process each request and uses environment variables, stdin, and stdout to “communicate” with it.


回答 1

从完全后退的角度来看,Blankman,这是我的Web服务网关接口的“简介页”:

第一部分:网络服务器

Web服务器提供响应。他们坐在那里,耐心等待,然后突然没有任何警告:

  • 客户端进程发送请求。客户端进程可以是Web服务器,机器人,移动应用程序等。简直就是“客户”
  • Web服务器收到此请求
  • 故意咕umble各种事情发生(见下文)
  • Web服务器将某些内容发送回客户端
  • Web服务器再次坐在附近

Web服务器(至少是更好的服务器)在这方面非常擅长。他们根据需求扩展和缩减处理,通过可靠的网络可靠地与最薄弱的客户进行对话,而我们永远不必担心。他们只是继续服役。

这就是我的观点:Web服务器就是:服务器。他们对内容一无所知,对用户一无所知,实际上除了如何耐心等待和可靠答复外,一无所知。

您选择的Web服务器应该反映您的交付偏好,而不是您的软件。您的网络服务器应负责服务,而不是处理或逻辑事务。

第二部分:(PYTHON)软件

软件不存在。软件仅在执行时存在。当软件在其环境中发生意外更改(文件不在期望的位置,重命名参数等)时,软件并不适应。尽管优化应该是设计的中心原则(当然),但是软件本身并不能优化。开发人员乐观。软件执行。软件会执行上面“故意含糊不清”部分中的所有内容。可以是任何东西。

您对软件的选择或设计应反映您的应用程序,功能的选择,而不是Web服务器的选择。

这是将语言“编译”到Web服务器的传统方法变得很痛苦的地方。您最终将代码放入应用程序中以应对物理服务器环境,或者至少被迫选择一个适当的“包装”库以在运行时包括在内,从而使跨Web服务器具有统一性的错觉。

那么WSGI是什么?

那么,最后,WSGI是什么?WSGI是一套规则,分为两部分。编写它们的方式可以将它们集成到任何欢迎集成的环境中。

为Web服务器端编写的第一部分说:“好吧,如果您要处理WSGI应用程序,则这是该软件在加载时的思考方式。这是您必须为应用程序提供的内容,这里是您可以期望每个应用程序具有的界面(布局)。此外,如果出现任何问题,这是应用程序的思维方式以及期望行为的方式。”

为Python应用程序软件编写的第二部分说:“好吧,如果您要处理WSGI服务器,这是服务器与您联系时的思考方式。这是您必须向服务器提供的东西,以及这是您可以期望每台服务器都具有的接口(布局)。此外,如果出现任何问题,这是您的行为方式,也应该告诉服务器。”

因此,有了它-服务器将成为服务器,软件将成为软件,这是它们可以很好地相处的一种方式,而不必为彼此的细节留出余地。这是WSGI。

mod_wsgi的,而另一方面,是Apache的一个插件,让它跟WSGI兼容的软件,换句话说,mod_wsgi的是一个实现 -在Apache中-上面的规则手册第一部分的规则。

至于CGI ….问其他人:-)

From a totally step-back point of view, Blankman, here is my “Intro Page” for Web Services Gateway Interface:

PART ONE: WEB SERVERS

Web servers serve up responses. They sit around, waiting patiently, and then with no warning at all, suddenly:

  • a client process sends a request. The client process could be a web server, a bot, a mobile app, whatever. It is simply “the client”
  • the web server receives this request
  • deliberate mumble various things happen (see below)
  • The web server sends back something to the client
  • web server sits around again

Web servers (at least, the better ones) are very VERY good at this. They scale up and down processing depending on demand, they reliably hold conversations with the flakiest of clients over really cruddy networks and we never really have to worry about it. They just keep on serving.

This is my point: web servers are just that: servers. They know nothing about content, nothing about users, nothing in fact other than how to wait a lot and reply reliably.

Your choice of web server should reflect your delivery preference, not your software. Your web server should be in charge of serving, not processing or logical stuff.

PART TWO: (PYTHON) SOFTWARE

Software does not sit around. Software only exists at execution time. Software is not terribly accommodating when it comes to unexpected changes in its environment (files not being where it expects, parameters being renamed etc). Although optimisation should be a central tenet of your design (of course), software itself does not optimise. Developers optimise. Software executes. Software does all the stuff in the ‘deliberate mumble’ section above. Could be anything.

Your choice or design of software should reflect your application, your choice of functionality, and not your choice of web server.

This is where the traditional method of “compiling in” languages to web servers becomes painful. You end up putting code in your application to cope with the physical server environment or, at least, being forced to choose an appropriate ‘wrapper’ library to include at runtime, to give the illusion of uniformity across web servers.

SO WHAT IS WSGI?

So, at last, what is WSGI? WSGI is a set of rules, written in two halves. They are written in such a way that they can be integrated into any environment that welcomes integration.

The first part, written for the web server side, says “OK, if you want to deal with a WSGI application, here’s how the software will be thinking when it loads. Here are the things you must make available to the application, and here is the interface (layout) that you can expect every application to have. Moreover, if anything goes wrong, here’s how the app will be thinking and how you can expect it to behave.”

The second part, written for the Python application software, says “OK, if you want to deal with a WSGI server, here’s how the server will be thinking when it contacts you. Here are the things you must make available to the server, and here is the interface (layout) that you can expect every server to have. Moreover, if anything goes wrong, here’s how you should behave and here’s what you should tell the server.”

So there you have it – servers will be servers and software will be software, and here’s a way they can get along just great without one having to make any allowances for the specifics of the other. This is WSGI.

mod_wsgi, on the other hand, is a plugin for Apache that lets it talk to WSGI-compliant software, in other words, mod_wsgi is an implementation – in Apache – of the rules of part one of the rulebook above.

As for CGI…. ask someone else :-)


回答 2

如果您不清楚这个领域中的所有术语,并且让我们面对现实,那是一个令人困惑的首字母缩写词,那么还有一个很好的背景阅读器,以官方的Python HOWTO形式提供,它讨论了CGI,FastCGI,WSGI等。上。希望我先读。

If you are unclear on all the terms in this space, and let’s face it, it’s a confusing acronym-laden one, there’s also a good background reader in the form of an official python HOWTO which discusses CGI vs. FastCGI vs. WSGI and so on. I wish I’d read it first.


回答 3

CGI和WSGI都定义了标准接口,程序可以使用这些标准接口来处理Web请求。CGI接口的级别低于WSGI,它涉及服务器设置环境变量,该环境变量包含HTTP请求中的数据,程序返回的格式类似于裸HTTP服务器响应。

另一方面,WSGI是特定于Python的更高级别的接口,它使程序员可以编写与服务器无关的应用程序,并且可以将其包装在其他WSGI应用程序(中间件)中。

Both CGI and WSGI define standard interfaces that programs can use to handle web requests. The CGI interface is at a lower level than WSGI, and involves the server setting up environment variables containing the data from the HTTP request, with the program returning something formatted pretty much like a bare HTTP server response.

WSGI, on the other hand, is a Python-specific, slightly higher-level interface that allows programmers to write applications that are server-agnostic and which can be wrapped in other WSGI applications (middleware).


uWSGI的意义是什么?

问题:uWSGI的意义是什么?

我正在研究WSGI规范,并试图弄清楚像uWSGI这样的服务器是如何适应图片的。我了解WSGI规范的重点是将Web服务器(如nginx)与Web应用程序(如您使用Flask编写的东西)分开。我不明白uWSGI是做什么的。为什么Nginx无法直接调用我的Flask应用程序?Flask不能直接对它说WSGI吗?uWSGI为什么需要介入它们之间?

WSGI规范有两个方面:服务器和Web应用程序。uWSGI在哪一边?

I’m looking at the WSGI specification and I’m trying to figure out how servers like uWSGI fit into the picture. I understand the point of the WSGI spec is to separate web servers like nginx from web applications like something you’d write using Flask. What I don’t understand is what uWSGI is for. Why can’t nginx directly call my Flask application? Can’t flask speak WSGI directly to it? Why does uWSGI need to get in between them?

There are two sides in the WSGI spec: the server and the web app. Which side is uWSGI on?


回答 0

好吧,我想我现在明白了。

为什么Nginx无法直接调用我的Flask应用程序?

因为nginx不支持WSGI规范。从技术上讲,nginx可以根据需要实施该WSGI规范,而实际上并没有。

在这种情况下,我们需要一个能够实现规范的Web服务器,这正是该uWSGI服务器的作用。

请注意,这uWSGI是一个完整的http服务器,可以单独运行并且运行良好。我已经以这种身份多次使用它,并且效果很好。如果您需要超高的静态内容吞吐量,则可以选择停留nginxuWSGI服务器前。完成后,他们将通过称为的低级协议进行通信uwsgi

“什么事?!又叫uwsgi ?!” 你问。是的,令人困惑。当您引用时,uWSGI您正在谈论的是http服务器。当您谈论uwsgi(全部小写)时,您所谈论的是是该uWSGI 服务器用来与其他服务器进行通讯二进制协议nginx。他们在这个名字上取了一个坏名字。

对于任何有兴趣的人,我都写了一篇有关它的博客文章,其中包含更多细节,一些历史和一些示例。

Okay, I think I get this now.

Why can’t nginx directly call my Flask application?

Because nginx doesn’t support the WSGI spec. Technically nginx could implement the WSGI spec if they wanted, they just haven’t.

That being the case, we need a web server that does implement the spec, which is what the uWSGI server is for.

Note that uWSGI is a full fledged http server that can and does work well on its own. I’ve used it in this capacity several times and it works great. If you need super high throughput for static content, then you have the option of sticking nginx in front of your uWSGI server. When you do, they will communicate over a low level protocol known as uwsgi.

“What the what?! Another thing called uwsgi?!” you ask. Yeah, it’s confusing. When you reference uWSGI you are talking about an http server. When you talk about uwsgi (all lowercase) you are talking about a binary protocol that the uWSGI server uses to talk to other servers like nginx. They picked a bad name on this one.

For anyone who is interested, I wrote a blog article about it with more specifics, a bit of history, and some examples.


回答 1

在这种情况下,NGINX仅用作反向代理和渲染 静态文件而不动态文件,它接收请求并将它们代理到应用服务器(即UWSGI)。

UWSGI服务器负责使用WSGI接口加载Flask应用程序。实际上,您可以使UWSGI直接侦听来自Internet的请求,并根据需要删除NGINX,尽管它通常在反向代理之后使用。

文档

uWSGI支持几种与Web服务器集成的方法。它也能够自己处理HTTP请求。

简单来说,WSGI只是一个接口规范,它告诉您应该实现哪些方法以在服务器和应用程序之间传递请求和响应。当使用Flask或Django之类的框架时,由框架本身来处理。

换句话说,WSGI本质上是python应用程序(Flask,Django等)和Web服务器(UWSGI,Gunicorn等)之间的契约。好处是您可以轻松更改Web服务器,因为您知道它们符合WSGI规范,而这实际上是目标之一,如PEP-333中所述

Python目前拥有各种各样的Web应用程序框架,如Zope的,堂吉诃德,Webware的,SkunkWeb,PSO和扭曲网站-仅举几个1。对于新的Python用户而言,如此众多的选择可能是一个问题,因为通常来说,他们对Web框架的选择将限制他们对可用Web服务器的选择,反之亦然。

NGINX in this case only works as a reverse proxy and render static files not the dynamic files, it receives the requests and proxies them to the application server, that would be UWSGI.

The UWSGI server is responsible for loading your Flask application using the WSGI interface. You can actually make UWSGI listen directly to requests from the internet and remove NGINX if you like, although it’s mostly used behind a reverse proxy.

From the docs:

uWSGI supports several methods of integrating with web servers. It is also capable of serving HTTP requests by itself.

WSGI is just an interface specification, in simple terms, it tells you what methods should be implemented for passing requests and responses between the server and the application. When using frameworks such as Flask or Django, this is handled by the framework itself.

In other words, WSGI is basically a contract between python applications (Flask, Django, etc) and web servers (UWSGI, Gunicorn, etc). The benefit is that you can change web servers with little effort because you know they comply with the WSGI specification, which is actually one of the goals, as stated in PEP-333.

Python currently boasts a wide variety of web application frameworks, such as Zope, Quixote, Webware, SkunkWeb, PSO, and Twisted Web — to name just a few 1. This wide variety of choices can be a problem for new Python users, because generally speaking, their choice of web framework will limit their choice of usable web servers, and vice versa.


回答 2

传统的Web服务器无法理解或无法运行Python应用程序。这就是WSGI服务器出现的原因。另一方面,Nginx支持反向代理来处理请求并传递Python WSGI服务器的响应。

该链接可能会对您有所帮助:https : //www.fullstackpython.com/wsgi-servers.html

A traditional web server does not understand or have any way to run Python applications. That’s why WSGI server come in. On the other hand Nginx supports reverse proxy to handle requests and pass back responses for Python WSGI servers.

This link might help you: https://www.fullstackpython.com/wsgi-servers.html


回答 3

简而言之,可以想像一下您在Nginx Web服务器上运行CGI或PHP应用程序的情况。您将使用像php-fpm这样的相应处理程序来运行这些文件,因为Web服务器以其本机格式不会呈现这些格式。

In simple terms, just think of an analogy where you are running a CGI or PHP application with Nginx web server. You will use the respective handlers like php-fpm to run these files since the webserver, in its native form doesn’t render these formats.


Python Web框架,WSGI和CGI如何结合在一起

问题:Python Web框架,WSGI和CGI如何结合在一起

我有一个Bluehost帐户,可以在其中运行Python脚本作为CGI。我猜这是最简单的CGI,因为要运行,我必须在中定义以下内容.htaccess

Options +ExecCGI
AddType text/html py
AddHandler cgi-script .py

现在,每当我使用Python查找Web编程时,我都会听到很多关于WSGI以及大多数框架如何使用它的知识。但是我只是不明白它们之间的关系如何,特别是当我的Web服务器(在主机上运行Apache)并且没有我真正可以使用的东西(定义.htaccess命令除外)时尤其如此。

WSGI,CGI和框架如何连接?我想在基本的CGI配置上运行Web框架(例如web.pyCherryPy),该怎么办?如何安装WSGI支持?

I have a Bluehost account where I can run Python scripts as CGI. I guess it’s the simplest CGI, because to run I have to define the following in .htaccess:

Options +ExecCGI
AddType text/html py
AddHandler cgi-script .py

Now, whenever I look up web programming with Python, I hear a lot about WSGI and how most frameworks use it. But I just don’t understand how it all fits together, especially when my web server is given (Apache running at a host’s machine) and not something I can really play with (except defining .htaccess commands).

How are WSGI, CGI, and the frameworks all connected? What do I need to know, install, and do if I want to run a web framework (say web.py or CherryPy) on my basic CGI configuration? How to install WSGI support?


回答 0

WSGI,CGI和框架如何连接?

Apache侦听端口80。它获取HTTP请求。它解析请求以找到一种响应方式。Apache有很多可供选择的响应方式。一种响应方式是使用CGI运行脚本。另一种响应方式是简单地提供文件。

对于CGI,Apache准备一个环境并通过CGI协议调用脚本。这是标准的Unix Fork / Exec情况-CGI子进程继承了包括套接字和标准输出的OS环境。CGI子进程编写一个响应,该响应可以返回到Apache。Apache将此响应发送到浏览器。

CGI是原始且令人讨厌的。主要是因为它为每个请求派生一个子流程,并且该子流程必须退出或关闭stdout和stderr来表示响应结束。

WSGI是基于CGI设计模式的接口。它不一定是CGI,也不必为每个请求派生一个子进程。可以是CGI,但不一定如此。

WSGI以几种重要方式添加到CGI设计模式中。它为您解析HTTP请求标头,并将其添加到环境中。它提供任何面向POST的输入,作为环境中的类似文件的对象。它还为您提供了可以制定响应的功能,从而使您免于许多格式设置细节。

如果要在基本CGI配置上运行Web框架(例如web.py或cherrypy),我需要知道/安装/做什么?

回想一下,分叉子过程很昂贵。有两种方法可以解决此问题。

  1. 在Apache中嵌入mod_wsgimod_python嵌入Python;没有分叉的过程。Apache直接运行Django应用程序。

  2. 守护程序, mod_wsgimod_fastcgi允许Apache使用WSGI协议与单独的守护程序(或“长时间运行的进程”)进行交互。您启动长期运行的Django进程,然后配置Apache的mod_fastcgi与该进程进行通信。

请注意,它mod_wsgi可以在两种模式下工作:嵌入式或守护程序。

当您阅读mod_fastcgi时,您会发现Django使用flup从mod_fastcgi提供的信息创建与WSGI兼容的接口。管道的工作原理是这样的。

Apache -> mod_fastcgi -> FLUP (via FastCGI protocol) -> Django (via WSGI protocol)

Django为各种接口提供了多个“ django.core.handlers”。

对于mod_fastcgi,Django提供了一个manage.py runfcgi集成FLUP和处理程序的。

对于mod_wsgi,有一个核心处理程序。

如何安装WSGI支持?

请遵循以下说明。

https://code.google.com/archive/p/modwsgi/wikis/IntegrationWithDjango.wiki

对于背景,请参阅此

http://docs.djangoproject.com/en/dev/howto/deployment/#howto-deployment-index

How WSGI, CGI, and the frameworks are all connected?

Apache listens on port 80. It gets an HTTP request. It parses the request to find a way to respond. Apache has a LOT of choices for responding. One way to respond is to use CGI to run a script. Another way to respond is to simply serve a file.

In the case of CGI, Apache prepares an environment and invokes the script through the CGI protocol. This is a standard Unix Fork/Exec situation — the CGI subprocess inherits an OS environment including the socket and stdout. The CGI subprocess writes a response, which goes back to Apache; Apache sends this response to the browser.

CGI is primitive and annoying. Mostly because it forks a subprocess for every request, and subprocess must exit or close stdout and stderr to signify end of response.

WSGI is an interface that is based on the CGI design pattern. It is not necessarily CGI — it does not have to fork a subprocess for each request. It can be CGI, but it doesn’t have to be.

WSGI adds to the CGI design pattern in several important ways. It parses the HTTP Request Headers for you and adds these to the environment. It supplies any POST-oriented input as a file-like object in the environment. It also provides you a function that will formulate the response, saving you from a lot of formatting details.

What do I need to know / install / do if I want to run a web framework (say web.py or cherrypy) on my basic CGI configuration?

Recall that forking a subprocess is expensive. There are two ways to work around this.

  1. Embedded mod_wsgi or mod_python embeds Python inside Apache; no process is forked. Apache runs the Django application directly.

  2. Daemon mod_wsgi or mod_fastcgi allows Apache to interact with a separate daemon (or “long-running process”), using the WSGI protocol. You start your long-running Django process, then you configure Apache’s mod_fastcgi to communicate with this process.

Note that mod_wsgi can work in either mode: embedded or daemon.

When you read up on mod_fastcgi, you’ll see that Django uses flup to create a WSGI-compatible interface from the information provided by mod_fastcgi. The pipeline works like this.

Apache -> mod_fastcgi -> FLUP (via FastCGI protocol) -> Django (via WSGI protocol)

Django has several “django.core.handlers” for the various interfaces.

For mod_fastcgi, Django provides a manage.py runfcgi that integrates FLUP and the handler.

For mod_wsgi, there’s a core handler for this.

How to install WSGI support?

Follow these instructions.

https://code.google.com/archive/p/modwsgi/wikis/IntegrationWithDjango.wiki

For background see this

http://docs.djangoproject.com/en/dev/howto/deployment/#howto-deployment-index


回答 1

我认为Florian的答案回答了您有关“ WSGI是什么”的部分问题,特别是如果您阅读了PEP

至于您即将提出的问题:

WSGI,CGI,FastCGI等都是Web服务器运行代码并传递产生的动态内容的协议。与此相比,静态Web服务基本上是将纯HTML文件原样发送到客户端的静态Web服务。

CGI,FastCGI和SCGI与语言无关。您可以用Perl,Python,C,bash等编写CGI脚本。CGI 根据URL 定义将调用哪个可执行文件,以及如何调用它:参数和环境。它还定义了可执行文件完成后应如何将返回值传递回Web服务器。这些变化基本上是优化的,以便能够处理更多请求,减少延迟等。基本概念是相同的。

WSGI仅适用于Python。定义了标准功能签名,而不是语言无关协议:

def simple_app(environ, start_response):
    """Simplest possible application object"""
    status = '200 OK'
    response_headers = [('Content-type','text/plain')]
    start_response(status, response_headers)
    return ['Hello world!\n']

那是一个完整的(如果有限制的话)WSGI应用程序。具有WSGI支持的Web服务器(例如具有mod_wsgi的Apache)可以在请求到达时调用此功能。

之所以如此出色,是因为我们可以避免从HTTP GET / POST转换为CGI再转换为Python的繁琐步骤,并在退出过程中再次返回。这是一种更加直接,干净和有效的链接。

如果需要对请求进行的所有操作都是函数调用,那么使长时间运行的框架在Web服务器后运行也变得更加容易。使用普通的CGI,您必须为每个单独的请求启动整个框架

要获得WSGI支持,您需要安装WSGI模块(如mod_wsgi),或使用带有WSGI嵌入的Web服务器(如CherryPy)。如果两者都不可行,则可以使用PEP中提供的CGI-WSGI桥。

I think Florian’s answer answers the part of your question about “what is WSGI”, especially if you read the PEP.

As for the questions you pose towards the end:

WSGI, CGI, FastCGI etc. are all protocols for a web server to run code, and deliver the dynamic content that is produced. Compare this to static web serving, where a plain HTML file is basically delivered as is to the client.

CGI, FastCGI and SCGI are language agnostic. You can write CGI scripts in Perl, Python, C, bash, whatever. CGI defines which executable will be called, based on the URL, and how it will be called: the arguments and environment. It also defines how the return value should be passed back to the web server once your executable is finished. The variations are basically optimisations to be able to handle more requests, reduce latency and so on; the basic concept is the same.

WSGI is Python only. Rather than a language agnostic protocol, a standard function signature is defined:

def simple_app(environ, start_response):
    """Simplest possible application object"""
    status = '200 OK'
    response_headers = [('Content-type','text/plain')]
    start_response(status, response_headers)
    return ['Hello world!\n']

That is a complete (if limited) WSGI application. A web server with WSGI support (such as Apache with mod_wsgi) can invoke this function whenever a request arrives.

The reason this is so great is that we can avoid the messy step of converting from a HTTP GET/POST to CGI to Python, and back again on the way out. It’s a much more direct, clean and efficient linkage.

It also makes it much easier to have long-running frameworks running behind web servers, if all that needs to be done for a request is a function call. With plain CGI, you’d have to start your whole framework up for each individual request.

To have WSGI support, you’ll need to have installed a WSGI module (like mod_wsgi), or use a web server with WSGI baked in (like CherryPy). If neither of those are possible, you could use the CGI-WSGI bridge given in the PEP.


回答 2

如Pep333所示,您可以在CGI上运行WSGI。但是,每次有一个请求时,都会启动一个新的Python解释器,并且需要构建整个上下文(数据库连接等),这都需要时间。

如果要运行WSGI,最好的方法是主机安装mod_wsgi并进行适当的配置以将控制权交给您的应用程序。

对于任何会说FCGISCGI或AJP的Web服务器,Flup是与WSGI一起运行的另一种方式。根据我的经验,只有FCGI确实有效,并且可以通过mod_fastcgi在Apache中使用它,或者可以通过mod_proxy_fcgi运行单独的Python守护程序。

WSGI是与CGI非常相似的协议,它定义了一组Web服务器和Python代码如何交互的规则,其定义为Pep333。这使得许多不同的Web服务器可以使用同一应用程序协议来使用许多不同的框架和应用程序。这是非常有益的,并使其非常有用。

You can run WSGI over CGI as Pep333 demonstrates as an example. However every time there is a request a new Python interpreter is started and the whole context (database connections, etc.) needs to be build which all take time.

The best if you want to run WSGI would be if your host would install mod_wsgi and made an appropriate configuration to defer control to an application of yours.

Flup is another way to run with WSGI for any webserver that can speak FCGI, SCGI or AJP. From my experience only FCGI really works, and it can be used in Apache either via mod_fastcgi or if you can run a separate Python daemon with mod_proxy_fcgi.

WSGI is a protocol much like CGI, which defines a set of rules how webserver and Python code can interact, it is defined as Pep333. It makes it possible that many different webservers can use many different frameworks and applications using the same application protocol. This is very beneficial and makes it so useful.


回答 3

如果您不清楚这个领域中的所有术语,并且让我们直面它,这是一个令人困惑的首字母缩写词,那么还有一个很好的背景阅读器,形式为官方python HOWTO,其中讨论了CGI,FastCGI,WSGI等。上:http : //docs.python.org/howto/webservers.html

If you are unclear on all the terms in this space, and lets face it, its a confusing acronym-laden one, there’s also a good background reader in the form of an official python HOWTO which discusses CGI vs. FastCGI vs. WSGI and so on: http://docs.python.org/howto/webservers.html


回答 4

这是用于Python的简单抽象层,类似于Servlet规范用于Java。尽管CGI确实是低级的,只是将内容转储到流程环境和标准输入/输出中,但是以上两个规范将http请求和响应建模为该语言的构造。但是,我的印象是,在Python中,人们还不太习惯实际的实现,因此您混合使用了参考实现和其他提供WSGI支持(例如Paste)的实用程序类型的库。当然,我可能是错的,我是Python的新手。“网络脚本”社区正从不同的方向提出问题(共享托管,CGI旧版,

It’s a simple abstraction layer for Python, akin to what the Servlet spec is for Java. Whereas CGI is really low level and just dumps stuff into the process environment and standard in/out, the above two specs model the http request and response as constructs in the language. My impression however is that in Python folks have not quite settled on de-facto implementations so you have a mix of reference implementations, and other utility-type libraries that provide other things along with WSGI support (e.g. Paste). Of course I could be wrong, I’m a newcomer to Python. The “web scripting” community is coming at the problem from a different direction (shared hosting, CGI legacy, privilege separation concerns) than Java folks had the luxury of starting with (running a single enterprise container in a dedicated environment against statically compiled and deployed code).


究竟什么是烧瓶蓝图?

问题:究竟什么是烧瓶蓝图?

阅读官方瓶文档的蓝图,甚至一个2上使用他们的博客文章。

我什至在我的Web应用程序中使用了它们,但是我不完全了解它们是什么,或者它们如何适合我的整个应用程序。它与我的应用程序实例有何相似之处,但又不太相似?文档虽然很全面,但是我想寻求外行的解释或启发性的类比给我以启发。当一位同事要求我向他们解释我选择在这里询问的Flask蓝图时,我感到非常困惑。

I have read the official Flask documentation on Blueprints and even one or two blog posts on using them.

I’ve even used them in my web app, but I don’t completely understand what they are or how they fit into my app as a whole. How is it similar to an instance of my app but not quite? The documentation is comprehensive but I seek a layman explanation or an enlightening analogy to spark it for me. I was sufficiently perplexed when a colleague asked me to explain a Flask blueprint to them that I elected to ask here.


回答 0

蓝图是用于生成Web应用程序“部分”的模板。您可以将其视为模具:

您可以获取该蓝图,并将其应用于多个位置。每次您应用它时,该蓝图都会在您的应用程序的石膏中创建其结构的新版本。

# An example
from flask import Blueprint

tree_mold = Blueprint("mold", __name__)

@tree_mold.route("/leaves")
def leaves():
    return "This tree has leaves"

@tree_mold.route("/roots")
def roots():
    return "And roots as well"

@tree_mold.route("/rings")
@tree_mold.route("/rings/<int:year>")
def rings(year=None):
    return "Looking at the rings for {year}".format(year=year)

这是处理树木的简单模型-它说与树木打交道的任何应用程序都应提供对其叶子,根和环的访问(按年)。就其本身而言,它是一个中空的外壳-它无法路由,无法响应,直到被应用程序打动为止:

from tree_workshop import tree_mold

app.register_blueprint(tree_mold, url_prefix="/oak")
app.register_blueprint(tree_mold, url_prefix="/fir")
app.register_blueprint(tree_mold, url_prefix="/ash")

一旦创建它,​​就可以通过使用register_blueprint功能将其“打动”在应用程序上-这在所指定的位置“打动”应用程序上的蓝图模具url_prefix

A blueprint is a template for generating a “section” of a web application. You can think of it as a mold:

You can take the blueprint and apply it to your application in several places. Each time you apply it the blueprint will create a new version of its structure in the plaster of your application.

# An example
from flask import Blueprint

tree_mold = Blueprint("mold", __name__)

@tree_mold.route("/leaves")
def leaves():
    return "This tree has leaves"

@tree_mold.route("/roots")
def roots():
    return "And roots as well"

@tree_mold.route("/rings")
@tree_mold.route("/rings/<int:year>")
def rings(year=None):
    return "Looking at the rings for {year}".format(year=year)

This is a simple mold for working with trees – it says that any application that deals with trees should provide access to its leaves, its roots, and its rings (by year). By itself, it is a hollow shell – it cannot route, it cannot respond, until it is impressed upon an application:

from tree_workshop import tree_mold

app.register_blueprint(tree_mold, url_prefix="/oak")
app.register_blueprint(tree_mold, url_prefix="/fir")
app.register_blueprint(tree_mold, url_prefix="/ash")

Once it is created it may be “impressed” on the application by using the register_blueprint function – this “impresses” the mold of the blueprint on the application at the locations specified by url_prefix.


回答 1

正如@Devasish评论中指出的那样,本文提供了一个很好的答案:

http://exploreflask.com/en/latest/blueprints.html

从文章引用:

一个例子就是Facebook。如果Facebook使用Flask,它可能具有静态页面(即,登出的首页,注册,关于等),仪表板(即新闻提要),个人资料(/ robert / about和/ robert / photos)的蓝图,设置(/ settings /安全性和/ settings / privacy)等等。这些组件都具有通用的布局和样式,但是每个组件也都有自己的布局

这是一个很好的解释,尤其是“如果Facebook使用Flask”部分。它为我们提供了一个具体情况,以可视化蓝图的实际工作方式。

As pointed out in a comment by @Devasish, this article provides a good answer:

http://exploreflask.com/en/latest/blueprints.html

Quoting from the article:

An example of this would be Facebook. If Facebook used Flask, it might have blueprints for the static pages (i.e. signed-out home, register, about, etc.), the dashboard (i.e. the news feed), profiles (/robert/about and /robert/photos), settings (/settings/security and /settings/privacy) and many more. These components all share a general layout and styles, but each has its own layout as well

This is a very good interpretation, especially the part “if Facebook used Flask”. It gives us a concrete situation to visualize how Blueprint actually works.


回答 2

我自己也偶然发现了这个问题,在阅读了一些文档资料后感到困惑。起初,我认为它就像C#/ Java实现风格,您可以定义一些东西,而不必担心以后定义它。但是,我偶然发现了该页面,将其置于非常普通的外行(以及当下颇为热闹的当下事件)术语。https://hackersandslackers.com/flask-blueprints/

从本质上讲,链接中提到的一项好处是使我可以有效地逻辑组织/划分,从而使我对它在现实世界中的使用情况有一个清晰的认识。应用程序为几个部分,这些部分只需要关心它自己的事务,就。因此,它提供了一些设计好的封装。

编辑:我目前正在使用它来细分我的webapps代码。这也是一个很好的决定,因为我发现首席设计师希望在Vue.js中成为前端。我还没有使用过,但是查看它的项目文件看起来会更加混乱,并且可能提供很多命名冲突的倾向。

I too just stumbled up this myself and was confused after reading a few of the documentation sources. At first I thought it was like C#/Java Implementation style where you define some stuff but dont have to worry about it defining it til later. However, I stumbled up this page which puts it in very very laymens (and quite hilarious current day events) terms. https://hackersandslackers.com/flask-blueprints/

Essentially one benefit that is mentioned in the link and provides me a clear idea of it’s real world usage is that I can effectively logically organize/divide the app into several parts that only need to be concerned with it’s own affairs. So it provides some designed encapsulation.

Edit: I’m currently using it to segment out my webapps code. It was good decision too because I found the lead designer wants to make the frontend in Vue.js. Which I havent used yet but looking at it’s project files would look far more messy and probably provide many naming collision prone.


回答 3

对于较大的项目,您的所有代码都不应位于同一文件中。相反,您可以根据功能将较大的代码分段或拆分为单独的文件。就像砖砌墙一样。

希望这会有所帮助。由于这是一个理论性的问题,因此请不要发布任何代码。

For bigger projects, all your code shouldn’t be in the same file. Instead you can segment or split bigger codes into separate file, mostly based on functionality. Like bricks forming a wall.

Hope this helped. Since this is a theoretical question, posting no codes.


Bottle-py是一个用于python web应用程序的快速而简单的微框架。

瓶子:Python Web框架

瓶子是一种快速、简单、轻便的WSGI微型Web-用于Python它作为单个文件模块分发,除了Python Standard Library

主页和文档:http://bottlepy.org

示例:瓶子里的“Hello World”

from bottle import route, run, template

@route('/hello/<name>')
def index(name):
    return template('<b>Hello {{name}}</b>!', name=name)

run(host='localhost', port=8080)

运行此脚本或将其粘贴到Python控制台,然后将浏览器指向http://localhost:8080/hello/world就这样

下载并安装

使用安装最新的稳定版本pip install bottle或下载bottle.py(不稳定)到您的项目目录中。除了Python标准库之外,没有其他硬依赖项。瓶子与Python 2.7和3.6+

许可证

代码和文档根据MIT许可提供(请参见LICENSE)

然而,瓶子的标志是都在那张执照的覆盖范围内。允许将徽标用作瓶子主页的链接,或与未经修改的图书馆直接关联。在所有其他情况下,请先询问一下。

Guricorn‘Green Unicorn’ 是一款适用于UNIX的WSGI HTTP服务器

Gunicorn‘Green Unicorn’是用于UNIX的Python WSGI HTTP服务器。这是一个从Ruby‘s移植过来的叉前工人模型Unicorn项目。Gunicorn服务器与各种Web框架广泛兼容,实现简单,对服务器资源的使用很少,而且速度相当快

欢迎加入我们的行列#gunicorn在……上面Freenode

文档

文档位于https://docs.gunicorn.org

安装

Gunicorn要求Python 3.x>=3.5

从PyPI安装:

$ pip install gunicorn

用法

基本用法:

$ gunicorn [OPTIONS] APP_MODULE

哪里APP_MODULE是属于这种模式的$(MODULE_NAME):$(VARIABLE_NAME)模块名称可以是完整的虚线路径。变量名引用应在指定模块中找到的WSGI可调用对象

测试应用示例:

$ cd examples
$ gunicorn --workers=2 test:app

贡献

看见our complete contributor’s guide有关更多详细信息,请参阅

许可证

Gunicorn是在麻省理工学院的许可下发布的。请参阅LICENSE有关更多详细信息,请提交文件

Flask-用于构建Web应用程序的Python微框架

Flask

Flask是一个轻量级的WSGI Web应用程序框架。它旨在使入门变得快速而简单,并且能够向上扩展到复杂的应用程序。它最初只是Werkzeug和JJJA_的一个简单包装器,现在已经成为最流行的Python Web应用程序框架之一

Fask提供建议,但不强制执行任何依赖项或项目布局。由开发人员选择他们想要使用的工具和库。社区提供了许多扩展,使添加新功能变得容易

 

一个简单的例子

使用pip_安装和更新:

$ pip install -U Flask

_PIP:https://pip.pypa.io/en/stable/quickstart/

贡献

代码-挡路::蟒蛇

# save this as app.py
from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello, World!"

有关设置开发环境以及如何为Flask做出贡献的指导,请参阅贡献指南_

$ flask run
  * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

捐赠

_投稿指南:https://github.com/pallets/flask/blob/main/CONTRIBUTING.rst

托盘组织开发并支持Flask及其使用的库。为了扩大贡献者和用户的社区,让维护人员有更多的时间在项目上投入更多的时间,请今天就捐款。

链接

  • Documentation: https://flask.palletsprojects.com/
  • Changes: https://flask.palletsprojects.com/changes/
  • PyPI Releases: https://pypi.org/project/Flask/
  • Source Code: https://github.com/pallets/flask/
  • Issue Tracker: https://github.com/pallets/flask/issues/
  • Website: https://palletsprojects.com/p/flask/
  • Twitter: https://twitter.com/PalletsTeam
  • Chat: https://discord.gg/pallets