本文整理汇总了Python中aiohttp.web.View方法的典型用法代码示例。如果您正苦于以下问题:Python web.View方法的具体用法?Python web.View怎么用?Python web.View使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类aiohttp.web
的用法示例。
在下文中一共展示了web.View方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_render_class_based_view
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import View [as 别名]
def test_render_class_based_view(aiohttp_client):
class MyView(web.View):
@aiohttp_jinja2.template('tmpl.jinja2')
async def get(self):
return {'head': 'HEAD', 'text': 'text'}
template = '<html><body><h1>{{head}}</h1>{{text}}</body></html>'
app = web.Application()
aiohttp_jinja2.setup(app, loader=jinja2.DictLoader({
'tmpl.jinja2': template
}))
app.router.add_route('*', '/', MyView)
client = await aiohttp_client(app)
resp = await client.get('/')
assert 200 == resp.status
txt = await resp.text()
assert '<html><body><h1>HEAD</h1>text</body></html>' == txt
示例2: test_atomic_from_view
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import View [as 别名]
def test_atomic_from_view(aiohttp_client):
app = web.Application()
class MyView(web.View):
@atomic
async def get(self):
return web.Response()
app.router.add_route("*", "/", MyView)
aiojobs_setup(app)
client = await aiohttp_client(app)
resp = await client.get('/')
assert resp.status == 200
scheduler = get_scheduler_from_app(app)
assert scheduler.active_count == 0
assert scheduler.pending_count == 0
示例3: test_nested_application
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import View [as 别名]
def test_nested_application(aiohttp_client):
app = web.Application()
aiojobs_setup(app)
app2 = web.Application()
class MyView(web.View):
async def get(self):
assert get_scheduler_from_request(self.request) ==\
get_scheduler_from_app(app)
return web.Response()
app2.router.add_route("*", "/", MyView)
app.add_subapp("/sub/", app2)
client = await aiohttp_client(app)
resp = await client.get("/sub/")
assert resp.status == 200
示例4: test_nested_application_separate_scheduler
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import View [as 别名]
def test_nested_application_separate_scheduler(aiohttp_client):
app = web.Application()
aiojobs_setup(app)
app2 = web.Application()
aiojobs_setup(app2)
class MyView(web.View):
async def get(self):
assert get_scheduler_from_request(self.request) !=\
get_scheduler_from_app(app)
assert get_scheduler_from_request(self.request) ==\
get_scheduler_from_app(app2)
return web.Response()
app2.router.add_route("*", "/", MyView)
app.add_subapp("/sub/", app2)
client = await aiohttp_client(app)
resp = await client.get("/sub/")
assert resp.status == 200
示例5: login_required
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import View [as 别名]
def login_required(func):
@wraps(func)
async def wrapped(*args, **kwargs):
if middleware._request_property is ...:
raise RuntimeError('Incorrect usage of decorator.'
'Please initialize middleware first')
request = args[-1]
if isinstance(request, web.View):
request = request.request
if not isinstance(request, web.BaseRequest): # pragma: no cover
raise RuntimeError(
'Incorrect usage of decorator.'
'Expect web.BaseRequest as an argument')
if not request.get(middleware._request_property):
raise web.HTTPUnauthorized(reason='Authorization required')
return await func(*args, **kwargs)
return wrapped
示例6: template
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import View [as 别名]
def template(
template_name: str,
*,
app_key: str = APP_KEY,
encoding: str = 'utf-8',
status: int = 200
) -> Any:
def wrapper(func: Any) -> Any:
@functools.wraps(func)
async def wrapped(*args: Any) -> web.StreamResponse:
if asyncio.iscoroutinefunction(func):
coro = func
else:
warnings.warn("Bare functions are deprecated, "
"use async ones", DeprecationWarning)
coro = asyncio.coroutine(func)
context = await coro(*args)
if isinstance(context, web.StreamResponse):
return context
# Supports class based views see web.View
if isinstance(args[0], AbstractView):
request = args[0].request
else:
request = args[-1]
response = render_template(template_name, request, context,
app_key=app_key, encoding=encoding)
response.set_status(status)
return response
return wrapped
return wrapper
示例7: test_nested_application_not_set
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import View [as 别名]
def test_nested_application_not_set(aiohttp_client):
app = web.Application()
app2 = web.Application()
class MyView(web.View):
async def get(self):
assert get_scheduler_from_request(self.request) is None
return web.Response()
app2.router.add_route("*", "/", MyView)
app.add_subapp("/sub/", app2)
client = await aiohttp_client(app)
resp = await client.get("/sub/")
assert resp.status == 200
示例8: atomic
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import View [as 别名]
def atomic(coro):
@wraps(coro)
async def wrapper(request):
if isinstance(request, View):
# Class Based View decorated.
request = request.request
job = await spawn(request, coro(request))
return await job.wait()
return wrapper
示例9: main
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import View [as 别名]
def main():
app = web.Application()
s = SwaggerDocs(app, swagger_ui_settings=SwaggerUiSettings(path="/docs"))
s.add_routes([web.view("/r/{param_id}", View)])
web.run_app(app)
示例10: test_class_based_spec_file
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import View [as 别名]
def test_class_based_spec_file(swagger_file, aiohttp_client):
class Pets(web.View):
async def get(self, limit: Optional[int] = None):
pets = []
for i in range(limit or 3):
pets.append({"id": i, "name": f"pet_{i}", "tag": f"tag_{i}"})
return web.json_response(pets)
async def post(self, body: Dict):
return web.json_response(body, status=201)
swagger = swagger_file()
swagger.add_routes([web.view("/pets", Pets)])
client = await aiohttp_client(swagger._app)
resp = await client.get("/pets", params={"limit": 1})
assert resp.status == 200
assert await resp.json() == [{"id": 0, "name": "pet_0", "tag": "tag_0"}]
resp = await client.get("/pets")
assert resp.status == 200
assert await resp.json() == [
{"id": 0, "name": "pet_0", "tag": "tag_0"},
{"id": 1, "name": "pet_1", "tag": "tag_1"},
{"id": 2, "name": "pet_2", "tag": "tag_2"},
]
req = {"id": 10, "name": "pet", "tag": "tag"}
resp = await client.post("/pets", json=req)
assert resp.status == 201
assert await resp.json() == req
示例11: _handle_swagger_method_call
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import View [as 别名]
def _handle_swagger_method_call(
self, view: web.View, route: "SwaggerRoute"
) -> web.StreamResponse:
kwargs = await route.parse(view.request)
return await route.handler(view, **kwargs)
示例12: test_preflight_request_max_age_webview
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import View [as 别名]
def test_preflight_request_max_age_webview(aiohttp_client):
"""Test CORS preflight handling on resource that is available through
several routes.
"""
app = web.Application()
cors = _setup(app, defaults={
"*": ResourceOptions(
allow_credentials=True,
expose_headers="*",
allow_headers="*",
max_age=1200
)
})
class TestView(web.View, CorsViewMixin):
async def get(self):
resp = web.Response(text=TEST_BODY)
resp.headers[SERVER_CUSTOM_HEADER_NAME] = \
SERVER_CUSTOM_HEADER_VALUE
return resp
cors.add(app.router.add_route("*", "/{name}", TestView))
client = await aiohttp_client(app)
resp = await client.options(
"/user",
headers={
hdrs.ORIGIN: "http://example.org",
hdrs.ACCESS_CONTROL_REQUEST_METHOD: "GET"
}
)
assert resp.status == 200
assert resp.headers[hdrs.ACCESS_CONTROL_MAX_AGE].upper() == "1200"
data = await resp.text()
assert data == ""
示例13: test_preflight_request_mult_routes_with_one_options_webview
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import View [as 别名]
def test_preflight_request_mult_routes_with_one_options_webview(
aiohttp_client):
"""Test CORS preflight handling on resource that is available through
several routes.
"""
app = web.Application()
cors = _setup(app, defaults={
"*": ResourceOptions(
allow_credentials=True,
expose_headers="*",
allow_headers="*",
)
})
class TestView(web.View, CorsViewMixin):
async def get(self):
resp = web.Response(text=TEST_BODY)
resp.headers[SERVER_CUSTOM_HEADER_NAME] = \
SERVER_CUSTOM_HEADER_VALUE
return resp
put = get
cors.add(app.router.add_route("*", "/{name}", TestView))
client = await aiohttp_client(app)
resp = await client.options(
"/user",
headers={
hdrs.ORIGIN: "http://example.org",
hdrs.ACCESS_CONTROL_REQUEST_METHOD: "PUT"
}
)
assert resp.status == 200
data = await resp.text()
assert data == ""
示例14: test_method_with_custom_cors
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import View [as 别名]
def test_method_with_custom_cors(app):
"""Test adding resource with web.View as handler"""
request = mock.Mock()
request.app = app
view = CustomMethodView(request)
assert hasattr(view.post, 'post_cors_config')
assert asyncio.iscoroutinefunction(view.post)
config = view.get_request_config(request, 'post')
assert config.get('www.client1.com') == CUSTOM_CONFIG['www.client1.com']
示例15: test_method_with_class_config
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import View [as 别名]
def test_method_with_class_config(app):
"""Test adding resource with web.View as handler"""
request = mock.Mock()
request.app = app
view = SimpleViewWithConfig(request)
assert not hasattr(view.get, 'get_cors_config')
config = view.get_request_config(request, 'get')
assert config.get('*') == CLASS_CONFIG['*']