本文整理汇总了Python中tastypie.utils.mime.build_content_type函数的典型用法代码示例。如果您正苦于以下问题:Python build_content_type函数的具体用法?Python build_content_type怎么用?Python build_content_type使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了build_content_type函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: test_build_content_type
def test_build_content_type(self):
# JSON & JSONP don't include charset.
self.assertEqual(build_content_type('application/json'), 'application/json')
self.assertEqual(build_content_type('text/javascript'), 'text/javascript')
self.assertEqual(build_content_type('application/json', encoding='ascii'), 'application/json')
# Everything else should.
self.assertEqual(build_content_type('application/xml'), 'application/xml; charset=utf-8')
self.assertEqual(build_content_type('application/xml', encoding='ascii'), 'application/xml; charset=ascii')
开发者ID:42ventures,项目名称:django-tastypie,代码行数:8,代码来源:utils.py
示例2: post_saved_shows
def post_saved_shows(self, request, **kwargs):
LOG.debug('in saved show')
form = SavedShowsForm(request.POST)
if form.is_valid():
user = request.user
add, remove = form.cleaned_data['add'], form.cleaned_data['remove']
LOG.debug('Request by user: %s to add: %s, remove: %s' % (user, add, remove))
show_set = user.starred_show_set
if add and add.id:
show_set.add_shows([add])
if remove and remove.id:
show_set.remove_shows([remove])
if add or remove:
show_set.save()
else:
desired_format = self.determine_format(request)
serialized = self.serialize(request, form.errors, desired_format)
response = HttpBadRequest(content=serialized, content_type=build_content_type(desired_format))
raise ImmediateHttpResponse(response=response)
开发者ID:hensom,项目名称:fancyashow,代码行数:26,代码来源:resources.py
示例3: error_response
def error_response(request, error_code=None, message=None, status_code=403, serializer_class=HTMLSerializer, **kwargs):
context = {}
if error_code:
context['error_code'] = error_code
if not message:
message = ERRORS[error_code].format(**kwargs)
if message:
context['error_message'] = message
context.update(kwargs)
serializer = serializer_class()
desired_format = determine_format(request, serializer)
options = {}
if 'text/javascript' in desired_format:
callback = request.GET.get('callback', 'callback')
if not is_valid_jsonp_callback_value(callback):
raise BadRequest('JSONP callback name is invalid.')
options['callback'] = callback
serialized = serializer.serialize(context, desired_format, options)
return HttpResponse(content=serialized, content_type=build_content_type(desired_format), status=status_code)
开发者ID:gannetson,项目名称:poc,代码行数:27,代码来源:functions.py
示例4: top_level
def top_level(self, request, api_name=None):
"""
A view that returns a serialized list of all resources registers
to the ``Api``. Useful for discovery.
"""
available_resources = {}
if api_name is None:
api_name = self.api_name
for name in sorted(self._registry.keys()):
available_resources[name] = {
"list_endpoint": self._build_reverse_url(
"api_dispatch_list", kwargs={"api_name": api_name, "resource_name": name}
),
"schema": self._build_reverse_url(
"api_get_schema", kwargs={"api_name": api_name, "resource_name": name}
),
}
desired_format = determine_format(request, self.serializer)
options = {}
if "text/javascript" in desired_format:
callback = request.GET.get("callback", "callback")
if not is_valid_jsonp_callback_value(callback):
raise BadRequest("JSONP callback name is invalid.")
options["callback"] = callback
serialized = self.serializer.serialize(available_resources, desired_format, options)
return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
开发者ID:dirn,项目名称:django-tastypie,代码行数:34,代码来源:api.py
示例5: create_response
def create_response(self, request, data, response_class=HttpResponse, **response_kwargs):
"""
Ensure that data is returned in the right format as an attachment if returning SDF or XLSX data
Should an object have been created or updated, now is the time to
reindex it in the elasticsearch index
"""
desired_format = self.determine_format(request)
if response_class == http.HttpCreated or response_class == http.HttpAccepted:
batches = []
if data.data.get("objects"):
for b in data.data.get("objects"):
batches.append(b.obj)
else:
batches.append(data.obj)
try:
index_batches_in_new_index(batches)
except:
#There has been an error in indexing therefore cleanup
session_key = request.COOKIES[settings.SESSION_COOKIE_NAME]
clean_up_multi_batch(data.obj.multiple_batch, session_key)
raise
serialized = self.serialize(request, data, desired_format)
rc = response_class(content=serialized, content_type=build_content_type(
desired_format), **response_kwargs)
if(desired_format == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'):
rc['Content-Disposition'] = 'attachment; filename=export_from_chembiohub_chemreg%d.xlsx' % int(time.time())
elif(desired_format == 'chemical/x-mdl-sdfile'):
rc['Content-Disposition'] = 'attachment; filename=export_from_chembiohub_chemreg%d.sdf' % int(time.time())
return rc
开发者ID:thesgc,项目名称:chembiohub_ws,代码行数:30,代码来源:resources.py
示例6: top_level
def top_level(self, request, api_name=None):
"""
A view that returns a serialized list of all resources registers
to the ``Api``. Useful for discovery.
"""
serializer = Serializer()
available_resources = {}
if api_name is None:
api_name = self.api_name
for name in sorted(self._registry.keys()):
available_resources[name] = {
'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs={
'api_name': api_name,
'resource_name': name,
}),
'schema': self._build_reverse_url("api_get_schema", kwargs={
'api_name': api_name,
'resource_name': name,
}),
}
desired_format = determine_format(request, serializer)
serialized = serializer.serialize(available_resources, desired_format)
return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
开发者ID:bmihelac,项目名称:django-tastypie,代码行数:26,代码来源:api.py
示例7: post_list
def post_list(self, request, **kwargs):
form = ItemImageCreationForm(data=request.POST,
files=request.FILES)
if form.is_valid():
if form.instance.item.store != request.user.store:
raise ImmediateHttpResponse(response=http.HttpForbidden())
images = form.save()
to_be_serialized = []
for image in images:
bundle = self.build_bundle(obj=image, request=request)
bundle = self.full_dehydrate(bundle)
to_be_serialized.append(bundle)
response = self.create_response(request, to_be_serialized)
response['x-frame-options'] = 'SAMEORIGIN'
return response
else:
desired_format = self.determine_format(request)
serialized = self.serialize(request,
{'errors': form.errors },
desired_format)
response = http.HttpBadRequest(
content=serialized,
content_type=build_content_type(desired_format))
response['x-frame-options'] = 'SAMEORIGIN'
raise ImmediateHttpResponse(response=response)
开发者ID:softak,项目名称:webfaction_demo,代码行数:27,代码来源:resources.py
示例8: validate_bundle_data
def validate_bundle_data(self, bundle, request, dataset):
"""
Perform additional validation that isn't possible with the Validation object.
"""
errors = {}
field_count = len(bundle.data["data"])
if dataset.initial_upload and not dataset.row_count:
errors["dataset"] = [
"Can not create or modify data for a dataset which has initial_upload, but has not completed the import process."
]
if dataset.column_schema is None:
errors["dataset"] = ["Can not create or modify data for a dataset without columns."]
else:
expected_field_count = len(dataset.column_schema)
if field_count != expected_field_count:
errors["data"] = ["Got %i data fields. Expected %i." % (field_count, expected_field_count)]
# Cribbed from is_valid()
if errors:
if request:
desired_format = self.determine_format(request)
else:
desired_format = self._meta.default_format
serialized = self.serialize(request, errors, desired_format)
response = http.HttpBadRequest(content=serialized, content_type=build_content_type(desired_format))
raise ImmediateHttpResponse(response=response)
开发者ID:newsapps,项目名称:panda,代码行数:31,代码来源:data.py
示例9: create_response
def create_response(self, request, data, response_class=HttpResponse,
**response_kwargs):
"""
Override the default create_response so we can pass the GET
parameters into options. This allows us to use GET parameters
to adjust how our serializers respond.
:param request: Django request object (Required)
:type request: :class:`django.http.HttpRequest`
:param data: The data to be worked on.
:type data: dict for multiple objects,
:class:`tastypie.bundle.Bundle` for a single object.
:param response_class: The class to utilize for the response.
:type response_class: :class:`django.http.HttpResponse` (Default)
:returns: :class:`django.http.HttpResponse` (Default)
"""
desired_format = self.determine_format(request)
options = request.GET.copy()
options['username'] = request.user.username
serialized = self.serialize(request, data, desired_format,
options=options)
return response_class(content=serialized,
content_type=build_content_type(desired_format),
**response_kwargs)
开发者ID:lakiw,项目名称:cripts,代码行数:25,代码来源:api.py
示例10: top_level
def top_level(self, request, api_name=None):
"""
A view that returns a serialized list of all resources registers
to the ``Api``. Useful for discovery.
"""
serializer = Serializer()
if api_name is None:
api_name = self.api_name
available_resources = dict((name, {
'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs={
'api_name': api_name,
'resource_name': name,
}),
'schema': self._build_reverse_url("api_get_schema", kwargs={
'api_name': api_name,
'resource_name': name,
}),
}) for name in self._registry.iterkeys())
desired_format = determine_format(request, serializer)
options = {}
if 'text/javascript' in desired_format:
callback = request.GET.get('callback', 'callback')
if not is_valid_jsonp_callback_value(callback):
raise BadRequest('JSONP callback name is invalid.')
options['callback'] = callback
serialized = serializer.serialize(available_resources, desired_format, options)
return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
开发者ID:georgemarshall,项目名称:django-tastypie,代码行数:34,代码来源:api.py
示例11: answerBadRequest
def answerBadRequest(self, request, error):
response_class = http.HttpBadRequest
desired_format = self.determine_format(request)
data = {'exception': error}
serialized = self.serialize(request, data, desired_format)
raise ImmediateHttpResponse(response=response_class(content=serialized,
content_type=build_content_type(desired_format)))
开发者ID:chembl,项目名称:chembl_webservices,代码行数:7,代码来源:compounds.py
示例12: is_valid
def is_valid(self, bundle, request=None):
"""Overridden to perform validation and persistence in one step"""
files = {}
# FIXME avatar file translation and persistence
avatar_data = bundle.data.get('avatar')
if avatar_data:
try:
files['avatar'] = SimpleUploadedFile(
avatar_data['name'], base64.b64decode(avatar_data['file']),
avatar_data.get("content_type", "application/octet-stream")
)
except Exception:
raise ImmediateHttpResponse(HttpBadRequest(content='ERROR PROCESSING IMAGE'))
# instantiate and validate the form
form = self._meta.validation.form_class(data=bundle.data, files=files)
if form.is_valid():
user = form.save()
# update request with the new user
request.user = user
request.user_created = True
# error handling
else:
if request:
desired_format = self.determine_format(request)
else:
desired_format = self._meta.default_format
serialized = self.serialize(request, form.errors, desired_format)
response = HttpBadRequest(content=serialized, content_type=build_content_type(desired_format))
raise ImmediateHttpResponse(response=response)
开发者ID:danbretl,项目名称:mid-tier,代码行数:34,代码来源:resources.py
示例13: build_response
def build_response(self):
from tastypie.serializers import Serializer
serializer = Serializer()
return HttpResponse(
content=serializer.serialize(self.response_data),
content_type=build_content_type('application/json')
)
开发者ID:WiserTogether,项目名称:django-tastypie,代码行数:7,代码来源:envelopes.py
示例14: top_level
def top_level(request):
available_resources = {}
apitop = reverse('ietf.api.top_level')
for name in sorted([ name for name, api in _api_list if len(api._registry) > 0 ]):
available_resources[name] = {
'list_endpoint': '%s/%s/' % (apitop, name),
}
serializer = Serializer()
desired_format = determine_format(request, serializer)
options = {}
if 'text/javascript' in desired_format:
callback = request.GET.get('callback', 'callback')
if not is_valid_jsonp_callback_value(callback):
raise BadRequest('JSONP callback name is invalid.')
options['callback'] = callback
serialized = serializer.serialize(available_resources, desired_format, options)
return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
开发者ID:wpjesus,项目名称:codematch,代码行数:25,代码来源:__init__.py
示例15: _create_response
def _create_response(res, request, data, response_class=HttpResponse, **response_kwargs):
"""
Overrides GeoNode's' own create_response() in BaseResources,
because get_list() may be skipping the dehydrate() call when
there are multiple objects to return.
"""
if isinstance(
data,
dict) and 'objects' in data and not isinstance(
data['objects'],
list):
logger.debug("Adding CREAD info to %d objects", len(data['objects']))
objects = list(data['objects'].values(*RESPONSE_VALUES))
for obj in objects:
_add_category_info(obj['id'], obj)
data['objects'] = objects
logger.debug("Added CREAD info")
desired_format = res.determine_format(request)
serialized = res.serialize(request, data, desired_format)
return response_class(
content=serialized,
content_type=build_content_type(desired_format),
**response_kwargs)
开发者ID:geosolutions-it,项目名称:geonode-cread,代码行数:26,代码来源:api.py
示例16: top_level
def top_level(self, request, api_name=None):
"""
A view that returns a serialized list of all DAS_sources in registers.
"""
sources = self._registry
if request.GET:
form = DASSourcesForm(request.GET)
if form.is_valid():
version = form.cleaned_data['version']
capability = form.cleaned_data['capability']
authority = form.cleaned_data['authority']
stype = form.cleaned_data['type']
organism = form.cleaned_data['organism']
else:
# :TODO raise exception
pass
sources = dict((key, value) for key, value in sources.items() if \
value._meta.version == int(version))
else: pass
if api_name is None:
api_name = self.api_name
#desired_format = determine_format(request, serializer)
desired_format = 'application/xml'
options = {}
response = HttpResponse(content = top_level_serializer(sources),
content_type=build_content_type(desired_format))
response = add_das_headers(response, self.version)
return response
开发者ID:KaiSmith,项目名称:biodas,代码行数:32,代码来源:biodas.py
示例17: create_response
def create_response(self, request, data, response_class=HttpResponse, response_objects=None, **response_kwargs):
"""
Extracts the common "which-format/serialize/return-response" cycle.
Mostly a useful shortcut/hook.
"""
# If an user does not have at least view permissions, he won't be able to see the resource at all.
filtered_objects_ids = None
if response_objects:
filtered_objects_ids = [
item.id
for item in response_objects
if request.user.has_perm("view_resourcebase", item.get_self_resource())
]
if isinstance(data, dict) and "objects" in data and not isinstance(data["objects"], list):
if filtered_objects_ids:
data["objects"] = [
x for x in list(self.format_objects(data["objects"])) if x["id"] in filtered_objects_ids
]
else:
data["objects"] = list(self.format_objects(data["objects"]))
desired_format = self.determine_format(request)
serialized = self.serialize(request, data, desired_format)
return response_class(content=serialized, content_type=build_content_type(desired_format), **response_kwargs)
开发者ID:kalxas,项目名称:geonode,代码行数:27,代码来源:resourcebase_api.py
示例18: top_level
def top_level(self, request, api_name=None):
"""This is the same method in the Api model with the execption
of the serializer used. This uses the SafeSerializer.
"""
serializer = SafeSerializer()
available_resources = {}
if api_name is None:
api_name = self.api_name
for name in sorted(self._registry.keys()):
available_resources[name] = {
'list_endpoint': self._build_reverse_url("api_dispatch_list", kwargs={
'api_name': api_name,
'resource_name': name,
}),
'schema': self._build_reverse_url("api_get_schema", kwargs={
'api_name': api_name,
'resource_name': name,
}),
}
desired_format = determine_format(request, serializer)
options = {}
if 'text/javascript' in desired_format:
callback = request.GET.get('callback', 'callback')
if not is_valid_jsonp_callback_value(callback):
raise BadRequest('JSONP callback name is invalid.')
options['callback'] = callback
serialized = serializer.serialize(available_resources, desired_format, options)
return HttpResponse(content=serialized, content_type=build_content_type(desired_format))
开发者ID:DeepInTheCode,项目名称:tendenci,代码行数:35,代码来源:api.py
示例19: raise_bad_request
def raise_bad_request(self, bundle, errors):
desired_format = self.determine_format(bundle.request)
serialized = self.serialize(bundle.request, errors, desired_format)
response = http.HttpBadRequest(
content=serialized,
content_type=build_content_type(desired_format))
raise ImmediateHttpResponse(response=response)
开发者ID:asfaltboy,项目名称:richard,代码行数:7,代码来源:api.py
示例20: create_response
def create_response(self, request, data, response_class=HttpResponse, **response_kwargs):
"""
Extracts the common "which-format/serialize/return-response" cycle.
Mostly a useful shortcut/hook.
"""
VALUES = [
# fields in the db
'id',
'uuid',
'title',
'abstract',
'csw_wkt_geometry',
'csw_type',
'distribution_description',
'distribution_url',
'owner_id',
'share_count',
'srid',
'category',
'supplemental_information',
'thumbnail_url',
'detail_url',
'rating',
]
if isinstance(data, dict) and 'objects' in data and not isinstance(data['objects'], list):
data['objects'] = list(data['objects'].values(*VALUES))
desired_format = self.determine_format(request)
serialized = self.serialize(request, data, desired_format)
return response_class(content=serialized, content_type=build_content_type(desired_format), **response_kwargs)
开发者ID:mishravikas,项目名称:geonode,代码行数:32,代码来源:resourcebase_api.py
注:本文中的tastypie.utils.mime.build_content_type函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论