确定在HTTP响应中发送的最佳内容
项目描述
accept-types 帮助您的应用程序以客户端偏好的方式响应用户的HTTP请求。HTTP请求的 Accept 头信息告知服务器客户端期望从该请求返回哪些MIME类型,并通过权重表示最偏好的类型。如果您的服务器可以以多种格式响应(例如:JSON、XML、HTML),则客户端可以轻松地告诉服务器首选的格式,而无需在查询字符串末尾使用如‘&format=json’之类的技巧。
用法
get_best_match
当提供 Accept 头和服务器可以响应的类型列表时,此函数将返回客户端最偏好的类型。此函数将仅返回您传入的可接受类型中的一个,或者如果没有找到合适的类型,则返回 None
from accept_type import get_best_match
def get_the_info(request):
info = gather_info()
return_type = get_best_match(request.META.get('HTTP_ACCEPT'), ['text/html', 'application/xml', 'text/json'])
if return_type == 'application/xml':
return render_xml(info)
elif return_type == 'text/json':
return render_json(info)
elif return_type == 'text/html':
return render_html(info)
elif return_type == None:
return HttpResponse406()
parse_header
当提供 Accept 头时,这将解析它并返回一个按顺序排列的客户端接受的MIME类型列表。这些将是 AcceptableType 类的实例。
>>> from accept_type import parse_header
>>> parse_header('text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8')
['text/html, weight 1', 'application/xhtml+xml, weight 1', 'application/xml, weight 0.9', '*/*, weight 0.8']
AcceptableType
AcceptableType 实例代表客户端愿意接受的一种类型。这种类型可能包括通配符,以匹配多个MIME类型。
>>> from accept_type import AcceptableType
>>> type = AcceptableType('image/*;q=0.9')
AcceptableType
>>> type.mime_type
'image/*'
>>> type.weight
0.9
>>> type.matches('image/png')
True
>>> type.matches('text/html')
False
项目详情
下载文件
下载适用于您的平台的文件。如果您不确定选择哪个,请了解更多关于 安装软件包 的信息。
源代码分发
accept-types-0.4.1.tar.gz (3.7 kB 查看哈希值)
构建分发
accept_types-0.4.1-py3-none-any.whl (5.0 kB 查看哈希值)