/
hello_world.py
47 lines (33 loc) · 1.12 KB
/
hello_world.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import os
import asyncio
import aiohttp
import api_hour
def handler(request):
return {'hello': 'world'}
def say_hello(request):
return 'Hello, {}!'.format(request.matchdict['name'])
def main():
loop = asyncio.get_event_loop()
server = api_hour.RESTServer(hostname='127.0.0.1', loop=loop)
server.add_url('GET', '/hello-world', handler)
server.add_url(['GET', 'POST'], '/hello/{name}', say_hello)
srv = loop.run_until_complete(loop.create_server(
server.make_handler, '127.0.0.1', 8080))
@asyncio.coroutine
def query():
resp = yield from aiohttp.request(
'GET', 'http://127.0.0.1:8080/hello-world',
loop=loop)
json_data = yield from resp.json()
print(json_data)
name = os.environ.get('USER', 'John')
resp = yield from aiohttp.request(
'GET', 'http://127.0.0.1:8080/hello/{}'.format(name))
json_data = yield from resp.json()
print(json_data)
loop.run_until_complete(query())
srv.close()
loop.run_until_complete(srv.wait_closed())
loop.close()
if __name__ == '__main__':
main()