ヌートリ日記

開発というより環境構築系のブログ

Python Hello world!

この記事の内容

uwsgi使ってPythonアプリケーションサーバを構築する

pipenvを使っているぐらいで他に変わったことは特になし

開発環境

macOS High Sierra 10.13.6

Pythonのバージョン固定

$ echo '3.7.0' > .python-version

パッケージ管理ツールの導入

$ pipenv install
$ cat Pipfile
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[packages]

[dev-packages]

[requires]
python_version = "3.7"

uwsgiとlogger追加

$ pipenv install uwsgi logger

uwsgi setup

$ vim uwsgi.ini
[uwsgi]
master = True
socket = 127.0.0.1:3031
wsgi-file = index.py
stats = 127.0.0.1:9191
logto = uwsgi.log
pidfile = uwsgi.pid

$ touch uwsgi.log

uwsgi code

$ vim index.py
# coding:utf-8

import logging

handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger = logging.getLogger()
logger.addHandler(handler)
logger.setLevel(logging.INFO)

def main():
    logger.info('Hello world!')

def application(env, start_response):
    main()
    start_response('200 OK', [('Content-Type','text/html')])
    return "Hello World!"

uwsgi start

$ pipenv shell
Launching subshell in virtual environment…
. /path/to/virtualenvs/app-xxxxxxxx/bin/activate
(app-xxxxxxxx) $ uwsgi --ini uwsgi.ini
[uWSGI] getting INI configuration from uwsgi.ini

動作確認

$ curl localhost:3031
$ cat uwsgi.log
.
.
.
2018-07-19 13:41:17,632 - root - INFO - Hello world!
[pid: 330|app: 0|req: 1/1] 127.0.0.1 () {28 vars in 293 bytes} [Thu Jul 19 13:41:17 2018] GET / => generated 0 bytes in 1 msecs (HTTP/1.1 200) 1 headers in 44 bytes (12 switches on core 0)