Python源码示例:aiohttp.web()

示例1
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
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
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
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
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
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
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
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
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
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
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
def ok(request):
        return aiohttp.web.Response() 
示例13
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
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
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', '*')}) 
示例16
def cors_preflight(self, request):
		return aiohttp.web.Response(headers={
			'Access-Control-Allow-Origin': request.headers.get('Origin', '*'),
		}) 
示例17
def api(config: Config) -> AsyncIterator[ApiConfig]:
    app = await create_app(config)
    runner = aiohttp.web.AppRunner(app)
    await runner.setup()
    api_config = ApiConfig(host="0.0.0.0", port=8080)
    site = aiohttp.web.TCPSite(runner, api_config.host, api_config.port)
    await site.start()
    yield api_config
    await runner.cleanup() 
示例18
def test_endpoint_index(client):
    r = await client.get("/")

    assert r.history[0].url.path == "/"
    assert r.history[0].status == 302

    assert r.status == 200
    assert r.url.path == "/web" 
示例19
def test_endpoint_slack(client):
    r = await client.get("/web/slack")
    assert r.status == 200 
示例20
def test_endpoint_slack_invite(client, data, expected):
    r = await client.post(path="/web/slack", data=data)
    html = await r.text()

    assert r.status == 200
    assert expected["html"] in html

    async with client.app["pg"].acquire() as conn:
        rows = await conn.fetch(select([domains.c.blocked, domains.c.domain]))

    if "domain" in expected:
        assert len(rows) == 1
        assert rows[0]["domain"] == expected["domain"]
    else:
        assert len(rows) == 0 
示例21
def test_invite_banned_email_domain(client, data, expected):
    async with client.app["pg"].acquire() as conn:
        await conn.fetchrow(
            pg_insert(domains)
            .values(domain="urhen.com", blocked=True, source=Source.MANUAL)
            .on_conflict_do_nothing(index_elements=[domains.c.domain])
        )
    r = await client.post(path="/web/slack", data=data)
    html = await r.text()

    assert r.status == 200
    assert expected in html
    client.app["subapps"]["website"][  # pylint: disable=protected-access
        "slack_client"
    ]._request.assert_not_awaited() 
示例22
def test_disable_invites(client, disable_invites):
    r = await client.get(path="/web/slack")
    html = await r.text()

    assert r.status == 200
    assert "Invites are disabled at this time" in html

    r = await client.post(path="/web/slack", data={"email": "foo@example.com", "agree_tos": True})
    html = await r.text()

    assert r.status == 200
    assert "Invites are disabled at this time" in html
    assert not client.app["slack_client"]._request.called 
示例23
def main(argv=None):
    args = parse_args(argv)

    logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO)

    config_str = ", ".join(f"{k}={v}" for k, v in sorted(vars(args).items()))
    logger.info(f"Kubernetes Web View v{__version__} started with {config_str}")

    if args.clusters:
        cluster_discoverer = StaticClusterDiscoverer(args.clusters)
    elif args.cluster_registry_url:
        cluster_discoverer = ClusterRegistryDiscoverer(
            args.cluster_registry_url, args.cluster_registry_oauth2_bearer_token_path
        )
    elif args.kubeconfig_path:
        cluster_discoverer = KubeconfigDiscoverer(
            args.kubeconfig_path, args.kubeconfig_contexts
        )
    else:
        # try to use in-cluster config
        try:
            cluster_discoverer = ServiceAccountClusterDiscoverer()
        except ServiceAccountNotFound:
            # fallback to default kubeconfig
            cluster_discoverer = KubeconfigDiscoverer(
                args.kubeconfig_path, args.kubeconfig_contexts
            )
    cluster_manager = ClusterManager(
        cluster_discoverer,
        args.cluster_label_selector,
        args.cluster_auth_token_path,
        args.preferred_api_versions,
    )
    app = get_app(cluster_manager, args)
    aiohttp.web.run_app(app, port=args.port, handle_signals=False) 
示例24
def handle_request(self, request):
        self.logger.info('Request path: {0}'.format(request.path_qs))
        data = self.tanner_handler.create_data(request, 200)
        if request.method == 'POST':
            post_data = await request.post()
            self.logger.info('POST data:')
            for key, val in post_data.items():
                self.logger.info('\t- {0}: {1}'.format(key, val))
            data['post_data'] = dict(post_data)

        # Submit the event to the TANNER service
        event_result = await self.tanner_handler.submit_data(data)

        # Log the event to slurp service if enabled
        if self.run_args.slurp_enabled:
            await self.submit_slurp(request.path_qs)

        content, headers, status_code = await self.tanner_handler.parse_tanner_response(
            request.path_qs, event_result['response']['message']['detection'])

        if self.run_args.server_header:
            headers['Server'] = self.run_args.server_header

        if 'cookies' in data and 'sess_uuid' in data['cookies']:
            previous_sess_uuid = data['cookies']['sess_uuid']
        else:
            previous_sess_uuid = None

        if event_result is not None and\
                'sess_uuid' in event_result['response']['message']:
            cur_sess_id = event_result['response']['message']['sess_uuid']
            if previous_sess_uuid is None or not previous_sess_uuid.strip() or previous_sess_uuid != cur_sess_id:
                headers.add('Set-Cookie', 'sess_uuid=' + cur_sess_id)

        return web.Response(body=content, status=status_code, headers=headers) 
