Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 2개 있습니다.)
(시리즈 글이 3개 있습니다.)
스크립트: 23. 파이썬 - WSGI를 만족하는 최소한의 구현 코드 및 PyCharm에서의 디버깅 방법
; https://www.sysnet.pe.kr/2/0/12794

스크립트: 64. 파이썬 - ASGI를 만족하는 최소한의 구현 코드
; https://www.sysnet.pe.kr/2/0/13633

스크립트: 65. 파이썬 - asgi 버전(2, 3)에 따라 달라지는 uvicorn 호스팅
; https://www.sysnet.pe.kr/2/0/13642




파이썬 - WSGI를 만족하는 최소한의 구현 코드 및 PyCharm에서의 디버깅 방법

uwsgi나 gunicorn이,

파이썬 - 윈도우 환경에서 개발한 Django 앱을 WSL 환경의 uwsgi를 이용해 실행
; https://www.sysnet.pe.kr/2/0/12772

파이썬 - 윈도우 환경에서 개발한 Django 앱을 WSL 환경의 gunicorn을 이용해 실행
; https://www.sysnet.pe.kr/2/0/12775

Django App을 동일하게 실행시킬 수 있는 건 2개의 응용 프로그램 사이에 WSGI라는 공통 규약이 있기 때문입니다.

PEP 333 -- Python Web Server Gateway Interface v1.0
; https://www.python.org/dev/peps/pep-0333/

PEP 3333 -- Python Web Server Gateway Interface v1.0.1
; https://www.python.org/dev/peps/pep-3333/

그렇다는 건, 꼭 Django를 사용하지 않더라도 저 WSGI 규약만 맞춰주면 우리가 만든 앱을 uwsgi/gunicorn을 이용해 동일하게 실행시킬 수 있다는 것을 의미합니다.

실제로 "PEP 3333 -- Python Web Server Gateway Interface v1.0.1" 문서에 실린 코드가 바로 WSGI 규약을 만족하는 최소한의 구현 코드입니다.

# main.py

HELLO_WORLD = b"Hello world!\n"


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]


application = simple_app

(닷넷과 비교하면 ASP.NET의 Route-to-code 방식과 유사합니다. ^^)

저렇게만 만들어 두면 이제 다음과 같이 gunicorn을 사용해 실행하는 것이 가능합니다.

$ gunicorn --bind 0.0.0.0:18090 main
[2021-08-18 18:14:02 +0900] [1670] [INFO] Starting gunicorn 20.0.4
[2021-08-18 18:14:02 +0900] [1670] [INFO] Listening at: http://0.0.0.0:18090 (1670)
[2021-08-18 18:14:02 +0900] [1670] [INFO] Using worker: sync
[2021-08-18 18:14:02 +0900] [1672] [INFO] Booting worker with pid: 1672

즉, uwsgi/gunicorn은 파이썬 애플리케이션으로부터 무조건 "application" 전역 변수에 설정된 웹 프레임워크 인스턴스를 받아와 Request/Response 처리를 넘겨주는 것입니다. 사실 여기서 application은 기본값에 불과하므로 이것을 정의하지 않는다면 다음과 같이 직접 simple_app을 지정하는 것도 가능합니다.

$ gunicorn --bind 0.0.0.0:18090 main:simple_app

어쨌든 이렇게 준비를 마쳤으면, 웹 브라우저에서 "http://localhost:18090"으로 접속해 "Hello world!"라는 문자열을 볼 수 있습니다.




그런데, 저렇게 구현한 코드를 어떻게 디버깅해야 하는 걸까요? 가령, PyCharm IDE 같은 환경에서 main.py의 simple_app 함수를 실행하는 순간 디버깅하고 싶으면 어떻게 해야 하냐는 것입니다.

(Visual Studio를 사용하는) 윈도우 개발자라면 이런 경우 시작 프로세스를 "gunicorn"으로, 명령행 인자에 "--bind 0.0.0.0:18090 main"으로 지정하고 F5 키를 누르면 실행 시 디버깅이 될 것이라는... 사용자 경험을 가지고 있습니다.

하지만, PyCharm의 경우에는 무조건 "Python Interpreter"의 'python'이 시작 프로세스로 지정돼 있어야 하고 이후의 명령행을 지정하는 식입니다. 이로 인해 시작 프로세스가 gunicorn/uwsgi라면 디버깅이 안 되는 것입니다.

이런 때 사용할 수 있는 서버가 바로 wsgiref입니다.

wsgiref — WSGI Utilities and Reference Implementation
; https://docs.python.org/3/library/wsgiref.html#module-wsgiref.simple_server

따라서 위의 문서에 나온 예제 코드에 따라 다음과 같이 간단하게 (uwsgi/gunicorn을 대체하는) Web Server를 python 코드로 완성할 수 있습니다.

# runserver.py

from wsgiref.validate import validator
from wsgiref.simple_server import make_server
import main

