Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 8개 있습니다.)

파이썬 - 윈도우 환경에서 개발한 Django 앱을 WSL 환경의 uwsgi를 이용해 실행

사실 uwsgi를 사용한다는 것은 서비스하겠다는 것이므로 WSL 환경에서 굳이 사용할 필요는 없습니다. 따라서 그냥 할 수 있다는 정도만 알고 (게다가 요즘은 gunicorn이 유명하다고 하니 더더욱) 넘어가셔도 무방한데요, 그래도 리눅스 서버에 올리기 전 확인을 해보고 싶은 분들이라면 간단하게 WSL을 이용해 볼 수도 있을 것입니다.

예를 들어, 다음과 같은 구조의 간단한 Django app을 만들었다고 가정하겠습니다.

./myapp
├───bbs
│   ├───migrations
│   ├───static
│   │   └───bbs
│   ├───templates
│   │   └───bbs
├───myapp
│   └───__pycache__
├───static
│   ├───admin
└───templates
    └───registration

(wsgi 파일은 ./myapp/myapp/wsgi.py에 있습니다.)

자, 그럼 우선 wsl 환경에 python을 위한 모듈을 먼저 설치하고,

$ sudo apt install python3

// ubuntu 20.04 + python 3.11
// https://ubuntuhandbook.org/index.php/2022/10/python-3-11-released-how-install-ubuntu/
$ sudo add-apt-repository ppa:deadsnakes/ppa
$ sudo apt update

$ sudo apt install python3.11
// 또는,
$ sudo apt install python3.11-full

$ python3.11 --version

이후의 다양한 환경 설정을 분리하기 위해 virtualenv도 설치 후,

$ sudo pip3 install virtualenv

가상 환경을 적당한 디렉터리(pyenv 하위의 myapp)에 활성화합니다.

$ cd ~
~$ mkdir pyenv
~$ cd pyenv
~/pyenv$ virtualenv myapp

~/pyenv$ source myapp/bin/activate
(myapp) testusr@TESTPC:~/pyenv$

마지막으로 (우여곡절 끝에 - 문제 1, 문제 2) Django와 uwsgi를 설치합니다.

(myapp) testusr@TESTPC:~/pyenv$ python3 -m pip install --upgrade pip

(myapp) testusr@TESTPC:~/pyenv$ pip3 install Django 
(myapp) testusr@TESTPC:~/pyenv$ pip3 install uwsgi




이제 uwsgi에서 호스팅하기 위한 Django App의 사전 준비를 합니다. 이 작업은 윈도우 개발 환경에서 해주시면 됩니다.

우선 settings.py에 정적 리소스를 위한 루트 디렉터리를 지정하고,

# settings.py

STATIC_ROOT = os.path.join(BASE_DIR, 'static/')

마이그레이션 후,

// 예를 들어 D:\pycharm\work\myapp에 Django 앱이 위치한 경우
c:\temp> cd D:\pycharm\work\myapp

// 개발하는 동안 수행한 적이 있으면 무시

d:\pycharm\work\myapp> python manage.py makemigrations
d:\pycharm\work\myapp> python manage.py migrate
d:\pycharm\work\myapp> python manage.py createsuperuser

정적 콘텐츠들을 모아줍니다.

D:\pycharm\work\myapp> python ./manage.py collectstatic

You have requested to collect static files at the destination
location as specified in your settings:

    D:\pycharm\work\myapp\static

This will overwrite existing files!
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel: yes

128 static files copied to 'D:\pycharm\work\myapp\static', 1 unmodified.




끝입니다. 이제 WSL에서 다음과 같은 옵션을 이용해,

-H|--home                               set PYTHONHOME/virtualenv
-H|--pyhome                             set PYTHONHOME/virtualenv

--http                                  add an http router/server on the specified address

--chdir                                 chdir to specified directory before apps loading
--chdir2                                chdir to specified directory after apps loading

--wsgi-file                             load .wsgi file
--file                                  load .wsgi file
-w|--module                             load a WSGI module
-w|--wsgi                               load a WSGI module

호스팅을 시작합니다.

uwsgi --http :[포트]
      --home [virtualenv_path]
      --chdir [webapp_path]
      --wsgi-file [chdir 기준 wsgi.py 경로]

예1) 18080 포트로, 윈도우의 d:\pycharm\work\myapp에 Django 앱을 개발한 경우
uwsgi --http :18080 
      --home $HOME/pyenv/myapp 
      --chdir /mnt/d/pycharm/work/myapp 
      --wsgi-file ./myapp/wsgi.py

