emmett-framework / emmett

The web framework for inventors
BSD 3-Clause "New" or "Revised" License
1.06k stars 71 forks source link

About asynchronous mode #259

Closed josejachuf closed 4 years ago

josejachuf commented 4 years ago

I am trying to see the differences in behavior using the asynchronous mode of the functions, but I don't succeed

given the following function:

@routes.route("/slow/<str:browser>")
async def slow(browser):
    start_time = time.time()
    current_time = datetime.datetime.now()
    print(browser, current_time.strftime('%H:%M:%S'))
    time.sleep(5)
    elapsed_time = time.time() - start_time
    return "%s: %s. ---> Elapsed time: %0.10f seconds." % (browser,
                                                               datetime.datetime.now().strftime('%H:%M:%S'),
                                                               elapsed_time)

refreshing the three pages, open in three different browsers I get:

async mode (async def slow(browser):): chrome 09:05:42 INFO: 127.0.0.1:39194 - "GET /slow/chrome HTTP/1.1" 200 OK firefox 09:05:47 brave 09:05:52 INFO: 127.0.0.1:39198 - "GET /slow/firefox HTTP/1.1" 200 OK INFO: 127.0.0.1:39200 - "GET /slow/brave HTTP/1.1" 200 OK

sync mode (def slow(browser):): chrome 09:08:00 INFO: 127.0.0.1:39214 - "GET /slow/chrome HTTP/1.1" 200 OK brave 09:08:05 firefox 09:08:10 INFO: 127.0.0.1:39220 - "GET /slow/brave HTTP/1.1" 200 OK INFO: 127.0.0.1:39218 - "GET /slow/firefox HTTP/1.1" 200 OK

tried many times and always the same results, 5 seconds always pass All this using the development server, maybe this can be seen in production.

I expected something like that in async mode:

chrome 09:08:00.xx brave 09:08:00.xx firefox 09:08:00.xx INFO: 127.0.0.1:39214 - "GET /slow/chrome HTTP/1.1" 200 OK INFO: 127.0.0.1:39220 - "GET /slow/brave HTTP/1.1" 200 OK INFO: 127.0.0.1:39218 - "GET /slow/firefox HTTP/1.1" 200 OK

Is my test function not correct?

gi0baro commented 4 years ago

@josejachuf I'm not sure what you trying to test here. Both your tests uses synchronous code, doesn't really matter if the route is a function or a coroutine function. The code inside it is the same, so you will get same results.

josejachuf commented 4 years ago

Hi @gi0baro Ready, now I understood.

I changed

time.sleep(5)

to

await asyncio.sleep(5)

And I got what I expected:

chrome 08:43:16 firefox 08:43:17 brave 08:43:18 INFO: 127.0.0.1:33662 - "GET /slow/chrome HTTP/1.1" 200 OK INFO: 127.0.0.1:33666 - "GET /slow/firefox HTTP/1.1" 200 OK INFO: 127.0.0.1:33668 - "GET /slow/brave HTTP/1.1" 200 OK

Thanks