本文整理汇总了Python中aiohttp.hdrs.CONTENT_TYPE属性的典型用法代码示例。如果您正苦于以下问题:Python hdrs.CONTENT_TYPE属性的具体用法?Python hdrs.CONTENT_TYPE怎么用?Python hdrs.CONTENT_TYPE使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类aiohttp.hdrs
的用法示例。
在下文中一共展示了hdrs.CONTENT_TYPE属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: process
# 需要导入模块: from aiohttp import hdrs [as 别名]
# 或者: from aiohttp.hdrs import CONTENT_TYPE [as 别名]
def process(self):
request = self.request
if request.method == hdrs.METH_OPTIONS:
headers = (
(hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"),
(hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"),
)
headers += session_cookie(request)
headers += cors_headers(request.headers)
headers += cache_headers()
return web.Response(status=204, headers=headers)
headers = (
(hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"),
(hdrs.CACHE_CONTROL, CACHE_CONTROL),
)
headers += session_cookie(request)
headers += cors_headers(request.headers)
resp = self.response = web.StreamResponse(headers=headers)
await resp.prepare(request)
await self.handle_session()
return resp
示例2: process
# 需要导入模块: from aiohttp import hdrs [as 别名]
# 或者: from aiohttp.hdrs import CONTENT_TYPE [as 别名]
def process(self):
headers = (
(hdrs.CONTENT_TYPE, "text/event-stream"),
(hdrs.CACHE_CONTROL, CACHE_CONTROL),
)
headers += session_cookie(self.request)
# open sequence (sockjs protocol)
resp = self.response = web.StreamResponse(headers=headers)
await resp.prepare(self.request)
await resp.write(b"\r\n")
# handle session
await self.handle_session()
return resp
示例3: request
# 需要导入模块: from aiohttp import hdrs [as 别名]
# 或者: from aiohttp.hdrs import CONTENT_TYPE [as 别名]
def request(
self, method, path, *args,
parts=None, json=None,
**kwargs):
# support name as url
if isinstance(path, str):
if not path.startswith('/'):
parts = parts or {}
path = self.server.app.router[path].url_for(**parts)
elif self.base_path and not path.startswith(self.base_path):
path = self.base_path + path
# support raw data
if json is not None:
kwargs['data'] = self.dumps(json)
hs = kwargs.setdefault('headers', {})
hs[hdrs.CONTENT_TYPE] = 'application/json'
return super().request(
method=method, path=path, *args, **kwargs)
示例4: __init__
# 需要导入模块: from aiohttp import hdrs [as 别名]
# 或者: from aiohttp.hdrs import CONTENT_TYPE [as 别名]
def __init__(self, *, body: Optional[Union[bytes, str]] = None, status: int = 200, reason: Optional[str] = None, headers: Optional[Union[Dict, CIMultiDict, CIMultiDictProxy]] = None, content_type: Optional[str] = None, charset: Optional[str] = None) -> None:
if headers is None:
headers = CIMultiDict()
elif not isinstance(headers, (CIMultiDict, CIMultiDictProxy)):
headers = CIMultiDict(headers)
self._body = body
self._status = status
self._reason = reason
self._headers = headers
self.content_type = content_type if hdrs.CONTENT_TYPE not in headers else None
self.charset = charset if hdrs.CONTENT_TYPE not in headers else None
self.missing_content_type = hdrs.CONTENT_TYPE not in headers and not content_type and not charset
示例5: get_aiohttp_response
# 需要导入模块: from aiohttp import hdrs [as 别名]
# 或者: from aiohttp.hdrs import CONTENT_TYPE [as 别名]
def get_aiohttp_response(self, context: Dict, default_charset: Optional[str] = None, default_content_type: Optional[str] = None) -> web.Response:
if self.missing_content_type:
self.charset = default_charset
self.content_type = default_content_type
charset = self.charset
if hdrs.CONTENT_TYPE in self._headers and ';' in self._headers[hdrs.CONTENT_TYPE]:
try:
charset = str([v for v in self._headers[hdrs.CONTENT_TYPE].split(';') if 'charset=' in v][0]).replace('charset=', '').strip()
except IndexError:
pass
elif hdrs.CONTENT_TYPE in self._headers and ';' not in self._headers[hdrs.CONTENT_TYPE]:
charset = None
if self._body and not isinstance(self._body, bytes) and charset:
body = self._body
try:
body_value = body.encode(charset.lower())
except (ValueError, LookupError, UnicodeEncodeError) as e:
logging.getLogger('exception').exception('Uncaught exception: {}'.format(str(e)))
raise web.HTTPInternalServerError() from e # type: ignore
elif self._body:
body_value = self._body.encode() if not isinstance(self._body, bytes) else self._body
else:
body_value = b''
response = web.Response(body=body_value, # type: ignore
status=self._status,
reason=self._reason,
headers=self._headers,
content_type=self.content_type,
charset=self.charset) # type: web.Response
return response
示例6: download_single
# 需要导入模块: from aiohttp import hdrs [as 别名]
# 或者: from aiohttp.hdrs import CONTENT_TYPE [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 hdrs [as 别名]
# 或者: from aiohttp.hdrs import CONTENT_TYPE [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: info
# 需要导入模块: from aiohttp import hdrs [as 别名]
# 或者: from aiohttp.hdrs import CONTENT_TYPE [as 别名]
def info(self, request):
resp = web.Response()
resp.headers[hdrs.CONTENT_TYPE] = "application/json;charset=UTF-8"
resp.headers[hdrs.CACHE_CONTROL] = CACHE_CONTROL
resp.headers.extend(cors_headers(request.headers))
info = {
"entropy": random.randint(1, 2147483647),
"websocket": "websocket" not in self.disable_transports,
"cookie_needed": self.cookie_needed,
"origins": ["*:*"],
}
resp.text = json.dumps(info)
return resp
示例9: info_options
# 需要导入模块: from aiohttp import hdrs [as 别名]
# 或者: from aiohttp.hdrs import CONTENT_TYPE [as 别名]
def info_options(self, request):
resp = web.Response(status=204)
resp.headers[hdrs.CONTENT_TYPE] = "application/json;charset=UTF-8"
resp.headers[hdrs.CACHE_CONTROL] = CACHE_CONTROL
resp.headers[hdrs.ACCESS_CONTROL_ALLOW_METHODS] = "OPTIONS, GET"
resp.headers.extend(cors_headers(request.headers))
resp.headers.extend(cache_headers())
resp.headers.extend(session_cookie(request))
return resp
示例10: iframe
# 需要导入模块: from aiohttp import hdrs [as 别名]
# 或者: from aiohttp.hdrs import CONTENT_TYPE [as 别名]
def iframe(self, request):
cached = request.headers.get(hdrs.IF_NONE_MATCH)
if cached:
response = web.Response(status=304)
response.headers[hdrs.CONTENT_TYPE] = ""
response.headers.extend(cache_headers())
return response
headers = (
(hdrs.CONTENT_TYPE, "text/html;charset=UTF-8"),
(hdrs.ETAG, self.iframe_html_hxd),
)
headers += cache_headers()
return web.Response(body=self.iframe_html, headers=headers)
示例11: greeting
# 需要导入模块: from aiohttp import hdrs [as 别名]
# 或者: from aiohttp.hdrs import CONTENT_TYPE [as 别名]
def greeting(self, request):
return web.Response(
body=b"Welcome to SockJS!\n",
headers=((hdrs.CONTENT_TYPE, "text/plain; charset=UTF-8"),),
)
示例12: process
# 需要导入模块: from aiohttp import hdrs [as 别名]
# 或者: from aiohttp.hdrs import CONTENT_TYPE [as 别名]
def process(self):
request = self.request
if request.method not in (hdrs.METH_GET, hdrs.METH_POST, hdrs.METH_OPTIONS):
return web.HTTPForbidden(text="Method is not allowed")
if self.request.method == hdrs.METH_OPTIONS:
headers = (
(hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"),
(hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"),
)
headers += session_cookie(request)
headers += cors_headers(request.headers)
headers += cache_headers()
return web.Response(status=204, headers=headers)
data = await request.read()
if not data:
return web.HTTPInternalServerError(text="Payload expected.")
try:
messages = loads(data.decode(ENCODING))
except Exception:
return web.HTTPInternalServerError(text="Broken JSON encoding.")
await self.session._remote_messages(messages)
headers = (
(hdrs.CONTENT_TYPE, "text/plain; charset=UTF-8"),
(hdrs.CACHE_CONTROL, CACHE_CONTROL),
)
headers += session_cookie(request)
headers += cors_headers(request.headers)
return web.Response(status=204, headers=headers)
示例13: process
# 需要导入模块: from aiohttp import hdrs [as 别名]
# 或者: from aiohttp.hdrs import CONTENT_TYPE [as 别名]
def process(self):
request = self.request
headers = (
(hdrs.CONNECTION, request.headers.get(hdrs.CONNECTION, "close")),
(hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"),
(hdrs.CACHE_CONTROL, CACHE_CONTROL),
)
headers += session_cookie(request)
headers += cors_headers(request.headers)
if request.method == hdrs.METH_OPTIONS:
headers += ((hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"),)
headers += cache_headers()
return web.Response(status=204, headers=headers)
# open sequence (sockjs protocol)
resp = self.response = web.StreamResponse(headers=headers)
resp.force_close()
await resp.prepare(request)
await resp.write(self.open_seq)
# event loop
await self.handle_session()
return resp
示例14: get_post_data
# 需要导入模块: from aiohttp import hdrs [as 别名]
# 或者: from aiohttp.hdrs import CONTENT_TYPE [as 别名]
def get_post_data(cls, request):
"""extract input JSON from POST request"""
if request.headers.get(hdrs.CONTENT_TYPE, None) == 'application/json':
return await request.json()
raise web.HTTPUnsupportedMediaType(reason="Application/json media type is needed")
示例15: download_url
# 需要导入模块: from aiohttp import hdrs [as 别名]
# 或者: from aiohttp.hdrs import CONTENT_TYPE [as 别名]
def download_url(self, url):
async with ClientSession() as session:
async with session.get(url) as resp:
content_type = resp.headers.get(hdrs.CONTENT_TYPE)
data = BytesIO(await resp.read())
if content_type and ';' in content_type:
content_type = content_type[:content_type.index(';')]
return content_type, data