本文整理汇总了Python中aiohttp.web.FileResponse方法的典型用法代码示例。如果您正苦于以下问题:Python web.FileResponse方法的具体用法?Python web.FileResponse怎么用?Python web.FileResponse使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类aiohttp.web
的用法示例。
在下文中一共展示了web.FileResponse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_tails_file
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import FileResponse [as 别名]
def get_tails_file(request: web.BaseRequest) -> web.FileResponse:
"""
Request handler to download the tails file of the revocation registry.
Args:
request: aiohttp request object
Returns:
The tails file in FileResponse
"""
context = request.app["request_context"]
registry_id = request.match_info["rev_reg_id"]
try:
revoc = IndyRevocation(context)
revoc_registry = await revoc.get_issuer_rev_reg_record(registry_id)
except StorageNotFoundError as err:
raise web.HTTPNotFound(reason=err.roll_up) from err
return web.FileResponse(path=revoc_registry.tails_local_path, status=200)
示例2: setup_router
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import FileResponse [as 别名]
def setup_router(self):
self.app.router.add_get('/get/proxy/', self.get_proxies_html)
self.app.router.add_get('/get/proxy_count_item/', self.get_proxy_count_items_html)
self.app.router.add_get('/get/number_of_proxies_to_process/', self.get_number_of_proxies_to_process_html)
self.app.router.add_get('/get/processor_proxies_queue_size/', self.get_processor_proxies_queue_size_html)
self.app.router.add_get('/get/collector_state/', self.get_collector_state_html)
self.app.router.add_get('/get/best/http/proxy/', self.get_best_http_proxy)
# self.app.router.add_get('/{tail:.*}', self.default_route)
#
# async def default_route(self, request: aiohttp.ClientRequest):
# path = request.path
# if path == '/':
# path = '/index.html'
#
# if re.match(r'^(/([a-zA-Z0-9_]+(\.[a-zA-Z0-9]+)*)?)+$', path):
# try:
# path = os.path.join('./server/frontend/angular/dist', path)
# with open(path, 'r'):
# return web.FileResponse(path)
# except (FileNotFoundError, IsADirectoryError):
# pass
#
# return web.FileResponse('./server/frontend/angular/dist/index.html')
示例3: redirect_index
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import FileResponse [as 别名]
def redirect_index(_: web.Request) -> web.FileResponse:
return web.FileResponse(pkg_resources.resource_filename("mautrix_hangouts",
"web/static/login-redirect.html"))
示例4: static_request_handler
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import FileResponse [as 别名]
def static_request_handler(cls: Any, obj: Any, context: Dict, func: Any, path: str, base_url: str, ignore_logging: Union[bool, List[int], Tuple[int]] = False) -> Any:
if '?P<filename>' not in base_url:
pattern = r'^{}(?P<filename>.+?)$'.format(re.sub(r'\$$', '', re.sub(r'^\^?(.*)$', r'\1', base_url)))
else:
pattern = r'^{}$'.format(re.sub(r'\$$', '', re.sub(r'^\^?(.*)$', r'\1', base_url)))
compiled_pattern = re.compile(pattern)
if path.startswith('/'):
path = os.path.dirname(path)
else:
path = '{}/{}'.format(os.path.dirname(context.get('context', {}).get('_service_file_path')), path)
if not path.endswith('/'):
path = '{}/'.format(path)
async def handler(request: web.Request) -> web.Response:
result = compiled_pattern.match(request.path)
filename = result.groupdict()['filename'] if result else ''
filepath = '{}{}'.format(path, filename)
try:
if os.path.commonprefix((os.path.realpath(filepath), os.path.realpath(path))) != os.path.realpath(path) or os.path.isdir(filepath) or not os.path.exists(filepath):
raise web.HTTPNotFound() # type: ignore
pathlib.Path(filepath).open('r')
response = FileResponse(path=filepath, # type: ignore
chunk_size=256 * 1024) # type: web.Response
return response
except PermissionError as e:
raise web.HTTPForbidden() # type: ignore
route_context = {'ignore_logging': ignore_logging}
context['_http_routes'] = context.get('_http_routes', [])
context['_http_routes'].append(('GET', pattern, handler, route_context))
start_func = cls.start_server(obj, context)
return (await start_func) if start_func else None
示例5: resolve_response
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import FileResponse [as 别名]
def resolve_response(value: Union[str, bytes, Dict, List, Tuple, web.Response, Response], request: Optional[web.Request] = None, context: Dict = None, status_code: Optional[Union[str, int]] = None, default_content_type: Optional[str] = None, default_charset: Optional[str] = None) -> web.Response:
if not context:
context = {}
if isinstance(value, Response):
return value.get_aiohttp_response(context, default_content_type=default_content_type, default_charset=default_charset)
if isinstance(value, web.FileResponse):
return value
status = int(status_code) if status_code else (request is not None and request._cache.get('error_status_code', 200)) or 200
headers = None
if isinstance(value, dict):
body = value.get('body')
_status = value.get('status') # type: Optional[SupportsInt]
if _status and isinstance(_status, (int, str, bytes)):
status = int(_status)
_returned_headers = value.get('headers')
if _returned_headers:
returned_headers = _returned_headers # type: Union[Mapping[str, Any], Iterable[Tuple[str, Any]]]
headers = CIMultiDict(returned_headers)
elif isinstance(value, list) or isinstance(value, tuple):
_status = value[0]
if _status and isinstance(_status, (int, str, bytes)):
status = int(_status)
body = value[1]
if len(value) > 2:
returned_headers = value[2]
headers = CIMultiDict(returned_headers)
elif isinstance(value, web.Response):
return value
else:
if value is None:
value = ''
body = value
return Response(body=body, status=status, headers=headers, content_type=default_content_type, charset=default_charset).get_aiohttp_response(context)
示例6: download_single
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import FileResponse [as 别名]
def download_single(request: web.Request, params: Any, row: VFolderRow) -> web.StreamResponse:
folder_name = request.match_info['name']
access_key = request['keypair']['access_key']
fn = params['file']
log.info('VFOLDER.DOWNLOAD_SINGLE (ak:{}, vf:{}, path:{})', access_key, folder_name, fn)
folder_path = get_folder_hostpath(row, request.app)
try:
file_path = (folder_path / fn).resolve()
file_path.relative_to(folder_path)
if not file_path.exists():
raise FileNotFoundError
except (ValueError, FileNotFoundError):
raise GenericNotFound('The file is not found.')
if not file_path.is_file():
if params['archive']:
# Download directory as an archive when archive param is set.
return await download_directory_as_archive(request, file_path)
else:
raise InvalidAPIParameters('The file is not a regular file.')
if request.method == 'HEAD':
return web.Response(status=200, headers={
hdrs.ACCEPT_RANGES: 'bytes',
hdrs.CONTENT_LENGTH: str(file_path.stat().st_size),
})
ascii_filename = file_path.name.encode('ascii', errors='ignore').decode('ascii').replace('"', r'\"')
encoded_filename = urllib.parse.quote(file_path.name, encoding='utf-8')
return web.FileResponse(file_path, headers={
hdrs.CONTENT_TYPE: "application/octet-stream",
hdrs.CONTENT_DISPOSITION: " ".join([
"attachment;"
f"filename=\"{ascii_filename}\";", # RFC-2616 sec2.2
f"filename*=UTF-8''{encoded_filename}", # RFC-5987
])
})
示例7: get_task_logs
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import FileResponse [as 别名]
def get_task_logs(request: web.Request, params: Any) -> web.StreamResponse:
log.info('GET_TASK_LOG (ak:{}, k:{})',
request['keypair']['access_key'], params['kernel_id'])
domain_name = request['user']['domain_name']
user_role = request['user']['role']
user_uuid = request['user']['uuid']
raw_kernel_id = params['kernel_id'].hex
mount_prefix = await request.app['config_server'].get('volumes/_mount')
fs_prefix = await request.app['config_server'].get('volumes/_fsprefix')
async with request.app['dbpool'].acquire() as conn, conn.begin():
matched_vfolders = await query_accessible_vfolders(
conn, user_uuid,
user_role=user_role, domain_name=domain_name,
allowed_vfolder_types=['user'],
extra_vf_conds=(vfolders.c.name == '.logs'))
if not matched_vfolders:
raise GenericNotFound('You do not have ".logs" vfolder for persistent task logs.')
log_vfolder = matched_vfolders[0]
log_path = (
Path(mount_prefix) / log_vfolder['host'] / Path(fs_prefix.lstrip('/')) /
log_vfolder['id'].hex /
'task' / raw_kernel_id[:2] / raw_kernel_id[2:4] / f'{raw_kernel_id[4:]}.log'
)
def check_file():
if not log_path.is_file():
raise GenericNotFound('The requested log file or the task was not found.')
try:
with open(log_path, 'rb'):
pass
except IOError:
raise GenericNotFound('The requested log file is not readable.')
loop = current_loop()
await loop.run_in_executor(None, check_file)
return web.FileResponse(log_path, headers={
hdrs.CONTENT_TYPE: "text/plain",
})
示例8: get_index
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import FileResponse [as 别名]
def get_index(_: web.Request) -> web.FileResponse:
return web.FileResponse(pkg_resources.resource_filename("mautrix_hangouts",
"web/static/login.html"))
示例9: handle_upload_global_file
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import FileResponse [as 别名]
def handle_upload_global_file(self, request):
try:
fileID = request.match_info.get("id", "")
return web.FileResponse(os.path.join(bumper.bumper_dir,"bumper","web","images","robotvac_image.jpg"))
except Exception as e:
logging.exception("{}".format(e))
示例10: handle_pimFile
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import FileResponse [as 别名]
def handle_pimFile(self, request):
try:
fileID = request.match_info.get("id", "")
return web.FileResponse(os.path.join(bumper.bumper_dir,"bumper","web","images","robotvac_image.jpg"))
except Exception as e:
logging.exception("{}".format(e))
示例11: download_song
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import FileResponse [as 别名]
def download_song(request: web.Request) -> web.FileResponse:
"""GET /api/install/song/{song_id}
Description:
Download a song by its ID.
Example:
link: /api/install/song/905110
Returns:
200: Found song;
400: Invalid type;
404: Failed to find the song.
Return Type:
audio/mpeg
"""
song_id = int(request.match_info["song_id"])
path = ROOT_PATH / f"song-{song_id}.mp3"
if path.exists():
return web.FileResponse(path)
song = await request.app.client.get_ng_song(song_id)
await song.download(file=path)
request.loop.create_task(delete_after(60, path))
return web.FileResponse(path)
示例12: generate_icons
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import FileResponse [as 别名]
def generate_icons(request: web.Request) -> web.Response:
query = multidict.CIMultiDict(request.query)
color_1 = color_from_hex(query.pop("color_1", "0x00ff00"))
color_2 = color_from_hex(query.pop("color_2", "0x00ffff"))
glow_outline = str_to_bool(query.pop("glow_outline", "false"))
error_on_not_found = str_to_bool(query.pop("error_on_not_found", "false"))
settings = f"color_1={color_1}$color_2={color_2}$glow_outline={glow_outline}".lower()
types = "$".join(f"{key}={value}".lower() for key, value in query.items())
name = f"[{settings}]({types}).png"
path = ROOT_PATH / name
if path.exists():
return web.FileResponse(path)
images = [
await gd.utils.run_blocking_io(
gd.factory.generate,
icon_type=gd.IconType.from_value(icon_type),
icon_id=int(icon_id),
color_1=color_1,
color_2=color_2,
glow_outline=glow_outline,
error_on_not_found=error_on_not_found,
)
for icon_type, icon_id in query.items()
]
if not images:
raise Warning("No types were generated.")
image = await gd.utils.run_blocking_io(gd.icon_factory.connect_images, images)
image.save(path)
request.loop.create_task(delete_after(5, path))
return web.FileResponse(path)
示例13: test_funnel
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import FileResponse [as 别名]
def test_funnel(tmp_path, aiohttp_client):
tmp_file = tmp_path / 'test'
data = bytes(getrandbits(8) for _ in range(16))
tmp_file.write_bytes(data)
async def serve_file(request):
# FileResponse supports range requests.
return web.FileResponse(tmp_file)
app = web.Application()
app.router.add_get('/', serve_file)
session = await aiohttp_client(app)
async def test(block_size, piece_size):
r = HttpRange(0, len(data) - 1)
buf = BytesIO()
async with Funnel(
url='/',
range=r,
session=session,
block_size=block_size,
piece_size=piece_size) as funnel:
async for block in funnel:
buf.write(block)
assert buf.getvalue() == data
tests = []
for block_size in range(1, len(data) + 1):
for piece_size in range(1, block_size + 1):
tests.append(asyncio.create_task(test(block_size, piece_size)))
await asyncio.gather(*tests)
示例14: index
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import FileResponse [as 别名]
def index(request):
return web.FileResponse(ROOT / 'index.html')
示例15: favicon
# 需要导入模块: from aiohttp import web [as 别名]
# 或者: from aiohttp.web import FileResponse [as 别名]
def favicon(request):
return web.FileResponse("static/favicon.ico")