本文整理汇总了Python中tastypie.utils.dict_strip_unicode_keys函数的典型用法代码示例。如果您正苦于以下问题:Python dict_strip_unicode_keys函数的具体用法?Python dict_strip_unicode_keys怎么用?Python dict_strip_unicode_keys使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了dict_strip_unicode_keys函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: post_list
def post_list(self, request, **kwargs):
deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
deserialized = self.alter_deserialized_list_data(request, deserialized)
bundle = self.build_bundle_custom_class(data=dict_strip_unicode_keys(deserialized), request=request)
self.is_valid(bundle, request)
updated_bundle = self.obj_create(bundle, request=request)
return HttpCreated(location=self.get_resource_uri(updated_bundle))
示例2: build_filters
def build_filters(self, filters=None):
if filters is None:
filters = {}
qs_filters = {}
if getattr(self._meta, 'queryset', None) is not None:
# Get the possible query terms from the current QuerySet.
query_terms = self._meta.queryset.query.query_terms
else:
query_terms = QUERY_TERMS
for filter_expr, value in filters.items():
filter_bits = filter_expr.split(LOOKUP_SEP)
field_name = filter_bits.pop(0)
filter_type = 'exact'
if not field_name in self.fields:
# It's not a field we know about. Move along citizen.
continue
if len(filter_bits) and filter_bits[-1] in query_terms:
filter_type = filter_bits.pop()
lookup_bits = self.check_filtering(field_name, filter_type, filter_bits)
value = self.filter_value_to_python(value, field_name, filters, filter_expr, filter_type)
db_field_name = LOOKUP_SEP.join(lookup_bits)
qs_filter = "%s%s%s" % (db_field_name, LOOKUP_SEP, filter_type)
qs_filters[qs_filter] = value
return dict_strip_unicode_keys(qs_filters)
示例3: update_temp_batches
def update_temp_batches(self, request, **kwargs):
'''Update a set of molecules into elasticsearch (used in ChemBio Hub to set the action field to ignore or new batch)'''
deserialized = self.deserialize(request, request.body, format=request.META.get(
'CONTENT_TYPE', 'application/json'))
deserialized = self.alter_deserialized_detail_data(
request, deserialized)
bundle = self.build_bundle(
data=dict_strip_unicode_keys(deserialized), request=request)
if bundle.obj.pk:
self.authorized_update_detail(
self.get_object_list(bundle.request), bundle)
else:
self.authorized_create_detail(
self.get_object_list(bundle.request), bundle)
multi_batch_id = bundle.data["multiplebatch"]
es_ready_updates = bundle.data["objects"]
index_name = elasticsearch_client.get_temp_index_name(
request.COOKIES[settings.SESSION_COOKIE_NAME], multi_batch_id)
elasticsearch_client.create_temporary_index(
es_ready_updates, index_name)
elasticsearch_client.get_action_totals(index_name, bundle.data)
return self.create_response(request, bundle, response_class=http.HttpAccepted)
示例4: multi_batch_custom_fields
def multi_batch_custom_fields(self, request, **kwargs):
'''change the structure column for an excel file'''
deserialized = self.deserialize(request, request.body, format=request.META.get(
'CONTENT_TYPE', 'application/json'))
deserialized = self.alter_deserialized_detail_data(
request, deserialized)
bundle = self.build_bundle(
data=dict_strip_unicode_keys(deserialized), request=request)
if bundle.obj.pk:
self.authorized_update_detail(
self.get_object_list(bundle.request), bundle)
else:
self.authorized_create_detail(
self.get_object_list(bundle.request), bundle)
id = bundle.data["multiplebatch"]
headers = bundle.data["headers"]
# structure_col = bundle.data.get("structure_col", None)
mb = CBHCompoundMultipleBatch.objects.get(pk=id)
processSmiles = False
# if structure_col and structure_col != mb.uploaded_data.get("structure_col", ""):
# processSmiles = True
index_name = elasticsearch_client.get_temp_index_name(request.COOKIES[settings.SESSION_COOKIE_NAME], mb.id)
elasticsearch_client.get_action_totals(index_name, bundle.data)
mb.uploaded_data = bundle.data
mb.save()
return self.create_response(request, bundle, response_class=http.HttpAccepted)
示例5: put_list
def put_list(self, request, **kwargs):
"""
Replaces a collection of resources with another collection.
Unlike the default put_list, this doesn't expect the new collections
to be wrapped in an 'objects' property.
"""
deserialized = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
deserialized = self.alter_deserialized_list_data(request, deserialized)
basic_bundle = self.build_bundle(request=request)
self.obj_delete_list_for_update(bundle=basic_bundle, **self.remove_api_resource_names(kwargs))
bundles_seen = []
for object_data in deserialized:
bundle = self.build_bundle(data=dict_strip_unicode_keys(object_data), request=request)
# Attempt to be transactional, deleting any previously created
# objects if validation fails.
try:
self.obj_create(bundle, request=request, **self.remove_api_resource_names(kwargs))
bundles_seen.append(bundle)
except ImmediateHttpResponse:
self.rollback(bundles_seen)
raise
if not self._meta.always_return_data:
return http.HttpNoContent()
else:
to_be_serialized = {}
to_be_serialized[self._meta.collection_name] = [self.full_dehydrate(bundle) for bundle in bundles_seen]
to_be_serialized = self.alter_list_data_to_serialize(request, to_be_serialized)
return self.create_response(request, to_be_serialized, response_class=http.HttpAccepted)
示例6: delete_detail
def delete_detail(self, request, **kwargs):
" Deleta um curso. "
# ETAPA 1 - Desserialização e validação dos dados recebidos
# ---------------------------------------------------------
course_id = course_id_decoder(kwargs['course_id_solaredx'])
deserialized = self.deserialize(request, request.body,
format=request.META.get('CONTENT_TYPE', 'application/json'))
deserialized = self.alter_deserialized_detail_data(
request, deserialized)
bundle = Bundle(data=dict_strip_unicode_keys(deserialized),
request=request)
bundle.data['course_id'] = course_id
validation = CleanedDataFormValidation(form_class=CourseDeleteForm)
validation_errors = validation.is_valid(bundle)
if validation_errors:
raise ImmediateHttpResponse(response=self.error_response(
bundle.request, validation_errors))
# ETAPA 2 - Efetuando operações no EDX
# ------------------------------------
course_delete(course_id)
return http.HttpNoContent()
示例7: post_list
def post_list(self, request, **kwargs):
deserialized = self.deserialize(request, request.body,
format=request.META.get('CONTENT_TYPE', 'application/json'))
deserialized = self.alter_deserialized_detail_data(request, deserialized)
data = dict_strip_unicode_keys(deserialized)
if 'objects' not in data:
raise BadRequest('Missing objects list.')
if not data.get('objects'):
raise BadRequest('Empty objects list.')
base_bundle = self.build_bundle(request=request)
supposed_objects = self.obj_get_list(bundle=base_bundle, **self.remove_api_resource_names(kwargs))
received_numbers = [obj['material_number'] for obj in data.get('objects')]
received_filters = {'material_number__in': received_numbers}
received_objects = self.get_object_list(request).filter(**received_filters)
tp_objects = [obj for obj in received_objects if obj in supposed_objects]
fn_objects = [obj for obj in received_objects if obj not in supposed_objects]
fp_objects = [obj for obj in supposed_objects if obj not in received_objects]
all_objects = {
'tp': tp_objects,
'fn': fn_objects,
'fp': fp_objects
}
for status, objects in all_objects.iteritems():
for obj in objects:
Log.create(
user=request.user,
luggage=obj,
status=status
)
return http.HttpCreated()
示例8: social_share
def social_share(self, request, **kwargs):
self.method_check(request, allowed=['post'])
self.is_authenticated(request)
try:
social_obj = self._meta.queryset._clone().get(pk=kwargs['pk'])
except self._meta.object_class.DoesNotExist:
return http.HttpNotFound()
deserialized = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
bundle = self.build_bundle(obj=social_obj, request=request, data=dict_strip_unicode_keys(deserialized))
try:
auth_result = self._meta.authorization.share_detail(None, bundle)
if not auth_result is True:
raise Unauthorized()
except Unauthorized as e:
self.unauthorized_result(e)
except AttributeError as e:
raise NotImplementedError("You must create a share_detail authorization method")
if 'provider' not in bundle.data:
return self.error_response(request, {"error": "No provider parameter given"}, response_class=http.HttpBadRequest)
try:
user_social_auth = UserSocialAuth.objects.get(user=bundle.request.user, provider=bundle.data['provider'])
# Inline import to remove recursive importing
from manticore_tastypie_social.manticore_tastypie_social.utils import post_social_media
post_social_media.delay(user_social_auth, bundle.obj.pk)
except UserSocialAuth.DoesNotExist:
return self.error_response(request, {"error": "User is not authenticated with %s" % bundle.data['provider']}, response_class=http.HttpBadRequest)
except BadRequest, e:
return self.error_response(request, {"error": e}, response_class=http.HttpBadRequest)
示例9: post_list
def post_list(self, request, **kwargs):
"""
Creates a new resource/object with the provided data.
Calls ``obj_create`` with the provided data and returns a response
with the new resource's location.
If a new resource is created, return ``HttpCreated`` (201 Created).
If ``Meta.always_return_data = True``, there will be a populated body
of serialized data.
"""
bundle = self.build_bundle(data=dict_strip_unicode_keys(request.POST), request=request)
bundle.files = request.FILES
updated_bundle = self.obj_create(bundle, **self.remove_api_resource_names(kwargs))
location = self.get_resource_uri(updated_bundle)
if not self._meta.always_return_data:
return http.HttpCreated(location=location)
else:
updated_bundle = self.full_dehydrate(updated_bundle)
updated_bundle = self.alter_detail_data_to_serialize(request, updated_bundle)
return self.create_upload_response(
request, updated_bundle, response_class=http.HttpCreated, location=location
)
示例10: build_related_resource
def build_related_resource(self, value):
"""
Used to ``hydrate`` the data provided. If just a URL is provided,
the related resource is attempted to be loaded. If a
dictionary-like structure is provided, a fresh resource is
created.
"""
self.fk_resource = self.to_class()
if isinstance(value, basestring):
# We got a URI. Load the object and assign it.
try:
obj = self.fk_resource.get_via_uri(value)
return self.fk_resource.full_dehydrate(obj)
except ObjectDoesNotExist:
raise ApiFieldError("Could not find the provided object via resource URI '%s'." % value)
elif hasattr(value, 'items'):
# Try to hydrate the data provided.
value = dict_strip_unicode_keys(value)
self.fk_bundle = Bundle(data=value)
try:
return self.fk_resource.obj_update(self.fk_bundle, **value)
except NotFound:
try:
# Attempt lookup by primary key
lookup_kwargs = dict((k, v) for k, v in value.iteritems() if getattr(self.fk_resource, k).unique)
if not lookup_kwargs:
raise NotFound
return self.fk_resource.obj_update(self.fk_bundle, **lookup_kwargs)
except NotFound:
return self.fk_resource.full_hydrate(self.fk_bundle)
except MultipleObjectsReturned:
return self.fk_resource.full_hydrate(self.fk_bundle)
else:
raise ApiFieldError("The '%s' field has was given data that was not a URI and not a dictionary-alike: %s." % (self.instance_name, value))
示例11: update_in_place
def update_in_place(self, request, original_bundle, new_data):
"""
Update the object in original_bundle in-place using new_data.
"""
updated = dict_strip_unicode_keys(new_data)
usable = {}
permitted_values = ['label', 'level', 'qualifiers']
for pv in permitted_values:
if pv in updated:
usable[pv] = updated[pv]
user = get_real_user_object(request.user)
# maybe should be pk, or uri not user object...
usable['labeller'] = user
original_bundle.data.update(**usable)
# Now we've got a bundle with the new data sitting in it and we're
# we're basically in the same spot as a PUT request. SO the rest of this
# function is cribbed from put_detail.
self.alter_deserialized_detail_data(request, original_bundle.data)
kwargs = {
self._meta.detail_uri_name: self.get_bundle_detail_data(original_bundle),
'request': request,
}
return self.obj_update(bundle=original_bundle, **kwargs)
示例12: _staff_or_instructor_delete_list
def _staff_or_instructor_delete_list(self, request, **kwargs):
# ETAPA 1 - Desserialização e validação dos dados recebidos
# ---------------------------------------------------------
course_id = course_id_decoder(kwargs['pk'])
staff_or_instructor = kwargs['staff_or_instructor']
deserialized = self.deserialize(request, request.body,
format=request.META.get('CONTENT_TYPE', 'application/json'))
deserialized = self.alter_deserialized_detail_data(
request, deserialized)
bundle = Bundle(data=dict_strip_unicode_keys(deserialized),
request=request)
if 'user_resource_uri' in bundle.data:
user_resource_uri = bundle.data['user_resource_uri']
bundle.data['course_id'] = course_id
bundle.data['staff_or_instructor'] = kwargs['staff_or_instructor']
validation = CleanedDataFormValidation(form_class=CourseDeleteUserForm)
validation_errors = validation.is_valid(bundle)
if validation_errors:
raise ImmediateHttpResponse(response=self.error_response(
bundle.request, validation_errors))
# ETAPA 2 - Efetuando operações no EDX
# ------------------------------------
username = user_resource_uri.split('/')[-2:-1][0]
course_remove_user(course_id, username, staff_or_instructor)
return http.HttpNoContent()
示例13: resource_from_data
def resource_from_data(self, fk_resource, data, request=None, related_obj=None, related_name=None):
"""
Given a dictionary-like structure is provided, a fresh related
resource is created using that data.
"""
# Try to hydrate the data provided.
data = dict_strip_unicode_keys(data)
fk_bundle = fk_resource.build_bundle(data=data, request=request)
if related_obj:
fk_bundle.related_obj = related_obj
fk_bundle.related_name = related_name
# We need to check to see if updates are allowed on the FK
# resource. If not, we'll just return a populated bundle instead
# of mistakenly updating something that should be read-only.
if not fk_resource.can_update():
return fk_resource.full_hydrate(fk_bundle)
try:
return fk_resource.obj_update(fk_bundle, skip_errors=True, **data)
except NotFound:
try:
# Attempt lookup by primary key
lookup_kwargs = dict((k, v) for k, v in data.iteritems() if getattr(fk_resource, k).unique)
if not lookup_kwargs:
raise NotFound()
return fk_resource.obj_update(fk_bundle, skip_errors=True, **lookup_kwargs)
except NotFound:
fk_bundle = fk_resource.full_hydrate(fk_bundle)
fk_resource.is_valid(fk_bundle, request)
return fk_bundle
except MultipleObjectsReturned:
return fk_resource.full_hydrate(fk_bundle)
示例14: post_list
def post_list(self, request, **kwargs):
# ETAPA 1 - Desserialização e validação dos dados recebidos
# ---------------------------------------------------------
deserialized = self.deserialize(request, request.body,
format=request.META.get('CONTENT_TYPE', 'application/json'))
deserialized = self.alter_deserialized_detail_data(
request, deserialized)
bundle = Bundle(data=dict_strip_unicode_keys(deserialized),
request=request)
validation = CleanedDataFormValidation(form_class=CourseCreateForm)
validation_errors = validation.is_valid(bundle)
if validation_errors:
raise ImmediateHttpResponse(response=self.error_response(
bundle.request, validation_errors))
# ETAPA 2 - Efetuando operações no EDX
# ------------------------------------
course_create(bundle.data)
# Adicionando ``resource_uri``
bundle.data['resource_uri'] = reverse('api_dispatch_detail',
kwargs={ 'api_name': CourseResource._meta.api_name,
'resource_name': CourseResource._meta.resource_name,
'course_id_solaredx': course_id_encoder(bundle.data['course_id'])})
return self.create_response(request, bundle,
response_class=http.HttpCreated)
示例15: patch_list
def patch_list(self, request=None, **kwargs):
"""
Exactly copied from https://github.com/toastdriven/django-tastypie/blob/v0.9.14/tastypie/resources.py#L1466
(BSD licensed) and modified to pass the kwargs to `obj_create` and support only create method
"""
request = convert_post_to_patch(request)
deserialized = self.deserialize(request, request.raw_post_data, format=request.META.get('CONTENT_TYPE', 'application/json'))
collection_name = self._meta.collection_name
if collection_name not in deserialized:
raise BadRequest("Invalid data sent: missing '%s'" % collection_name)
if len(deserialized[collection_name]) and 'put' not in self._meta.detail_allowed_methods:
raise ImmediateHttpResponse(response=http.HttpMethodNotAllowed())
bundles_seen = []
status = http.HttpAccepted
for data in deserialized[collection_name]:
data = self.alter_deserialized_detail_data(request, data)
bundle = self.build_bundle(data=dict_strip_unicode_keys(data), request=request)
try:
self.obj_create(bundle=bundle, **self.remove_api_resource_names(kwargs))
except AssertionError as ex:
status = http.HttpBadRequest
bundle.data['_id'] = ex.message
bundles_seen.append(bundle)
to_be_serialized = [bundle.data['_id'] for bundle in bundles_seen]
return self.create_response(request, to_be_serialized, response_class=status)