예2) virtualenv를 사용하지 않겠다면,
uwsgi --http :18080 
      --chdir /mnt/d/pycharm/work/myapp 
      --wsgi-file ./myapp/wsgi.py

예3) 이미 current directory가 Django App의 경로라면,
/mnt/d/pycharm/work/myapp$ uwsgi --http :18080 --wsgi-file ./myapp/wsgi.py

그래서 이렇게 실행하고,

$ uwsgi --http :18080 --home $HOME/pyenv/myapp --chdir /mnt/d/pycharm/work/myapp --wsgi-file ./myapp/wsgi.py
*** Starting uWSGI 2.0.19.1 (64bit) on [Wed Aug 11 17:40:05 2021] ***
compiled with version: 9.3.0 on 10 August 2021 10:28:41
os: Linux-5.10.16.3-microsoft-standard-WSL2 #1 SMP Fri Apr 2 22:23:49 UTC 2021
nodename: TESTPC
machine: x86_64
clock source: unix
detected number of CPU cores: 4
current working directory: /mnt/d/pycharm/work/myapp
detected binary path: /home/testusr/pyenv/myapp/bin/uwsgi
!!! no internal routing support, rebuild with pcre support !!!
chdir() to /mnt/d/pycharm/work/myapp
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 102268
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
uWSGI http bound on :18080 fd 4
spawned uWSGI http 1 (pid: 20543)
uwsgi socket 0 bound to TCP address 127.0.0.1:40761 (port auto-assigned) fd 3
Python version: 3.8.10 (default, Jun  2 2021, 10:49:15)  [GCC 9.4.0]
PEP 405 virtualenv detected: /home/testusr/pyenv/myapp
Set PythonHome to /home/testusr/pyenv/myapp
*** Python threads support is disabled. You can enable it with --enable-threads ***
Python main interpreter initialized at 0x563d77ee7080
your server socket listen backlog is limited to 100 connections
your mercy for graceful operations on workers is 60 seconds
mapped 72904 bytes (71 KB) for 1 cores
*** Operational MODE: single process ***
WSGI app 0 (mountpoint='') ready in 0 seconds on interpreter 0x563d77ee7080 pid: 20542 (default app)
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (and the only) (pid: 20542, cores: 1)
/mnt/d/pycharm/work/myapp

/* uwsgi 이름을 가진 모든 프로세스를 종료하고 싶다면?
sudo pkill -f uwsgi -9
*/

"http://localhost:18080/bbs"로 요청을 보내면 정상적으로 ./bbs/views.py가 요청을 처리하는 것을 확인할 수 있습니다.

참고로, wsgi.py의 의미는 다음의 문서를 읽어보시면 이해가 되실 것입니다.

Quickstart for Python/WSGI applications
; https://uwsgi-docs.readthedocs.io/en/latest/WSGIquickstart.html




만약 uwsgi로 실행했는데 페이지 요청 시 "Internal Server Error"가 발생한다면? 아마 거의 대부분 uwsgi 출력 화면에 다음과 같은 메시지가 있을 것입니다.

...[생략]...
failed to open python file wsgi.py
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***
*** uWSGI is running in multiple interpreter mode ***
spawned uWSGI worker 1 (and the only) (pid: 20588, cores: 1)
--- no python application found, check your startup logs for errors ---
[pid: 20588|app: -1|req: -1/1] 127.0.0.1 () {52 vars in 1114 bytes} [Wed Aug 11 15:09:37 2021] GET /bbs/ => generated 21 bytes in 0 msecs (HTTP/1.1 500) 2 headers in 83 bytes (0 switches on core 0)

이런 경우 uwsgi 실행 시 넘겨 준 "--wsgi-file" 옵션의 경로가 올바른지 확인해 보세요. 또는, "-w" 옵션으로 모듈 경로를 넘겨주는 것도 볼 수 있는데요,

$ uwsgi --http :18080 --home $HOME/pyenv/myapp --chdir /mnt/d/pycharm/work/myapp -w test.wsgi

이럴 때는 로그에 ModuleNotFoundError 메시지가 남습니다.

...[생략]...
ModuleNotFoundError: No module named 'test.wsgi'
unable to load app 0 (mountpoint='') (callable not found or import error)
*** no app loaded. going in full dynamic mode ***
...[생략]...