validator_app = validator(main.simple_app)

with make_server('', 18090, validator_app) as httpd:
    print("Listening on port 18090....")
    httpd.serve_forever()

이제 PyCharm의 "Run/Debug Configuration"에서 "Script path"를 "...[프로젝트 경로]...\runserver.py"로 지정하고 실행하면 simple_app의 코드에 BP를 걸고 디버깅을 할 수 있습니다. (PyCharm과 관련한 디버깅 방법은 이후로도 쭉 소개하겠습니다. ^^)

아울러 아래의 글들도 참고하시고. ^^

Quickstart uwsgi
; https://brunch.co.kr/@ddangdol/8

wsgi를 왜 쓰나요
; https://uiandwe.tistory.com/1268

[python] 서버의 기본 동작 방식
; https://uiandwe.tistory.com/1240




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 8/20/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2021-08-24 10시16분
정성태

... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12208정성태4/12/202015955Linux: 29. 리눅스 환경에서 C/C++ 프로그램이 Segmentation fault 에러가 발생한 경우
12207정성태4/2/202015752스크립트: 19. Windows PowerShell의 NonInteractive 모드
12206정성태4/2/202018407오류 유형: 613. 파일 잠금이 바로 안 풀린다면? - The process cannot access the file '...' because it is being used by another process.
12205정성태4/2/202015063스크립트: 18. Powershell에서는 cmd.exe의 명령어를 지원하진 않습니다.
12204정성태4/1/202015074스크립트: 17. Powershell 명령어에 ';' (semi-colon) 문자가 포함된 경우
12203정성태3/18/202017901오류 유형: 612. warning: 'C:\ProgramData/Git/config' has a dubious owner: '...'.
12202정성태3/18/202021173개발 환경 구성: 486. .NET Framework 프로젝트를 위한 GitLab CI/CD Runner 구성
12201정성태3/18/202018402오류 유형: 611. git-credential-manager.exe: Using credentials for username "Personal Access Token". [1]
12200정성태3/18/202018506VS.NET IDE: 145. NuGet + Github 라이브러리 디버깅 관련 옵션 3가지 - "Enable Just My Code" / "Enable Source Link support" / "Suppress JIT optimization on module load (Managed only)"
12199정성태3/17/202016146오류 유형: 610. C# - CodeDomProvider 사용 시 Unhandled Exception: System.IO.DirectoryNotFoundException: Could not find a part of the path '...\f2_6uod0.tmp'.
12198정성태3/17/202019525오류 유형: 609. SQL 서버 접속 시 "Cannot open user default database. Login failed."
12197정성태3/17/202018777VS.NET IDE: 144. .NET Core 콘솔 응용 프로그램을 배포(publish) 시 docker image 자동 생성 - 두 번째 이야기 [1]
12196정성태3/17/202015933오류 유형: 608. The ServicedComponent being invoked is not correctly configured (Use regsvcs to re-register).
12195정성태3/16/202018257.NET Framework: 902. C# - 프로세스의 모든 핸들을 열람 - 세 번째 이야기
12194정성태3/16/202020983오류 유형: 607. PostgreSQL - Npgsql.NpgsqlException: sorry, too many clients already
12193정성태3/16/202017883개발 환경 구성: 485. docker - SAP Adaptive Server Enterprise 컨테이너 실행 [1]
12192정성태3/14/202019902개발 환경 구성: 484. docker - Sybase Anywhere 16 컨테이너 실행
12191정성태3/14/202021025개발 환경 구성: 483. docker - OracleXE 컨테이너 실행 [1]
12190정성태3/14/202015587오류 유형: 606. Docker Desktop 업그레이드 시 "The process cannot access the file 'C:\Program Files\Docker\Docker\resources\dockerd.exe' because it is being used by another process."
12189정성태3/13/202021179개발 환경 구성: 482. Facebook OAuth 처리 시 상태 정보 전달 방법과 "유효한 OAuth 리디렉션 URI" 설정 규칙
12188정성태3/13/202026009Windows: 169. 부팅 시점에 실행되는 chkdsk 결과를 확인하는 방법
12187정성태3/12/202015538오류 유형: 605. NtpClient was unable to set a manual peer to use as a time source because of duplicate error on '...'.
12186정성태3/12/202017390오류 유형: 604. The SysVol Permissions for one or more GPOs on this domain controller and not in sync with the permissions for the GPOs on the Baseline domain controller.
12185정성태3/11/202017964오류 유형: 603. The browser service was unable to retrieve a list of servers from the browser master...
12184정성태3/11/202019892오류 유형: 602. Automatic certificate enrollment for local system failed (0x800706ba) The RPC server is unavailable. [3]
12183정성태3/11/202017696오류 유형: 601. Warning: DsGetDcName returned information for \\[...], when we were trying to reach [...].
... 61  62  63  64  65  66  67  68  [69]  70  71  72  73  74  75  ...