Share
Embed
Transcript
219 slides
-
썡쎕썟썷쎣쎟 •ా ൏ʢJunya Fukudaʣʢ@JunyaFffʣ •גࣜձࣾຊγεςϜٕݚʢJSLʣॴଐ •PyCon JP 2020 Gold Sponser
ʢΦϯϥΠϯϒʔεʹ༡ͼʹ͖ͯͶʣ •GEEKLAB.NAGANO •࠷ۙϚΠϯΫϥϑτͰখֶੜ͚Youtube৴࢝ΊΔ ΪʔΫϥϘϚΠΫϥ -
)551쎂썻썛썽쎅썡썬쎠썛 •HTTP/1.0 •HTTP/2 •HTTP/3 1990 2000 2010 2020 •HTTP/0.9 •HTTP/1.1
1997 •HTTPͷඪ४ԽΛ࣌ܥྻʹ -
)551쎂썻썛썽쎅썡썬쎠썛 •HTTP/1.0 •HTTP/2 •HTTP/3 1990 2000 2010 2020 •HTTP/0.9 •HTTP/1.1
1997 1999 •HTTPͷඪ४ԽΛ࣌ܥྻʹ -
)551쎂썻썛썽쎅썡썬쎠썛 •HTTP/1.0 •HTTP/2 •HTTP/3 1990 2000 2010 2020 •HTTP/0.9 •HTTP/1.1
1997 1999 2015 •HTTPͷඪ४ԽΛ࣌ܥྻʹ -
)551쎂썻썛썽쎅썡썬쎠썛 •HTTP/1.0 •HTTP/2 •HTTP/3 1990 2000 2010 2020 •HTTP/0.9 •HTTP/1.1
1997 1999 2015 •HTTPͷඪ४ԽΛ࣌ܥྻʹ ύϑΥʔϚεͷ্ʹϑΥʔΧε -
)551쎂썻썛썽쎅썡썬쎠썛 •HTTP/1.0 •HTTP/2 •HTTP/3 1990 2000 2010 2020 •HTTP/0.9 •HTTP/1.1
1997 1999 2015 2020ϒϥβͰରԠ࢝·Γͩ͢ •HTTPͷඪ४ԽΛ࣌ܥྻʹ -
)551쎂썻썛썽쎅썡썬쎠썛 •HTTP/1.0 •HTTP/2 •HTTP/3 1990 2000 2010 2020 •HTTP/0.9 •HTTP/1.1
1997 1999 2015 •WebSocket •֦ுػೳ -
)551쎂썻썛썽쎅썡썬쎠썛 •HTTP/1.0 •HTTP/2 •HTTP/3 1990 2000 2010 2020 •HTTP/0.9 •HTTP/1.1
1997 1999 2015 •WebSocket 2011 •WebSocketͷొʢRFC6455ʣ -
84(* •WSGIͷొ •HTTP/2 2000 2010 2020 •HTTP/1.1 1999 2015 •WebSocket
2011 WSGI 2003 2016 -
"4(* •ASGIͷొ •HTTP/2 2000 2010 2020 •HTTP/1.1 1999 2015 •WebSocket
2011 WSGI 2003 2016 -
"4(* •ASGIͷొ •HTTP/2 2000 2010 2020 •HTTP/1.1 1999 2015 •WebSocket
2011 WSGI 2003 2016 ASGI -
84(*"4(*쎅쎿쏧썗쏒 •WSGIHTTP1.1Λαϙʔτ •ASGIHTTP/1.1͔ΒWebSocketɺHTTP/2 •HTTP/2 2000 2010 2020 •HTTP/1.1 1999 2015
•WebSocket 2011 WSGI 2003 2016 ASGI -
84(* •WSGIʢWeb Server Gateway Interfaceʣͷུ •2003ʹPEP 333 ʢ 2010 PEP
3333 Python3ରԠʣ IUUQTXXXQZUIPOPSHEFWQFQTQFQ -
84(* •WSGIʢWeb Server Gateway Interfaceʣͷུ •2003ʹPEP 333 ʢ 2010 PEP
3333 Python3ରԠʣ IUUQTXXXQZUIPOPSHEFWQFQTQFQ -
84(* •WSGIʢWeb Server Gateway Interfaceʣͷུ •TypeʮInformationalʯ •2003ʹPEP 333 ʢ 2010
PEP 3333 Python3ରԠʣ ΫϥΠΞϯτ 8FCαʔό ΞϓϦέʔγϣϯ ϑϨʔϜϫʔΫ -
84(*쎅ࢦ썮썶쎾썗쏵 “PythonݱࡏɺZope, Quixote, Webware, SkunkWeb, PSO, Twisted WebͳͲɺଟछଟ༷ͳWebΞϓϦέʔγϣϯϑϨʔϜ ϫʔΫΛތ͍ͬͯ·͢ɻWebϑϨʔϜϫʔΫͷબ༻Մೳͳ WebαʔόʔͷબΛ੍ݶ͠ɺͦͷٯಉ༷Ͱ͋ΔͨΊɺ͜ͷ෯
͍બࢶ৽͍͠PythonϢʔβʔʹͱͬͯʹͳΔՄೳੑ͕ ͋Γ·͢ɻ” - PEP 333 https://www.python.org/dev/peps/pep-0333/#rationale-and-goals -
84(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ environ = { "REQUEST_METHOD": "GET", "SCRIPT_NAME": "", "PATH_INFO": "/",
"QUERY_STRING":"search=red+blue&maximum_price=20", "SERVER_NAME": "www.example.org", "SERVER_PORT": 443, "REMOTE_HOST": "134.56.78.4", "REMOTE_PORT": 1453, "SERVER_PROTOCOL": "HTTP/1.1", "HTTP_HOST": "www.example.org", "HTTP_ACCEPT": "application/json", } -
84(*쎿썗쏚 def application(environ, start_response): start_response( '200, OK', [('Content-Type', 'text/plain')] )
return [b'Hello, World'] 84(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ -
84(*쎿썗쏚 def application(environ, start_response): start_response( '200, OK', [('Content-Type', 'text/plain')] )
return [b'Hello, World'] 84(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ -
84(*쎿썗쏚 def application(environ, start_response): start_response( '200, OK', [('Content-Type', 'text/plain')] )
return [b'Hello, World'] 84(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ •WSGIڥมͷ࡞ -
84(*쎿썗쏚 def application(environ, start_response): start_response( '200, OK', [('Content-Type', 'text/plain')] )
return [b'Hello, World'] 84(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ •WSGIڥมͷ࡞ •WSGIΞϓϦέʔγϣϯ͔Βݺͼग़͞ΕΔίʔϧόοΫؔͷ࡞ -
84(*쎿썗쏚 84(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ •WSGIڥมͷ࡞ •WSGIΞϓϦέʔγϣϯ͔Βݺͼग़͞ΕΔίʔϧόοΫؔͷ࡞ •WSGIΞϓϦέʔγϣϯͷݺͼग़͠ def application(environ, start_response): start_response( '200,
OK', [('Content-Type', 'text/plain')] ) return [b'Hello, World'] -
•WSGIڥมͷ࡞ env = {} env['wsgi.version'] = (1, 0) # WSGIͷόʔδϣϯɿܾΊଧͪ
env['wsgi.url_scheme'] = 'http' # urlͷεΩʔϜ(http/https) # HTTP ϦΫΤετຊମͷόΠτྻΛಡΈग़͢͜ͱ͕Ͱ͖ΔೖྗετϦʔϜ env['wsgi.input'] = io.BytesIO(byte_request) env['wsgi.errors'] = sys.stderr env['wsgi.multithread'] = False env['wsgi.multiprocess'] = False env['wsgi.run_once'] = False env['REQUEST_METHOD'] = request_method # GET env['PATH_INFO'] = path # / env['SERVER_NAME'] = server_name # FQDN env['SERVER_PORT'] = str(port) # 8888 IUUQTXXXQZUIPOPSHEFWQFQTQFQFOWJSPOWBSJBCMFT 84(*쎿썗쏚 -
•WSGIΞϓϦέʔγϣϯ͔Βݺͼग़͞ΕΔίʔϧόοΫؔͷ࡞ IUUQTXXXQZUIPOPSHEFWQFQTQFQUIFTUBSUSFTQPOTFDBMMBCMF def start_response(status, response_headers, exc_info=None): # ҙͷ༰ͷɺWSGIαʔόͰՃ͢ΔϨεϙϯεϔομ server_headers =
[ ('Date', 'Sat, 16 Jul 2016 00:00:00 JST'), ('Server', 'HenaWSGIServer 0.1'), ] global headers_set headers_set = [status, response_headers + server_headers] 84(*쎿썗쏚 -
84(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ def application(environ, start_response): start_response( '200, OK', [('Content-Type', 'text/plain')] )
return [b'Hello, World'] 84(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ -
썰쎐썽쎆BTZODBXBJU썢쎠࢝쎕썺썶 •ඇಉظIOͷͨΊͷڞ௨ίϯϙʔωϯτ͕PythonʹՃ •Pyhton 3.4 ʢ2014ʣ ΑΓ asyncio Ϟδϡʔϧ •Pyhton 3.5
ʢ2015ʣΑΓ async/await ͕ར༻Մೳʹͳͬͨ -
"4(*쎅ొ •ASGIʢAsynchronous Server Gateway Interfaceʣͷུ •2016ʹRead the Docs͕ొ - 1,2Λܦͯݱࡏ
3 Ͱ ࠷৽൛ͷ҆ఆ൛ •WSGIͷਫ਼ਆతʢεϐϦνϡΞϧʁʣͳޙܧऀʢa spiritual successorʣ -
"4(*쎅ొ •ASGIʢAsynchronous Server Gateway Interfaceʣͷུ •HTTP/1.1ɺWebsocketɺHTTP/2ʹରԠ •2016ʹRead the Docs͕ొ -
1,2Λܦͯݱࡏ 3 Ͱ ࠷৽൛ͷ҆ఆ൛ •WSGIͷਫ਼ਆతʢεϐϦνϡΞϧʁʣͳޙܧऀʢa spiritual successorʣ -
"4(*쎅ొ •ASGIʢAsynchronous Server Gateway Interfaceʣͷུ •HTTP/1.1ɺWebsocketɺHTTP/2ʹରԠ •2016ʹRead the Docs͕ొ -
1,2Λܦͯݱࡏ 3 Ͱ ࠷৽൛ͷ҆ఆ൛ •WSGIͷਫ਼ਆతʢεϐϦνϡΞϧʁʣͳޙܧऀʢa spiritual successorʣ •·ͩPEPʹͳ͍ͬͯͳ͍ -
"4(*쎅ొ •ASGIʢAsynchronous Server Gateway Interfaceʣͷུ •HTTP/1.1ɺWebsocketɺHTTP/2ʹରԠ •2016ʹRead the Docs͕ొ -
1,2Λܦͯݱࡏ 3 Ͱ ࠷৽൛ͷ҆ఆ൛ •WSGIͷਫ਼ਆతʢεϐϦνϡΞϧʁʣͳޙܧऀʢa spiritual successorʣ •·ͩPEPʹͳ͍ͬͯͳ͍ -
"4(*쎂썻썛썽3FBEUIF%PDT •ͦͷ΄͔ͷASGIͷ༷ •ASGI sub-specification - Life Span •ASGI Extention -
HTTP/2 Server Push •ASGI Extention - Websocket Denial Response https://asgi.readthedocs.io/en/latest/ -
"4(*쎂썻썛썽BTZODJPBTZODBXBJU •͜ͷޙͷίʔυͰ asyncio async/await͕ొ͠·͢ɻ •asyncio •ίϧʔνϯ 処理を明示的に中断し、再開できるタスクを利用して複数の処理を実行すること コルーチンを定義するには async def
を利用します •async/await 標準ライブラリに含まれ、コルーチンを活用して主にネットワーク関連の IO処理を非同期に行うためのモジュールです。 -
"4(*쎂썻썛썽BTZODJPBTZODBXBJU •͜ͷޙͷίʔυͰ asyncio async/await͕ొ͠·͢ɻ •asyncio •ίϧʔνϯ 処理を明示的に中断し、再開できるタスクを利用して複数の処理を実行すること コルーチンを定義するには async def
を利用します •async/await 標準ライブラリに含まれ、コルーチンを活用して主にネットワーク関連の IO処理を非同期に行うためのモジュールです。 -
"4(*쎂썻썛썽BTZODJPBTZODBXBJU •͜ͷޙͷίʔυͰ asyncio async/await͕ొ͠·͢ɻ •asyncio •ίϧʔνϯ •async/await async/await構文。asyncでコルーチンを定義し、awaitはコルーチンの 実行結果を取得するために使用します。 処理を明示的に中断し、再開できるタスクを利用して複数の処理を実行すること
コルーチンを定義するには async def を利用します 標準ライブラリに含まれ、コルーチンを活用して主にネットワーク関連の IO処理を非同期に行うためのモジュールです。 -
"4(*쎂썻썛썽BTZODJPBTZODBXBJU •͜ͷޙͷίʔυͰ asyncio async/await͕ొ͠·͢ɻ •asyncio •ίϧʔνϯ •async/await async/await構文。asyncでコルーチンを定義し、awaitはコルーチンの 実行結果を取得するために使用します。 処理を明示的に中断し、再開できるタスクを利用して複数の処理を実行すること
コルーチンを定義するには async def を利用します 標準ライブラリに含まれ、コルーチンを活用して主にネットワーク関連の IO処理を非同期に行うためのモジュールです。 -
"4(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ async def app(scope, receive, send): assert scope['type'] == 'http'
await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ [b'content-type', b'text/plain'], ] }) await send({ 'type': 'http.response.body', 'body': b'Hello, world!', }) IUUQTXXXVWJDPSOPSH -
"4(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ async def app(scope, receive, send): assert scope['type'] == 'http'
await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ [b'content-type', b'text/plain'], ] }) await send({ 'type': 'http.response.body', 'body': b'Hello, world!', }) IUUQTXXXVWJDPSOPSH -
"4(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ async def app(scope, receive, send): assert scope['type'] == 'http'
await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ [b'content-type', b'text/plain'], ] }) await send({ 'type': 'http.response.body', 'body': b'Hello, world!', }) scope -
"4(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ = { "type": "http", "http_version": "2.0", "asgi": { "spec_version":
"2.1", "version": “3.0", }, "method": "POST", "scheme": "https", "path": "/", "query_string": b"a=b", "headers": [(b"content-length", b"5")], "client": ("10.0.0.0", 1234), "server": ("127.0.0.1", 443), "root_path": ".", } scope IUUQTBTHJSFBEUIFEPDTJPFOMBUFTUTQFDTXXXIUNMIUUQDPOOFDUJPOTDPQF HTTP Connection Scope -
"4(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ async def app( , , send): assert scope['type'] ==
'http' await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ [b'content-type', b'text/plain'], ] }) await send({ 'type': 'http.response.body', 'body': b'Hello, world!', }) receive scope -
"4(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ = { "type": "http.request.body", "body": b'{"example": "Some JSON data"}',
"more_body": False } receive IUUQTBTHJSFBEUIFEPDTJPFOMBUFTUTQFDTXXXIUNMSFRVFTUSFDFJWFFWFOU Request - receive event -
"4(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ = { "type": "http.request.body", "body": b'{"example": "Some JSON data"}',
"more_body": False } receive IUUQTBTHJSFBEUIFEPDTJPFOMBUFTUTQFDTXXXIUNMSFRVFTUSFDFJWFFWFOU Request - receive event -
"4(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ = { "type": "http.request.body", "body": b'{"example": "Some JSON data"}',
"more_body": False } receive IUUQTBTHJSFBEUIFEPDTJPFOMBUFTUTQFDTXXXIUNMSFRVFTUSFDFJWFFWFOU Request - receive event -
"4(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ receive async def app(scope, receive, send): assert scope[“type”] ==
“http” await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ [b'content-type', b'text/plain'], ] }) await send({ 'type': 'http.response.body', 'body': b'Hello, world!', }) -
"4(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ async def app(scope, receive, send): assert scope[“type”] == “http”
await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ [b'content-type', b'text/plain'], ] }) await send({ 'type': 'http.response.body', 'body': b'Hello, world!', }) IUUQTBTHJSFBEUIFEPDTJPFOMBUFTUTQFDTXXXIUNMSFTQPOTFTUBSUTFOEFWFOU Response Start - send event -
"4(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ async def app(scope, receive, send): assert scope[“type”] == “http”
await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ [b'content-type', b'text/plain'], ] }) await send({ 'type': 'http.response.body', 'body': b'Hello, world!', }) IUUQTBTHJSFBEUIFEPDTJPFOMBUFTUTQFDTXXXIUNMSFTQPOTFTUBSUTFOEFWFOU Response Start - send event -
"4(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ async def app(scope, receive, send): assert scope[“type”] == “http”
await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ [b'content-type', b'text/plain'], ] }) await send({ 'type': 'http.response.body', 'body': b'Hello, world!', ‘more_body’: }) -
"4(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ async def app(scope, receive, send): assert scope[“type”] == “http”
await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ [b'content-type', b'text/plain'], ] }) await send({ 'type': 'http.response.body', 'body': b'Hello, world!', ‘more_body’: }) False -
"4(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅ྫ async def app(scope, receive, send): assert scope[“type”] == “http”
await send({ 'type': 'http.response.start', 'status': 200, 'headers': [ [b'content-type', b'text/plain'], ] }) await send({ 'type': 'http.response.body', 'body': b'Hello, world!', }) -
"4(*४ڌ쎅쎬쏡쏴쎻썗쏁쏱쏽쎅쎦썢썺썶썪썿 •Ҿ3ͭ •Scope ɿ ΫϥΠΞϯτ͔ΒͷϦΫΤετͷใؚ͕·Ε͍ͯΔʢWSGIͷenvironʹ ֘ʣ •recieveɿαʔό͔ΒͷϘσΟͷใΛड͚औΓͦ͏ͩ •sendɿԠ։࢝ͷsend ͱ Ԡຊମͷsend
IUUQTBTHJSFBEUIFEPDTJPFOMBUFTUTQFDTXXXIUNMIUUQDPOOFDUJPOTDPQF HTTP & WebSocket ASGI Message Format - HTTP -
•class HTTPParser: HTTPͷϦΫΤετΛύʔε͢Δ class HTTPParser: def __init__(self): self.part = "REQUEST"
self.headers = [] self.body_length = 0 def feed_line(self, line: bytes): if self.part == "REQUEST": self.method, self.path, self.version = line.split(b" ", 2) self.part = "HEADERS" elif self.part == "HEADERS" and line.strip() == b"": self.part = "BODY" elif self.part == "HEADERS": name, value = line.split(b":", 1) self.headers.append((name.strip(), value.strip())) if name.lower() == b"content-length": self.body_length = int(value) "4(*FDIP8FC쎿썗쏚 -
def create_scope(parser): return { "type": "http", "method": parser.method, "asgi": {
"spec_version": "2.1", "version": "3.0", }, "scheme": "http", "raw_path": parser.path, "path": parser.path.decode(), "headers": parser.headers, } •create_scope ؔɿscopeΛ࡞ΔʢASGIΞϓϦͷୈҰҾΛ࡞Δʣ "4(*FDIP8FC쎿썗쏚 -
def create_message(body, more_body): return { "type": "http.request", "body": body, "more_body":
more_body, } •create_message ؔɿreceive༻ͷϝοηʔδΛ࡞ΔʢASGIΞϓϦͷୈ̎Ҿʣ "4(*FDIP8FC쎿썗쏚 -
if __name__ == "__main__": if len(sys.argv) < 2: sys.exit('"module:callable"ͷܗͰASGIΞϓϦέʔγϣϯΛࢦఆ͍ͯͩ͘͠͞') host,
port = 'localhost', 8888 app_path = sys.argv[1] module, application = app_path.split(':') module = __import__(module) asgi_app = getattr(module, application) global app app = asgi_app asyncio.run(main(host, port)) •mainॲཧɾmainίϧʔνϯɿasyncio Ͱcreateserver "4(*FDIP8FC쎿썗쏚 -
async def main(host, port): server = await asyncio.start_server(asgi_http_parser_server, host, port)
await server.serve_forever() •mainॲཧɾmainίϧʔνϯɿasyncio Ͱcreateserver "4(*FDIP8FC쎿썗쏚 -
async def main(host, port): server = await asyncio.start_server(asgi_http_parser_server, host, port)
await server.serve_forever() •mainॲཧɾmainίϧʔνϯɿasyncio Ͱcreateserver "4(*FDIP8FC쎿썗쏚 -
async def main(host, port): server = await asyncio.start_server(asgi_http_parser_server, host, port)
await server.serve_forever() •mainॲཧɾmainίϧʔνϯɿasyncio Ͱcreateserver "4(*FDIP8FC쎿썗쏚 -
•asgi_http_parser_server ίϧʔνϯɿΞϓϦέʔγϣϯͱΓͱΓͷϝΠϯ async def asgi_http_parser_server(reader, writer): parser = HTTPParser() receive
= asyncio.Queue() read = 0 while not reader.at_eof(): if parser.part != "BODY": parser.feed_line(await reader.readline()) elif parser.body_length == 0: await receive.put(create_message(b"", False)) break else: body = await reader.read(100) read += len(body) await receive.put(create_message(body, read < parser.body_length)) if read >= parser.body_length: break "4(*FDIP8FC쎿썗쏚 -
•asgi_http_parser_server ίϧʔνϯɿΞϓϦέʔγϣϯͱΓͱΓͷϝΠϯ async def asgi_http_parser_server(reader, writer): parser = HTTPParser() receive
= asyncio.Queue() read = 0 while not reader.at_eof(): if parser.part != "BODY": parser.feed_line(await reader.readline()) elif parser.body_length == 0: await receive.put(create_message(b"", False)) break else: body = await reader.read(100) read += len(body) await receive.put(create_message(body, read < parser.body_length)) if read >= parser.body_length: break "4(*FDIP8FC쎿썗쏚 -
•asgi_http_parser_server ίϧʔνϯɿΞϓϦέʔγϣϯͱΓͱΓͷϝΠϯ async def asgi_http_parser_server(reader, writer): parser = HTTPParser() receive
= asyncio.Queue() read = 0 while not reader.at_eof(): if parser.part != "BODY": parser.feed_line(await reader.readline()) elif parser.body_length == 0: await receive.put(create_message(b"", False)) break else: body = await reader.read(100) read += len(body) await receive.put(create_message(body, read < parser.body_length)) if read >= parser.body_length: break "4(*FDIP8FC쎿썗쏚 -
•asgi_http_parser_server ίϧʔνϯɿΞϓϦέʔγϣϯͱΓͱΓͷϝΠϯ # httpͷϦΫΤετͷparser͔ΒscopeΛ࡞Δ scope = create_scope(parser) { "type": "http",
"http_version": "2.0", "asgi": { "spec_version": "2.1", "version": “3.0", }, "method": "POST", "scheme": "https", "path": "/", "query_string": b"a=b", "headers": [(b"content-length", b"5")], "client": ("10.0.0.0", 1234), "server": ("127.0.0.1", 443), "root_path": ".", } "4(*FDIP8FC쎿썗쏚 -
•asgi_http_parser_server ίϧʔνϯɿΞϓϦέʔγϣϯͱΓͱΓͷϝΠϯ while True: message = await send.get() if message["type"]
== "http.response.start": writer.write(b"HTTP/1.1 %d\r\n" % message["status"]) for header in message["headers"]: writer.write(b"%s: %s\r\n" % (header)) writer.write(b"\r\n") elif message["type"] == "http.response.body": if message.get("body") is not None: writer.write(message["body"]) writer.write(b"\r\n") if not message.get("more_body", False): break "4(*FDIP8FC쎿썗쏚 -
•asgi_http_parser_server ίϧʔνϯɿΞϓϦέʔγϣϯͱΓͱΓͷϝΠϯ while True: message = await send.get() if message["type"]
== "http.response.start": writer.write(b"HTTP/1.1 %d\r\n" % message["status"]) for header in message["headers"]: writer.write(b"%s: %s\r\n" % (header)) writer.write(b"\r\n") elif message["type"] == "http.response.body": if message.get("body") is not None: writer.write(message["body"]) writer.write(b"\r\n") if not message.get("more_body", False): break "4(*FDIP8FC쎿썗쏚 -
•asgi_http_parser_server ίϧʔνϯɿΞϓϦέʔγϣϯͱΓͱΓͷϝΠϯ while True: message = await send.get() if message["type"]
== "http.response.start": writer.write(b"HTTP/1.1 %d\r\n" % message["status"]) for header in message["headers"]: writer.write(b"%s: %s\r\n" % (header)) writer.write(b"\r\n") elif message[“type"] == "http.response.body": if message.get("body") is not None: writer.write(message["body"]) writer.write(b"\r\n") if not message.get("more_body", False): break "4(*FDIP8FC쎿썗쏚 -
•asgi_http_parser_server ίϧʔνϯɿΞϓϦέʔγϣϯͱΓͱΓͷϝΠϯ while True: message = await send.get() if message["type"]
== "http.response.start": writer.write(b"HTTP/1.1 %d\r\n" % message["status"]) for header in message["headers"]: writer.write(b"%s: %s\r\n" % (header)) writer.write(b"\r\n") elif message[“type"] == "http.response.body": if message.get("body") is not None: writer.write(message["body"]) writer.write(b"\r\n") if not message.get("more_body", False): break "4(*FDIP8FC쎿썗쏚 -
•asgi_http_parser_server ίϧʔνϯɿΞϓϦέʔγϣϯͱΓͱΓͷϝΠϯ while True: message = await send.get() if message["type"]
== "http.response.start": writer.write(b"HTTP/1.1 %d\r\n" % message["status"]) for header in message["headers"]: writer.write(b"%s: %s\r\n" % (header)) writer.write(b"\r\n") elif message[“type"] == "http.response.body": if message.get("body") is not None: writer.write(message["body"]) writer.write(b"\r\n") if not message.get("more_body", False): break "4(*FDIP8FC쎿썗쏚 -
•asgi_http_parser_server ίϧʔνϯɿΞϓϦέʔγϣϯͱΓͱΓͷϝΠϯ while True: message = await send.get() if message["type"]
== "http.response.start": writer.write(b"HTTP/1.1 %d\r\n" % message["status"]) for header in message["headers"]: writer.write(b"%s: %s\r\n" % (header)) writer.write(b"\r\n") elif message["type"] == "http.response.body": if message.get("body") is not None: writer.write(message["body"]) writer.write(b"\r\n") if not message.get("more_body", False): break "4(*FDIP8FC쎿썗쏚 -
•asgi_http_parser_server ίϧʔνϯɿΞϓϦέʔγϣϯͱΓͱΓͷϝΠϯ while True: message = await send.get() if message["type"]
== "http.response.start": writer.write(b"HTTP/1.1 %d\r\n" % message["status"]) for header in message["headers"]: writer.write(b"%s: %s\r\n" % (header)) writer.write(b"\r\n") elif message["type"] == "http.response.body": if message.get("body") is not None: writer.write(message["body"]) writer.write(b"\r\n") if not message.get("more_body", False): break "4(*FDIP8FC쎿썗쏚 -
•asgi_http_parser_server ίϧʔνϯɿΞϓϦέʔγϣϯͱΓͱΓͷϝΠϯ while True: message = await send.get() if message["type"]
== "http.response.start": writer.write(b"HTTP/1.1 %d\r\n" % message["status"]) for header in message["headers"]: writer.write(b"%s: %s\r\n" % (header)) writer.write(b"\r\n") elif message["type"] == "http.response.body": if message.get("body") is not None: writer.write(message["body"]) writer.write(b"\r\n") if not message.get("more_body", False): break "4(*FDIP8FC쎿썗쏚 -
•asgi_http_parser_server ίϧʔνϯɿΞϓϦέʔγϣϯͱΓͱΓͷϝΠϯ while True: message = await send.get() if message["type"]
== "http.response.start": writer.write(b"HTTP/1.1 %d\r\n" % message["status"]) for header in message["headers"]: writer.write(b"%s: %s\r\n" % (header)) writer.write(b"\r\n") elif message["type"] == "http.response.body": if message.get("body") is not None: writer.write(message["body"]) writer.write(b"\r\n") if not message.get("more_body", False): break "4(*FDIP8FC쎿썗쏚 -
"4(*)551쏫쏍쏅썗쏂 Server Application { 'asgi': {'spec_version': ‘2.1', 'version': '3.0'}, ...
'method': ‘GET', 'type': 'http' } -
"4(*)551쏫쏍쏅썗쏂 Server Application { 'asgi': {'spec_version': ‘2.1', 'version': '3.0'}, ...
'method': ‘GET', 'type': 'http' } { "type": "http.request", "body": b'', "more_body": False } -
"4(*)551쏫쏍쏅썗쏂 Server Application { 'asgi': {'spec_version': ‘2.1', 'version': '3.0'}, ...
'method': ‘GET', 'type': 'http' } { "type": "http.request", "body": b'', "more_body": False } { "type": "http.response.start", "status": 200, "headers": [(b"name", b"value")], } -
"4(*)551쏫쏍쏅썗쏂 Server Application { 'asgi': {'spec_version': ‘2.1', 'version': '3.0'}, ...
'method': ‘GET', 'type': 'http' } { "type": "http.request", "body": b'', "more_body": False } { "type": "http.response.start", "status": 200, "headers": [(b"name", b"value")], } { "type": "http.response.body", "body": b"Hello, World", "more_body": False, } -
"4(*)551쏫쏍쏅썗쏂 Server Application { 'asgi': {'spec_version': ‘2.1', 'version': '3.0'}, ...
'method': ‘GET', 'type': 'http' } { "type": "http.request", "body": b'', "more_body": False } { "type": "http.response.start", "status": 200, "headers": [(b"name", b"value")], } { "type": "http.response.body", "body": b"Hello, World", "more_body": False, } -
"4(*)551쏫쏍쏅썗쏂 Server Application { 'asgi': {'spec_version': ‘2.1', 'version': '3.0'}, ...
'method': ‘GET', 'type': 'http' } { "type": "http.request", "body": b'', "more_body": False } { "type": "http.response.start", "status": 200, "headers": [(b"name", b"value")], } { "type": "http.response.body", "body": b"Hello, World", "more_body": False, } {"type": "http.disconnect"} -
"4(*쎂썻썛썽3FBEUIF%PDT https://asgi.readthedocs.io/en/latest/ ASGI applications must run as async / await
compatible coroutines (i.e. asyncio-compatible) -
"4(*쎂썻썛썽3FBEUIF%PDT ASGI ΞϓϦέʔγϣϯ async / await ޓͷίϧʔνϯ (͢ͳ Θͪ asyncio
ޓ) ͱ࣮ͯ͠ߦ͞Εͳ͚ΕͳΓ·ͤΜ ɻ https://asgi.readthedocs.io/en/latest/ ASGI applications must run as async / await compatible coroutines (i.e. asyncio-compatible) -
"4(*쎂썻썛썽3FBEUIF%PDT ASGI ΞϓϦέʔγϣϯ async / await ޓͷίϧʔνϯ (͢ͳ Θͪ asyncio
ޓ) ͱ࣮ͯ͠ߦ͞Εͳ͚ΕͳΓ·ͤΜ ɻ https://asgi.readthedocs.io/en/latest/ ASGI applications must run as async / await compatible coroutines (i.e. asyncio-compatible) -
"4(*쎂썻썛썽3FBEUIF%PDT •ͦͷ΄͔ͷASGIͷ༷ •ASGI sub-specification - Life Span •ASGI Extention -
HTTP/2 Server Push •ASGI Extention - Websocket Denial Response https://asgi.readthedocs.io/en/latest/ -
"4(*8FC4PDLFU Server Application { 'asgi': {'spec_version': ‘2.1', 'version': '3.0'}, ...
'method': ‘GET', 'type': 'websocket' } { “type": "websocket.connect" } { “type": “websocket.accept" } { “type": “websocket.close” “code": 1000 } { “type": “websocket.send” “text": ”Hello, World” } { “type": “websocket.disconnect" } IUUQTBTHJSFBEUIFEPDTJPFOMBUFTUTQFDTXXXIUNMXFCTPDLFU -
"4(*-JGF4BQBO "scope" : { "type": "lifespan", "asgi": {"spec_version": "2.0", "version":
"3.0"}, } --- SERVER {"type": "lifespan.startup"} {"type": "lifespan.shutdown"} --- APPLICATION {"type": "lifespan.startup.complete"} {"type": "lifespan.shutdown.complete"} -
"4(*-JGF4BQBO async def app(scope, receive, send): if scope['type'] == 'lifespan':
while True: message = await receive() if message['type'] == 'lifespan.startup': ... # Do some startup here! await send({'type': 'lifespan.startup.complete'}) elif message['type'] == 'lifespan.shutdown': ... # Do some shutdown here! await send({'type': 'lifespan.shutdown.complete'}) return else: pass # Handle other types IUUQTBTHJSFBEUIFEPDTJPFOMBUFTUTQFDTMJGFTQBOIUNM -
"4(*TVCTQFDJpDBUJPO-JGF4BQBO async def app(scope, receive, send): if scope['type'] == 'lifespan':
while True: message = await receive() if message['type'] == 'lifespan.startup': ... # Do some startup here! await send({'type': 'lifespan.startup.complete'}) elif message['type'] == 'lifespan.shutdown': ... # Do some shutdown here! await send({'type': 'lifespan.shutdown.complete'}) return else: pass # Handle other types IUUQTBTHJSFBEUIFEPDTJPFOMBUFTUTQFDTMJGFTQBOIUNM -
"4(*&YUFOTJPOT)5514FSWFS1VTI "scope": { ..., "extensions": {"http.response.push": {}}, } --- {
"type": "http.response.push", "path": "/path", "headers": [(b"name", b"value")], } Server Application IUUQTBTHJSFBEUIFEPDTJPFOMBUFTUFYUFOTJPOTIUNMIUUQTFSWFSQVTI -
"4(*'SBNFXPSLT$PNQBSFE Framework HTTP WebSocket Server Push WebSocket HTTP response
Quart ✓ ✓ ✓ ✓ FastAPI ✓ ✓ ❌ ❌ Responder ✓ ✓ ❌ ❌ Starlette ✓ ✓ ❌ ❌ Django ✓ ✓ ❌ ❌ -
"4(*4FSWFST $PNQBSFE Framework HTTP WebSockets Server Push WebSocket
HTTP response Hypercorn 1 ✓ 2 ✓ 1 ✓ 2 ✓ ✓ ✓ Uvicorn 1 ✓ 2 ❌ 1 ✓ 2 ❌ ❌ ❌ Daphne 1 ✓ 2 ✓ 1 ✓ 2 ❌ ❌ ❌ Mangum 1 ✓ 2 ❌ 1✓ 2 ❌ ❌ ❌ -
84(*썿"4(*쎕썿쎘 •WSGI ͱ ASGI ͷతಉ͡ •WSGI ͱ ASGI ͷ࣮ࣅ͍ͯΔʢͨͩasync/awitͰܾఆతʹҧ͏ʣ •WSGI
ͱ ASGI ͷঢ়گࣅ͍ͯΔ •ASGIPEPʹͳͬͯΑ͍ͷͰ -
"4(*1&1쎏쎅ಓ [email protected] ϝʔϦϯάϦετ 20201݄28 Subject:Is the deployment standard for WSGI
ready? *EPOUUIJOLUIJTTPSUPGUIJOHTIPVMECFB1&1 -PPLBU"4(*BOEIPXUIBUJTOUB1&1BOETUJMMNBOBHFTUPFYJTU 4JODFUIJTJTO`UBMBOHVBHFSFMBUFEPSQBDLBHFSFMBUFEUIJOH*EPOUUIJOLJUSFBMMZOFFETUPHPUISPVHIUIF1&1 QSPDFTT -
"4(*1&1쎏쎅ಓ [email protected] ϝʔϦϯάϦετ 20201݄28 Subject:Is the deployment standard for WSGI
ready? *EPOUUIJOLUIJTTPSUPGUIJOHTIPVMECFB1&1 -PPLBU"4(*BOEIPXUIBUJTOUB1&1BOETUJMMNBOBHFTUPFYJTU 4JODFUIJTJTO`UBMBOHVBHFSFMBUFEPSQBDLBHFSFMBUFEUIJOH*EPOUUIJOLJUSFBMMZOFFETUPHPUISPVHIUIF1&1 QSPDFTT 4JODF84(*BOE QSPCBCMZTPPO "4(*BSFWFSZDPNNPO"1*TUBOEBSETJO1ZUIPOMBOE UIFZEFTFSWFUP HPJOUPUIF1&1JOEFYBTXFMM *.0 -
"4(*1&1쎏쎅ಓ It's worth noting that I was discouraged from making
ASGI a PEP by several Python core developers, which is why I have not been pursuing that process any further. I'm not sure I share this view, so I may come back to it in the future, but there's a reason it's not in the process right now. ಛච͖͢ɺࢲ͕ASGIΛPEPʹ͢Δ͜ͱΛԿਓ͔ͷPythonίΞ։ൃऀ͔Βམ͞Εͯ ͍ͨ͜ͱͰɺͦΕҎ্ͦͷϓϩηεΛٻͯ͜͠ͳ͔ͬͨ͜ͱͰ͢ɻ ࢲ͜ͷݟղʹڞײ͍ͯ͠ΔΘ͚Ͱͳ͍ͷͰɺকདྷతʹͬͯ͘Δ͔͠Ε·ͤΜ ͕ɺࠓͦͷϓϩηεʹೖ͍ͬͯͳ͍ͷʹཧ༝͕͋Γ·͢ɻ [email protected] ϝʔϦϯάϦετ 20201݄28 -
•Encode OSS ͱ͍͏ΠΪϦεͷձࣾ - ༷ʑͳϓϩμΫτͷ։ൃݩ •uvicorn •starletteʢFastAPIResponder ͷϕʔεʹͳ͍ͬͯΔ࠷খASGI FWʣ •HTTPX
•Django REST framework •ASGIهࣄ͋Γ - Hello, ASGI ͳͲͳͲ "4(*쎅쎡্썣쎡 -
ࢀߟࢿྉ •An ASGI Server from scratch / Philip Jones IUUQTXXXZPVUVCFDPNXBUDI
W(QRY6*8KJX •An introduction to ASGI, Asynchronous Server Gateway Interface / Philip Jones IUUQTXXXZPVUVCFDPNXBUDI WUH$,2R986 •Hello, ASGI IUUQTXXXFODPEFJPBSUJDMFTIFMMPBTHJ •Introduction to ASGI: Emergence of an Async Python Web Ecosystem IUUQTqPSJNPOEEFWCMPHBSUJDMFTJOUSPEVDUJPOUPBTHJBTZODQZUIPOXFC