이번 예제와 같은 경우에는 (wsgi.py가 current directory 기준으로 myapp 디렉터리 하위에 있으므로) "-w myapp.wsgi"라고 설정해야 합니다.




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/15/2022]

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

비밀번호

댓글 작성자
 



2021-12-13 02시17분
정성태

... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13222정성태1/20/20233934개발 환경 구성: 657. WSL - DockerDesktop.vhdx 파일 위치를 옮기는 방법
13221정성태1/19/20234167Linux: 57. C# - 리눅스 프로세스 메모리 정보파일 다운로드1
13220정성태1/19/20234316오류 유형: 837. NETSDK1045 The current .NET SDK does not support targeting .NET ...
13219정성태1/18/20233881Windows: 220. 네트워크의 인터넷 접속 가능 여부에 대한 판단 기준
13218정성태1/17/20233811VS.NET IDE: 178. Visual Studio 17.5 (Preview 2) - 포트 터널링을 이용한 웹 응용 프로그램의 외부 접근 허용
13217정성태1/13/20234406디버깅 기술: 185. windbg - 64비트 운영체제에서 작업 관리자로 뜬 32비트 프로세스의 덤프를 sos로 디버깅하는 방법
13216정성태1/12/20234658디버깅 기술: 184. windbg - 32비트 프로세스의 메모리 덤프인 경우 !peb 명령어로 나타나지 않는 환경 변수
13215정성태1/11/20236182Linux: 56. 리눅스 - /proc/pid/stat 정보를 이용해 프로세스의 CPU 사용량 구하는 방법 [1]
13214정성태1/10/20235742.NET Framework: 2087. .NET 6부터 SourceGenerator와 통합된 System.Text.Json [1]파일 다운로드1
13213정성태1/9/20235271오류 유형: 836. docker 이미지 빌드 시 "RUN apt install ..." 명령어가 실패하는 이유
13212정성태1/8/20235032기타: 85. 단정도/배정도 부동 소수점의 정밀도(Precision)에 따른 형변환 손실
13211정성태1/6/20235113웹: 42. (https가 아닌) http 다운로드를 막는 웹 브라우저
13210정성태1/5/20234134Windows: 219. 윈도우 x64의 경우 0x00000000`7ffe0000 아래의 주소는 왜 사용하지 않을까요?
13209정성태1/4/20234040Windows: 218. 왜 윈도우에서 가상 메모리 공간은 64KB 정렬이 된 걸까요?
13208정성태1/3/20233983.NET Framework: 2086. C# - Windows 운영체제의 2MB Large 페이지 크기 할당 방법파일 다운로드1
13207정성태12/26/20224287.NET Framework: 2085. C# - gpedit.msc의 "User Rights Assignment" 특권을 코드로 설정/해제하는 방법파일 다운로드1
13206정성태12/24/20224500.NET Framework: 2084. C# - GetTokenInformation으로 사용자 SID(Security identifiers) 구하는 방법 [3]파일 다운로드1
13205정성태12/24/20224888.NET Framework: 2083. C# - C++과의 연동을 위한 구조체의 fixed 배열 필드 사용 (2)파일 다운로드1
13204정성태12/22/20224169.NET Framework: 2082. C# - (LSA_UNICODE_STRING 예제로) CustomMarshaler 사용법파일 다운로드1
13203정성태12/22/20224329.NET Framework: 2081. C# Interop 예제 - (LSA_UNICODE_STRING 예제로) 구조체를 C++에 전달하는 방법파일 다운로드1
13202정성태12/21/20224713기타: 84. 직렬화로 설명하는 Little/Big Endian파일 다운로드1
13201정성태12/20/20225331오류 유형: 835. PyCharm 사용 시 C 드라이브 용량 부족
13200정성태12/19/20224206오류 유형: 834. 이벤트 로그 - SSL Certificate Settings created by an admin process for endpoint
13199정성태12/19/20224495개발 환경 구성: 656. Internal Network 유형의 스위치로 공유한 Hyper-V의 VM과 호스트가 통신이 안 되는 경우
13198정성태12/18/20224374.NET Framework: 2080. C# - Microsoft.XmlSerializer.Generator 처리 없이 XmlSerializer 생성자를 예외 없이 사용하고 싶다면?파일 다운로드1
13197정성태12/17/20224308.NET Framework: 2079. .NET Core/5+ 환경에서 XmlSerializer 사용 시 System.IO.FileNotFoundException 예외 발생하는 경우파일 다운로드1
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...