本文整理汇总了Python中aiohttp.web方法的典型用法代码示例。如果您正苦于以下问题:Python aiohttp.web方法的具体用法?Python aiohttp.web怎么用?Python aiohttp.web使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类aiohttp
的用法示例。
在下文中一共展示了aiohttp.web方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import web [as 别名]
def main(loop):
global server, srv, app, handler
try:
os.unlink(config['eventsocket'])
except FileNotFoundError:
pass
server = Server()
await server.start(config['eventsocket'], config['event_port'])
app = aiohttp.web.Application()
app.router.add_route('GET', '/api/v2/events', server.negotiate)
app.router.add_route('OPTIONS', '/api/v2/events', server.cors_preflight)
app.on_shutdown.append(server.on_shutdown)
handler = app.make_handler()
srv = await loop.create_server(handler, 'localhost', 8080)
if sys.platform == "win32":
# On Windows Ctrl+C doesn't interrupt `select()`.
def windows_is_butts():
asyncio.get_event_loop().call_later(5, windows_is_butts)
windows_is_butts()
示例2: start
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import web [as 别名]
def start(self):
app = web.Application()
app.add_routes([web.route('*', '/{tail:.*}', self.handle_request)])
aiohttp_jinja2.setup(
app, loader=jinja2.FileSystemLoader(self.dir)
)
middleware = SnareMiddleware(
error_404=self.meta['/status_404'].get('hash'),
headers=self.meta['/status_404'].get('headers', []),
server_header=self.run_args.server_header
)
middleware.setup_middlewares(app)
self.runner = web.AppRunner(app)
await self.runner.setup()
site = web.TCPSite(
self.runner,
self.run_args.host_ip,
self.run_args.port)
await site.start()
names = sorted(str(s.name) for s in self.runner.sites)
print("======== Running on {} ========\n"
"(Press CTRL+C to quit)".format(', '.join(names)))
示例3: _setup_stream
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import web [as 别名]
def _setup_stream(self, data: bytes, save_blobs: bool = True, save_files: bool = False, file_size=0):
self.daemon.conf.save_blobs = save_blobs
self.daemon.conf.save_files = save_files
self.data = data
await self.stream_create('foo', '0.01', data=self.data, file_size=file_size)
if save_blobs:
self.assertGreater(len(os.listdir(self.daemon.blob_manager.blob_dir)), 1)
await (await self.daemon.jsonrpc_file_list())['items'][0].fully_reflected.wait()
await self.daemon.jsonrpc_file_delete(delete_from_download_dir=True, claim_name='foo')
self.assertEqual(0, len(os.listdir(self.daemon.blob_manager.blob_dir)))
# await self._restart_stream_manager()
await self.daemon.streaming_runner.setup()
site = aiohttp.web.TCPSite(self.daemon.streaming_runner, self.daemon.conf.streaming_host,
self.daemon.conf.streaming_port)
await site.start()
self.assertItemCount(await self.daemon.jsonrpc_file_list(), 0)
示例4: test_range_requests_with_blob_lru_cache
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import web [as 别名]
def test_range_requests_with_blob_lru_cache(self):
self.data = b'hi'
self.daemon.conf.save_blobs = False
self.daemon.conf.save_files = False
await self.stream_create('foo', '0.01', data=self.data, file_size=0)
await (await self.daemon.jsonrpc_file_list())['items'][0].fully_reflected.wait()
await self.daemon.jsonrpc_file_delete(delete_from_download_dir=True, claim_name='foo')
self.assertEqual(0, len(os.listdir(self.daemon.blob_manager.blob_dir)))
await self.daemon.streaming_runner.setup()
site = aiohttp.web.TCPSite(self.daemon.streaming_runner, self.daemon.conf.streaming_host,
self.daemon.conf.streaming_port)
await site.start()
self.assertItemCount(await self.daemon.jsonrpc_file_list(), 0)
await self._request_stream()
self.assertItemCount(await self.daemon.jsonrpc_file_list(), 1)
self.server.stop_server()
# running with cache size 0 gets through without errors without
# this since the server doesn't stop immediately
await asyncio.sleep(1, loop=self.loop)
await self._request_stream()
示例5: get_osapi
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import web [as 别名]
def get_osapi(self, request):
"""获取用户的内嵌游戏网页地址,返回一个JSON格式的字典。
结果中`status`键值为1时获取成功,`osapi_url`键值为内嵌网页地址;`status`为0时获取失败,`message`键值提供了错误信息。
:param request: aiohttp.web.Request
:return: aiohttp.web.Response or aiohttp.web.HTTPBadRequest
"""
data = yield from request.post()
login_id = data.get('login_id', None)
password = data.get('password', None)
if login_id and password:
headers = aiohttp.MultiDict({'Content-Type': 'application/json'})
kancolle = KancolleAuth(login_id, password)
try:
osapi_url = yield from kancolle.get_osapi()
result = {'status': 1,
'osapi_url': osapi_url}
except OOIAuthException as e:
result = {'status': 0,
'message': e.message}
return aiohttp.web.Response(body=json.dumps(result).encode(), headers=headers)
else:
return aiohttp.web.HTTPBadRequest()
示例6: get_flash
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import web [as 别名]
def get_flash(self, request):
"""获取用户的游戏FLASH地址,返回一个JSON格式的字典。
结果中`status`键值为1时获取成功,`flash_url`键值为游戏FLASH地址;`status`为0时获取失败,`message`键值提供了错误信息。
:param request: aiohttp.web.Request
:return: aiohttp.web.Response or aiohttp.web.HTTPBadRequest
"""
data = yield from request.post()
login_id = data.get('login_id', None)
password = data.get('password', None)
if login_id and password:
headers = aiohttp.MultiDict({'Content-Type': 'application/json'})
kancolle = KancolleAuth(login_id, password)
try:
entry_url = yield from kancolle.get_entry()
result = {'status': 1,
'flash_url': entry_url}
except OOIAuthException as e:
result = {'status': 0,
'message': e.message}
return aiohttp.web.Response(body=json.dumps(result).encode(), headers=headers)
else:
return aiohttp.web.HTTPBadRequest()
示例7: create_aiohttp_app
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import web [as 别名]
def create_aiohttp_app(self, app: flask.Flask) -> aiohttp.web.Application:
"""Create aiohttp web application from Flask application
:param app: Flask application
:returns: aiohttp web application
"""
# aiohttp web application instance
aio_app = aiohttp.web.Application()
# WSGI handler for aiohttp
wsgi_handler = self.handler_factory(app)
# aiohttp's router should accept any possible HTTP method of request.
aio_app.router.add_route('*', r'/{path:.*}', wsgi_handler)
return aio_app
示例8: handle_incoming_webhook
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import web [as 别名]
def handle_incoming_webhook(self, request):
"""This coroutine handles incoming webhooks: It receives incoming
webhooks and relays the messages to XMPP."""
if request.content_type == 'application/json':
payload = await request.json()
# print(payload)
else:
# TODO: Handle other content types
payload = await request.post()
# Disgard empty messages
if payload['text'] == "":
return aiohttp.web.Response()
token = payload['token']
logging.debug("--> Handling incoming request from token "
"'{}'...".format(token))
username = payload['user_name']
msg = payload['text']
for bridge in self.bridges:
bridge.handle_incoming_webhook(token, username, msg)
return aiohttp.web.Response()
示例9: test_start_runserver_app_instance
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import web [as 别名]
def test_start_runserver_app_instance(tmpworkdir, loop):
mktree(tmpworkdir, {
'app.py': """\
from aiohttp import web
async def hello(request):
return web.Response(text='<h1>hello world</h1>', content_type='text/html')
app = web.Application()
app.router.add_get('/', hello)
"""
})
aux_app, aux_port, _, _ = runserver(app_path='app.py', host='foobar.com')
assert isinstance(aux_app, aiohttp.web.Application)
assert aux_port == 8001
assert len(aux_app.on_startup) == 2
assert len(aux_app.on_shutdown) == 2
示例10: test_start_main_app_app_instance
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import web [as 别名]
def test_start_main_app_app_instance(tmpworkdir, loop, mocker):
mktree(tmpworkdir, {
'app.py': """\
from aiohttp import web
async def hello(request):
return web.Response(text='<h1>hello world</h1>', content_type='text/html')
app = web.Application()
app.router.add_get('/', hello)
"""
})
mock_modify_main_app = mocker.patch('aiohttp_devtools.runserver.serve.modify_main_app')
config = Config(app_path='app.py')
await start_main_app(config, config.import_app_factory(), loop)
mock_modify_main_app.assert_called_with(mock.ANY, config)
示例11: _run
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import web [as 别名]
def _run(self):
asyncio.set_event_loop(asyncio.new_event_loop())
app = aiohttp.web.Application()
app.router.add_route('*', '/ok', self.ok)
app.router.add_route('*', '/{anything:.*}', self.stream_handler)
try:
aiohttp.web.run_app(app, host=host, port=self._port,
handle_signals=False)
except BaseException:
pytest.fail('unable to start and connect to aiohttp server')
raise
示例12: ok
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import web [as 别名]
def ok(request):
return aiohttp.web.Response()
示例13: get_last_events
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import web [as 别名]
def get_last_events(self, request):
try:
last_event_id = int(request.headers.get('Last-Event-Id', request.query.get('last-event-id')))
except (ValueError, TypeError):
last_event_id = None
interval = request.query.get('interval')
if interval is not None and last_event_id is None:
last_event_id = 0
if last_event_id is not None:
events = self.metadata.tables['events']
query = sqlalchemy.select([
events.c.id, events.c.event, events.c.data, events.c.time
])
query = query.where(events.c.id > last_event_id)
if interval is not None:
query = query.where(events.c.time > sqlalchemy.func.current_timestamp() - sqlalchemy.cast(interval, sqlalchemy.Interval))
query = query.order_by(events.c.id)
try:
with self.engine.begin() as conn:
return [
{'id': id, 'event': event, 'data': dict(data, time=time.isoformat())}
for id, event, data, time in conn.execute(query)
]
except sqlalchemy.exc.DataError as e:
raise aiohttp.web.HTTPBadRequest from e
return []
示例14: event_stream
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import web [as 别名]
def event_stream(self, request):
queue = asyncio.Queue()
for event in self.get_last_events(request):
await queue.put(event)
self.queues.append(queue)
response = aiohttp.web.StreamResponse()
response.enable_chunked_encoding()
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Content-Type'] = 'text/event-stream; charset=utf-8'
response.headers['Vary'] = "Accept"
await response.prepare(request)
while True:
try:
try:
event = await asyncio.wait_for(queue.get(), 15)
if event['event'] is Poison:
break
await response.write(b"id:%d\n" % event['id'])
await response.write(b"event:%s\n" % event['event'].encode('utf-8'))
await response.write(b"data:%s\n" % json.dumps(event['data']).encode('utf-8'))
await response.write(b"\n")
queue.task_done()
except asyncio.TimeoutError:
await response.write(b":keep-alive\n\n")
except IOError:
break
self.queues.remove(queue)
return response
示例15: json
# 需要导入模块: import aiohttp [as 别名]
# 或者: from aiohttp import web [as 别名]
def json(self, request):
return aiohttp.web.json_response({
'events': self.get_last_events(request),
}, headers={"Vary": "Accept", 'Access-Control-Allow-Origin': request.headers.get('Origin', '*')})