-
-
Save p--q/558d9531cff0dcc8e103 to your computer and use it in GitHub Desktop.
マルチスレッド化したWSGIサーバの例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
from wsgiref import simple_server | |
import socketserver | |
class ThreadedWSGIServer(socketserver.ThreadingMixIn, simple_server.WSGIServer): # WSGIServerをマルチスレッド対応にしたクラスを作成。 | |
pass | |
def calculator(val): # 引数の値を初期値としてそれを2倍にした値を返す関数を返す。 | |
def f(): # 関数f()を定義。 | |
nonlocal val # 関数calc()のローカル変数valを使用。 | |
val *= 2 # 2倍にする。 | |
return val # これは関数f()の戻り値。 | |
return f # これは関数calc()の戻り値。 | |
def counter(n): # 引数の値を初期値としてそれに1加えた値を返す関数を返す。 | |
def f(): # 関数f()を定義。 | |
nonlocal n # 関数counter()のローカル変数valを使用。 | |
n += 1 # 1を加える。 | |
return n # これは関数f()の戻り値。 | |
return f # これは関数counter()の戻り値。 | |
def app(environ, start_response): # WSGIアプリ。辞書environを引数にとる。 | |
start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')]) # start_responseを設定。 | |
path = environ['PATH_INFO'] # 辞書environからURLのパスを取得。 | |
if path == "/stop": # パスがstopのとき。 | |
server.shutdown() # WSGIサーバを停止終了する。 | |
return ["終了".encode()] # 終了と出力。このあとにスクリプトが終了。 | |
elif path == "/reset": # パスがresetのとき。 | |
global count # グローバルスコープのcountを使用することを宣言。 | |
global calc # グローバルスコープのcalcを使用することを宣言。 | |
count = counter(1) # countにcounter()が返す1を初期値とする関数を代入。 | |
calc = calculator(2) # calcにcalculator()が返す2を初期値とする関数を代入。 | |
c = count() # 関数countを呼び出して戻り値をcに代入。 | |
val = calc() # 関数calcを呼び出して戻り値をvalに代入。 | |
html = ''' | |
{2}(=2<sup>{3}</sup>)を2倍にした計算結果 2<sup>{4}</sup>={5}<br> | |
<br> | |
<a href="http://{0}:{1}">この計算結果をさらに2倍する</a><br> | |
<br> | |
<a href="http://{0}:{1}/reset">最初に戻る</a><br> | |
<br> | |
<a href="http://{0}:{1}/stop">WSGIサーバを停止する</a> | |
'''.format(host, port, val//2, c-1, c, val) # 出力するhtmlを作成。 | |
return [html.encode()] # htmlをUTF-8からバイト列に変換して返す。 | |
if __name__ == "__main__": # ここから開始。 | |
calc = calculator(2) # countにcounter()が返す1を初期値とする関数を代入。グローバルスコープ。 | |
count = counter(1) # calcにcalculator()が返す2を初期値とする関数を代入。 | |
host, port = "localhost", 8000 # ホスト名とポート番号を設定。 | |
server = simple_server.make_server(host, port, app, ThreadedWSGIServer) # appへの接続を受け付けるThreadedWSGIServerを生成。 | |
url = "http://{}:{}".format(host, port) # 出力先のurlを取得。 | |
import threading | |
server_thread = threading.Thread(target=server.serve_forever) # 要求によりスレッドを生成するメソッドをtargetに指定。 | |
server_thread.start() # スレッドの受付を開始。 | |
import webbrowser | |
webbrowser.open_new_tab(url) # デフォルトのブラウザでurlを開く。 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment