27
loading...
This website collects cookies to deliver better user experience
async/await
to python 3.5, things started to change.var q := new queue
coroutine produce
loop
while q is not full
create some new items
add the items to q
yield to consume
coroutine consume
loop
while q is not empty
remove some items from q
use the items
yield to produce
call produce
Generators, also known as semicoroutines (not discussed here)
asyncio python example.
import asyncio
import random
async def fetch():
print("Started..")
await asyncio.sleep(2) #Fetching delay
print("Done!")
async def receive():
for i in range(10):
print(i)
await asyncio.sleep(0.225) # Receiving delay
async def main():
task1 = asyncio.create_task(fetch()) #returns a future
task2 = asyncio.create_task(receive())
await task1 # wait for the promise to return something
print("task one awaited")
await task2
asyncio.run(main()) # event loop beginning
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'websocket_app.settings')
application = get_asgi_application()
from django.core.asgi import get_asgi_application
from websocket_app.websocket import websocket_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'websocket_app.settings')
django_application = get_asgi_application()
async def application(scope, receive, send):
if scope['type'] == 'http':
await django_application(scope, receive, send)
elif scope['type'] == 'websocket':
await websocket_application(scope, receive, send)
else:
raise NotImplementedError(f"Unknown scope type {scope['type']}")
# websocket.py
async def websocket_applciation(scope, receive, send):
pass
# websocket.py
async def websocket_applciation(scope, receive, send):
while True:
event = await receive()
if event['type'] == 'websocket.connect':
await send({
'type': 'websocket.accept'
})
if event['type'] == 'websocket.disconnect':
break
if event['type'] == 'websocket.receive':
if event['text'] == 'ping':
await send({
'type': 'websocket.send',
'text': 'pong!'
})
pip install uvicorn
uvicorn websocket_app.asgi:application
> ws = new WebSocket('ws://localhost:8000/')
WebSocket {url: "ws://localhost:8000/", readyState: 0, bufferedAmount: 0, onopen: null, onerror: null, …}
> ws.onmessage = event => console.log(event.data)
event => console.log(event.data)
> ws.send("ping")
undefined
pong!