I am in trying to write a snippet to study Python asyncio. The basic idea is:
use a "simple" web server (aiohttp) to present some data to user
the data return to user will change promptly
here is the code:
import asyncio
import random
from aiohttp import web
userfeed = [] # the data suppose to return to the user via web browsers
async def data_updater(): #to simulate data change promptly
while True:
await asyncio.sleep(3)
userfeed = [x for x in range(random.randint(1, 20))]
print('user date updated: ', userfeed)
async def web_handle(request):
text = str(userfeed)
#print('in handler:', text) # why text is empty?
return web.Response(text=text)
async def init(loop):
app = web.Application(loop=loop)
app.router.add_route('GET', '/', web_handle)
srv = await loop.create_server(app.make_handler(), '127.0.0.1', 8000)
print('Server started @ http://127.0.0.1:8000...')
return srv
loop = asyncio.get_event_loop()
asyncio.ensure_future(data_updater())
asyncio.ensure_future(init(loop))
loop.run_forever()
the problem is, the code is running (python 3.5), but the userfeed
is always empty in browsers and also in web_handler()
:-(
- why
userfeed
is not been updated? - regarding this
timely date update
function, because the update mechanism might be more complex later say async IO wait may be involved, is there a better way instead of usingwhile True: await asyncio.sleep(3)
indata_updater()
to get "more roughly precise" timer?