Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async def handle2(request):
nonlocal processed
resp = web.StreamResponse()
await resp.prepare(request)
resp.write(b'test2')
await resp.write_eof()
processed.append(2)
return resp
async def handler(request):
resp = web.StreamResponse(headers={'content-length': '100'})
await resp.prepare(request)
await asyncio.sleep(0.1)
return resp
async def handler(request):
resp = web.StreamResponse(headers={'content-length': str(4)})
await resp.prepare(request)
with pytest.warns(DeprecationWarning):
await resp.drain()
await asyncio.sleep(0.01)
await resp.write(b'test')
await asyncio.sleep(0.01)
await resp.write_eof()
return resp
def test_setting_charset() -> None:
resp = StreamResponse()
resp.content_type = 'text/html'
resp.charset = 'koi8-r'
assert 'text/html; charset=koi8-r' == resp.headers['content-type']
# Simple request
if (
hdrs.CONTENT_LENGTH in result.headers
and int(result.headers.get(hdrs.CONTENT_LENGTH, 0)) < 4194000
):
# Return Response
body = await result.read()
return web.Response(
headers=headers,
status=result.status,
content_type=result.content_type,
body=body,
)
# Stream response
response = web.StreamResponse(status=result.status, headers=headers)
response.content_type = result.content_type
try:
await response.prepare(request)
async for data in result.content.iter_chunked(4096):
await response.write(data)
except (aiohttp.ClientError, aiohttp.ClientPayloadError) as err:
_LOGGER.debug("Stream error %s / %s: %s", token, path, err)
return response
import copy
from pathlib import Path
from typing import Awaitable, Callable
from aiohttp import web
from aiohttp.hdrs import METH_ALL, METH_ANY
from apispec import APISpec
from apispec.core import VALID_METHODS_OPENAPI_V2
from apispec.ext.marshmallow import MarshmallowPlugin, common
from jinja2 import Template
from webargs.aiohttpparser import parser
from .utils import get_path, get_path_keys, issubclass_py37fix
_AiohttpView = Callable[[web.Request], Awaitable[web.StreamResponse]]
VALID_RESPONSE_FIELDS = {"description", "headers", "examples"}
def resolver(schema):
schema_instance = common.resolve_schema_instance(schema)
prefix = "Partial-" if schema_instance.partial else ""
schema_cls = common.resolve_schema_cls(schema)
name = prefix + schema_cls.__name__
if name.endswith("Schema"):
return name[:-6] or name
return name
class AiohttpApiSpec:
def __init__(
def __new__(cls, name, bases, attrs):
cls = type.__new__(cls, name, bases, attrs)
cls.Request = web.Request
cls.StreamResponse = web.StreamResponse
cls.Response = web.Response
cls.WebSocketResponse = web.WebSocketResponse
for name, obj in vars(web).items():
if name.startswith('HTTP'):
name = name.replace('HTTP', '', 1)
setattr(cls, name, obj)
return cls
async def hub(self, request: web.Request):
token = request.query.get("token")
if not token:
raise web.HTTPFound("/register?" + urlencode({"redirect": request.url}))
api_resp = await self.session.get("https://discordapp.com/api/users/@me",
headers={
"Authorization": f"Bearer {token}",
})
js = await api_resp.json()
if "code" in js:
return web.StreamResponse(reason=js["message"], status=js["code"])
resp = await self.get_userdata(js['id'])
guilds = await (await self.session.get("https://discordapp.com/api/users/@me/guilds",
headers={
"Authorization": f"Bearer {token}",
})).json()
fguilds = filter(lambda x: x["id"] in resp, guilds)
servers = "\n".join(f"""
<button>
<a href="/guilds?guild_id={guild[">
<img src="https://cdn.discordapp.com/icons/{guild[">
{guild["name"]}
</a>
</button>
<br>""" for guild in fguilds)
async def response(request):
logging.info('Response handler...')
r = await handler(request)
# 如果相应结果为StreamResponse,直接返回
# #treamResponse是aiohttp定义response的基类,即所有响应类型都继承自该类
# StreamResponse主要为流式数据而设计
if isinstance(r, web.StreamResponse):
return r
# 如果相应结果为字节流,则将其作为应答的body部分,并设置响应类型为流型
if isinstance(r, bytes):
resp = web.Response(body=r)
resp.content_type = 'application/octet-stream'
return resp
# 如果响应结果为字符串
if isinstance(r, str):
# 判断响应结果是否为重定向,如果是,返回重定向后的结果
if r.startswith('redirect:'):
return web.HTTPFound(r[9:]) # 即把r字符串之前的"redirect:"去掉
# 然后以utf8对其编码,并设置响应类型为html型
resp = web.Response(body=r.encode('utf-8'))
resp.content_type = 'text/html;charset=utf-8'
return resp
# 如果响应结果是字典,则获取他的jinja2模板信息,此处为jinja2.env
async def _proxy_http_forward_response(request, call):
"""Forward agent proxy response to an HTTP stream.
Must be run in parallel with the sending task.
Swallows any RPC exceptions, transforming them to HTTP error pages.
Args:
request: aiohttp request instance.
call: Active prpc call to proxy endpoint.
Returns:
aiohttp.Web.StreamResponse instance.
"""
response = aiohttp.web.StreamResponse()
msg_index = 0
async for msg in call.stream:
if msg_index == 0:
response.set_status(msg)
elif msg_index == 1:
headers = multidict.MultiDict(msg)
# Drop cache-related headers from the response, if any.
# Dynamic proxy content shouldn't be cached.
headers.popall('Cache-Control', None)
headers.popall('Expires', None)
response.headers.update(headers)
# TODO: add proxy headers?
# (X-Forwarded-For, drop Host => to X-Forwarded-Host,
# X-Forwarded-Proto OR the new shiny 'Forwarded')
# Note:
# All of those require 'append' like behavior.