Issue
I often see code like along the lines of the following (which is similar to examples in aiohttp docs).
@asyncio.coroutine
def init(loop):
srv = yield from loop.create_server(web.Application().make_handler(), '0.0.0.0', 8080)
return srv
Are there any advantages/disadvantages to doing it in 1 line as below, presuming you don't want to do anything to the srv
object in between getting it and returning it?
@asyncio.coroutine
def init(loop):
return (yield from loop.create_server(web.Application().make_handler(), '0.0.0.0', 8080))
Solution
The example in the aiohttp docs you seem to have adapted has important additional code:
@asyncio.coroutine
def init(loop):
app = web.Application(loop=loop)
app.router.add_route('GET', '/{name}', handle)
srv = yield from loop.create_server(app.make_handler(),
'127.0.0.1', 8080)
print("Server started at http://127.0.0.1:8080") # THIS PART
return srv
The function needs to do something between the yield from
and the return
, so it needs to save the return value to a variable. If there is no need to do something between the yield and the return, it is indeed equivalent to do
return (yield from whatever)
instead of
srv = yield from whatever
return srv
and you can see that done in other examples on the same page:
@asyncio.coroutine
def fetch_page(url):
response = yield from aiohttp.request('GET', url)
assert response.status == 200
return (yield from response.read())
For an example as simple as your code, I don't think you even need the yield from
. You should be able to do
@asyncio.coroutine
def init(loop):
return loop.create_server(web.Application().make_handler(), '0.0.0.0', 8080)
though I'm not familiar with asyncio, so I'm not entirely sure that that won't interact weirdly with the asyncio.coroutine
decorator.
Answered By - user2357112 supports Monica
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.