-
-
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 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 calc # グローバルスコープのcalcを使用することを宣言。 | |
calc = [1, 2] # リストcalcをリセット。 | |
else: | |
calc[0] += 1 # リストの0番目の要素に1を加える。 | |
calc[1] *= 2 # リストの1番目の要素を2倍にする。 | |
c, val = calc # リストの値をそれぞれcと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 = [1, 2] # グローバル変数calcに初期値を代入。 | |
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