當前位置: 首頁>>代碼示例>>Python>>正文


Python aiohttp.web方法代碼示例

本文整理匯總了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() 
開發者ID:mrphlip,項目名稱:lrrbot,代碼行數:23,代碼來源:eventserver.py

示例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))) 
開發者ID:mushorg,項目名稱:snare,代碼行數:26,代碼來源:server.py

示例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) 
開發者ID:lbryio,項目名稱:lbry-sdk,代碼行數:18,代碼來源:test_streaming.py

示例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() 
開發者ID:lbryio,項目名稱:lbry-sdk,代碼行數:26,代碼來源:test_streaming.py

示例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() 
開發者ID:acgx,項目名稱:ooi3,代碼行數:25,代碼來源:service.py

示例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() 
開發者ID:acgx,項目名稱:ooi3,代碼行數:25,代碼來源:service.py

示例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 
開發者ID:Hardtack,項目名稱:Flask-aiohttp,代碼行數:18,代碼來源:__init__.py

示例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() 
開發者ID:saqura,項目名稱:xmppwb,代碼行數:26,代碼來源:bridge.py

示例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 
開發者ID:aio-libs,項目名稱:aiohttp-devtools,代碼行數:19,代碼來源:test_runserver_main.py

示例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) 
開發者ID:aio-libs,項目名稱:aiohttp-devtools,代碼行數:20,代碼來源:test_runserver_main.py

示例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 
開發者ID:aio-libs,項目名稱:aiobotocore,代碼行數:14,代碼來源:mock_server.py

示例12: ok

# 需要導入模塊: import aiohttp [as 別名]
# 或者: from aiohttp import web [as 別名]
def ok(request):
        return aiohttp.web.Response() 
開發者ID:aio-libs,項目名稱:aiobotocore,代碼行數:4,代碼來源:mock_server.py

示例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 [] 
開發者ID:mrphlip,項目名稱:lrrbot,代碼行數:28,代碼來源:eventserver.py

示例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 
開發者ID:mrphlip,項目名稱:lrrbot,代碼行數:34,代碼來源:eventserver.py

示例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', '*')}) 
開發者ID:mrphlip,項目名稱:lrrbot,代碼行數:6,代碼來源:eventserver.py


注:本文中的aiohttp.web方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。