development

Python 웹 프레임 워크, WSGI 및 CGI가 어떻게 결합 되는가

big-blog 2020. 6. 13. 09:29
반응형

Python 웹 프레임 워크, WSGI 및 CGI가 어떻게 결합 되는가


Python 스크립트를 CGI로 실행할 수 있는 Bluehost 계정이 있습니다. 실행하려면 다음을 정의해야하기 때문에 가장 간단한 CGI라고 생각합니다 .htaccess.

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

이제 파이썬으로 웹 프로그래밍을 검색 할 때마다 WSGI와 대부분의 프레임 워크에서이를 사용하는 방법에 대해 많이 듣습니다. 그러나 나는 웹 서버가 제공 될 때 (호스트 컴퓨터에서 실행되는 Apache) 특히 내가 실제로 할 수있는 것이 아닌 경우 ( .htaccess명령 정의 제외) 모든 것이 어떻게 어울리는 지 이해하지 못합니다 .

방법이다 WSGI , CGI, 그리고 프레임 워크는 모든 연결? 기본 CGI 구성 에서 웹 프레임 워크 (예 : web.py 또는 CherryPy ) 를 실행하려면 무엇을 알고 설치하고 수행해야 합니까? WSGI 지원을 설치하는 방법?


WSGI, CGI 및 프레임 워크는 모두 어떻게 연결되어 있습니까?

Apache는 포트 80에서 수신 대기합니다. HTTP 요청을받습니다. 응답 방법을 찾기 위해 요청을 구문 분석합니다. 아파치는 응답을위한 많은 선택이있다. 응답하는 한 가지 방법은 CGI를 사용하여 스크립트를 실행하는 것입니다. 응답하는 또 다른 방법은 단순히 파일을 제공하는 것입니다.

CGI의 경우 Apache는 환경을 준비하고 CGI 프로토콜을 통해 스크립트를 호출합니다. 이것은 표준 Unix Fork / Exec 상황입니다. CGI 하위 프로세스는 소켓 및 stdout을 포함한 OS 환경을 상속합니다. CGI 서브 프로세스는 응답을 작성하여 Apache로 돌아갑니다. Apache는이 응답을 브라우저로 보냅니다.

CGI는 원시적이고 성가시다. 대부분 요청마다 서브 프로세스를 분기하므로 서브 프로세스는 stdout 및 stderr를 종료하거나 닫아 응답의 끝을 나타냅니다.

WSGI는 CGI 디자인 패턴을 기반으로하는 인터페이스입니다. 반드시 CGI 일 필요는 없으며 각 요청에 대해 하위 프로세스를 분기 할 필요는 없습니다. CGI 일 수 있지만 반드시 그럴 필요는 없습니다.

WSGI는 몇 가지 중요한 방식으로 CGI 디자인 패턴에 추가됩니다. HTTP 요청 헤더를 구문 분석하고이를 환경에 추가합니다. 환경에서 POST 지향 입력을 파일과 같은 오브젝트로 제공합니다. 또한 응답을 공식화하는 기능을 제공하여 많은 서식 세부 사항을 저장합니다.

기본 CGI 구성에서 웹 프레임 워크 (예 : web.py 또는 cherrypy)를 실행하려면 무엇을 알고 / 설치 /해야합니까?

하위 프로세스를 포크하는 것은 비용이 많이 듭니다. 이 문제를 해결하는 데는 두 가지 방법이 있습니다.

  1. 아파치 안에 파이썬을 내장mod_wsgi 하거나 mod_python내장한다; 프로세스가 분기되지 않습니다. Apache는 Django 애플리케이션을 직접 실행합니다.

  2. WSGI 프로토콜을 사용하여 데몬mod_wsgi 또는 mod_fastcgiApache가 별도의 데몬 (또는 "장기 실행 프로세스")과 상호 작용할 수 있도록합니다. 장기 실행 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 runfcgiFLUP와 처리기를 통합 하는 제공 합니다.

mod_wsgi의 경우이를위한 핵심 처리기가 있습니다.

WSGI 지원을 설치하는 방법?

다음 지시 사항을 따르십시오.

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

배경은 이것을 참조하십시오

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


플로리안의 답변 은 특히 PEP 를 읽는 경우 "WSGI 란 무엇인가"에 대한 귀하의 질문에 대한 답변 이라고 생각 합니다 .

끝까지 향한 질문에 관해서는 :

WSGI, CGI, FastCGI 등은 웹 서버가 코드실행 하고 생성되는 동적 컨텐츠를 제공 하기위한 모든 프로토콜입니다 . 이것을 일반 웹 파일과 비교하면 일반 HTML 파일이 기본적으로 클라이언트에 그대로 제공됩니다.

CGI, FastCGI 및 SCGI는 언어에 구애받지 않습니다. Perl, Python, C, bash 등으로 CGI 스크립트를 작성할 수 있습니다. CGI는 URL을 기반으로 호출 실행 파일과 호출 방법 ( 인수 및 환경)을 정의합니다. 실행 파일이 완료되면 반환 값을 웹 서버로 다시 전달하는 방법도 정의합니다. 변형은 기본적으로 더 많은 요청을 처리하고 지연 시간을 줄일 수있는 최적화입니다. 기본 개념은 동일합니다.

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를 지원하는 웹 서버 (예 : mod_wsgi가있는 Apache)는 요청이 도착할 때마다이 기능을 호출 할 수 있습니다.

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.


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.


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


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).

참고URL : https://stackoverflow.com/questions/219110/how-python-web-frameworks-wsgi-and-cgi-fit-together

반응형