本文整理汇总了Python中tastypie.utils.mime.build_content_type函数的典型用法代码示例。如果您正苦于以下问题:Python build_content_type函数的具体用法?Python build_content_type怎么用?Python build_content_type使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了build_content_type函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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')
示例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)
示例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)
示例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))
示例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
示例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))
示例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)
示例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)
示例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)
示例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))
示例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)))
示例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)
示例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')
)
示例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))
示例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)