示例25
def make_svg(self, request):
        try:
            parts = request.query["fen"].replace("_", " ").split(" ", 1)
            board = chess.BaseBoard("/".join(parts[0].split("/")[0:8]))
        except KeyError:
            raise aiohttp.web.HTTPBadRequest(reason="fen required")
        except ValueError:
            raise aiohttp.web.HTTPBadRequest(reason="invalid fen")

        try:
            size = min(max(int(request.query.get("size", 360)), 16), 1024)
        except ValueError:
            raise aiohttp.web.HTTPBadRequest(reason="size is not a number")

        try:
            uci = request.query.get("lastMove") or request.query["lastmove"]
            lastmove = chess.Move.from_uci(uci)
        except KeyError:
            lastmove = None
        except ValueError:
            raise aiohttp.web.HTTPBadRequest(reason="lastMove is not a valid uci move")

        try:
            check = chess.SQUARE_NAMES.index(request.query["check"])
        except KeyError:
            check = None
        except ValueError:
            raise aiohttp.web.HTTPBadRequest(reason="check is not a valid square name")

        try:
            arrows = [arrow(s.strip()) for s in request.query.get("arrows", "").split(",") if s.strip()]
        except ValueError:
            raise aiohttp.web.HTTPBadRequest(reason="invalid arrow")

        flipped = request.query.get("orientation", "white") == "black"

        return chess.svg.board(board, coordinates=False, flipped=flipped, lastmove=lastmove, check=check, arrows=arrows, size=size, style=self.css) 
示例26
def render_svg(self, request):
        return aiohttp.web.Response(text=self.make_svg(request), content_type="image/svg+xml") 
示例27
def render_png(self, request):
        svg_data = self.make_svg(request)
        png_data = cairosvg.svg2png(bytestring=svg_data)
        return aiohttp.web.Response(body=png_data, content_type="image/png") 
示例28
def init_app(self):
        from nautilus.api.endpoints import template_dir as api_template_dir
        from nautilus.auth import template_dir as auth_template_dir
        # the secret key
        secret_key = 'NERbTdtQl7IrBM9kx1PDjJXiyZhWWBZ9E7q2B3U7KVE='
        # create a web application instance
        self.app = aiohttp.web.Application(
            middlewares=[
                session_middleware(
                    EncryptedCookieStorage(secret_key, secure=True, domain='*')
                )
            ]
        )
        # add the template loader
        aiohttp_jinja2.setup(self.app,
            loader=jinja2.ChoiceLoader([
                jinja2.FileSystemLoader(api_template_dir),
                jinja2.FileSystemLoader(auth_template_dir)
            ])
        )
        # TODO:
            # debug mode

        # attach the ioloop to the application
        self.loop = asyncio.get_event_loop()
        # attach the service to the loop
        self.loop.service = self 
示例29
def world_image(self, request):
        """ 显示正确的镇守府图片。
        舰娘游戏中客户端FLASH请求的镇守府图片是根据FLASH本身的URL生成的,需要根据用户所在的镇守府IP为其显示正确的图片。

        :param request: aiohttp.web.Request
        :return: aiohttp.web.HTTPFound or aiohttp.web.HTTPBadRequest
        """
        size = request.match_info['size']
        session = yield from get_session(request)
        world_ip = session['world_ip']
        if world_ip:
            ip_sections = map(int, world_ip.split('.'))
            image_name = '_'.join([format(x, '03') for x in ip_sections]) + '_' + size
            if image_name in self.worlds:
                body = self.worlds[image_name]
            else:
                url = 'http://203.104.209.102/kcs/resources/image/world/' + image_name + '.png'
                coro = aiohttp.get(url, connector=self.connector)
                try:
                    response = yield from asyncio.wait_for(coro, timeout=5)
                except asyncio.TimeoutError:
                    return aiohttp.web.HTTPBadRequest()
                body = yield from response.read()
                self.worlds[image_name] = body
            return aiohttp.web.Response(body=body, headers={'Content-Type': 'image/png', 'Cache-Control': 'no-cache'})
        else:
            return aiohttp.web.HTTPBadRequest() 
示例30
def api(self, request):
        """ 转发客户端和游戏服务器之间的API通信。

        :param request: aiohttp.web.Request
        :return: aiohttp.web.Response or aiohttp.web.HTTPBadRequest
        """
        action = request.match_info['action']
        session = yield from get_session(request)
        world_ip = session['world_ip']
        if world_ip:
            if action == 'api_start2' and self.api_start2 is not None:
                return aiohttp.web.Response(body=self.api_start2,
                                            headers=aiohttp.MultiDict({'Content-Type': 'text/plain'}))
            else:
                referrer = request.headers.get('REFERER')
                referrer = referrer.replace(request.host, world_ip)
                referrer = referrer.replace('https://', 'http://')
                url = 'http://' + world_ip + '/kcsapi/' + action
                headers = aiohttp.MultiDict({
                    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko',
                    'Origin': 'http://' + world_ip + '/',
                    'Referer': referrer,
                })
                data = yield from request.post()
                coro = aiohttp.post(url, data=data, headers=headers, connector=self.connector)
                try:
                    response = yield from asyncio.wait_for(coro, timeout=5)
                except asyncio.TimeoutError:
                    return aiohttp.web.HTTPBadRequest()
                body = yield from response.read()
                if action == 'api_start2' and len(body) > 100000:
                    self.api_start2 = body
                return aiohttp.web.Response(body=body, headers=aiohttp.MultiDict({'Content-Type': 'text/plain'}))
        else:
            return aiohttp.web.HTTPBadRequest()