本文整理汇总了Python中tastypie.bundle.Bundle类的典型用法代码示例。如果您正苦于以下问题:Python Bundle类的具体用法?Python Bundle怎么用?Python Bundle使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Bundle类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: dehydrate
def dehydrate(self, bundle, for_list=True):
foreign_obj = None
if callable(self.attribute):
previous_obj = bundle.obj
foreign_obj = self.attribute(bundle)
elif isinstance(self.attribute, six.string_types):
foreign_obj = bundle.obj
for attr in self._attrs:
previous_obj = foreign_obj
try:
foreign_obj = getattr(foreign_obj, attr, None)
except ObjectDoesNotExist:
foreign_obj = None
if not foreign_obj:
if not self.null:
if callable(self.attribute):
raise ApiFieldError("The related resource for resource %s could not be found." % (previous_obj))
else:
raise ApiFieldError("The model '%r' has an empty attribute '%s' and doesn't allow a null value." % (previous_obj, attr))
return None
fk_resource = self.get_related_resource(foreign_obj)
fk_bundle = Bundle(obj=foreign_obj, request=bundle.request)
fk_bundle.fields = getattr(bundle, 'fields', None)
depth = getattr(bundle, 'depth', None)
if depth is None:
depth = self.max_depth
if depth is not None:
fk_bundle.depth = depth - 1
return self.dehydrate_related(fk_bundle, fk_resource, for_list=for_list)
示例2: _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()
示例3: 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)
示例4: 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()
示例5: full_dehydrate
def full_dehydrate(self, obj):
"""
Given an object instance, extract the information from it to populate
the resource.
"""
bundle = Bundle(obj=obj)
# Dehydrate each field.
for field_name, field_object in self.fields.items():
# A touch leaky but it makes URI resolution work.
if isinstance(field_object, RelatedField):
field_object.api_name = self._meta.api_name
field_object.resource_name = self._meta.resource_name
bundle.data[field_name] = field_object.dehydrate(bundle)
# Run through optional overrides.
for field_name, field_object in self.fields.items():
method = getattr(self, "dehydrate_%s" % field_name, None)
if method:
bundle.data[field_name] = method(bundle)
bundle = self.dehydrate(bundle)
return bundle
示例6: save
def save(self):
""" Implements the save method so this form can be used in regular django views.
It does the same validation that it usually does for the API, but instead of
creating a JSON response, it just creates the object and then returns it.
"""
assert hasattr(self, 'request')
assert self.type == 'create' or self.type == 'update'
# Use the form's cleaned_data to create a bundle
bundle = Bundle()
bundle.data = self.cleaned_data
if hasattr(self, 'request'):
bundle.request = self.request
if hasattr(self, 'instance'):
bundle.obj = self.instance
# Use the resource's methods to save the bundle
self.resource.request = self.request
if self.type == 'create':
bundle = self.resource.obj_create(bundle)
elif self.type == 'update':
assert self.request != None
assert bundle.obj != None
bundle = self.resource.obj_update(bundle, self.request)
# Return the object
return bundle.obj
示例7: dehydrate
def dehydrate(self, bundle):
foreign_obj = None
if isinstance(self.attribute, basestring):
attrs = self.attribute.split('__')
foreign_obj = bundle.obj
for attr in attrs:
previous_obj = foreign_obj
try:
foreign_obj = getattr(foreign_obj, attr, None)
except ObjectDoesNotExist:
foreign_obj = None
elif callable(self.attribute):
foreign_obj = self.attribute(bundle)
if not foreign_obj:
if not self.null:
raise ApiFieldError("The model '%r' has an empty attribute '%s' and doesn't allow a null value." % (previous_obj, attr))
return None
self.fk_resource = self.get_related_resource(foreign_obj)
fk_bundle = Bundle(obj=foreign_obj, request=bundle.request)
depth = getattr(bundle, 'depth', None)
if depth is None:
depth = self.max_depth
if depth is not None:
fk_bundle.depth = depth - 1
return self.dehydrate_related(fk_bundle, self.fk_resource)
示例8: dehydrate
def dehydrate(self, bundle, for_list=False):
print 1
if not bundle.obj or not bundle.obj.pk:
print 2
if not self.null:
raise ApiFieldError("The model '%r' does not have a primary key and can not be d in a ToMany context." % bundle.obj)
return []
if not getattr(bundle.obj, self.attribute):
print 3
if not self.null:
raise ApiFieldError("The model '%r' has an empty attribute '%s' and doesn't all a null value." % (bundle.obj, self.attribute))
return []
self.m2m_resources = []
m2m_dehydrated = []
# TODO: Also model-specific and leaky. Relies on there being a
# ``Manager`` there.
# NOTE: only had to remove .all()
print 4
for m2m in getattr(bundle.obj, self.attribute):
print 5
m2m_resource = self.get_related_resource(m2m)
m2m_bundle = Bundle(obj=m2m)
self.m2m_resources.append(m2m_resource)
# youhou, dirty hack again baby!
m2m_bundle.obj = type("DummyContainer", (object,), {'pk': m2m_bundle.obj})
m2m_dehydrated.append(self.dehydrate_related(m2m_bundle, m2m_resource))
return m2m_dehydrated
示例9: hydrate_lang
def hydrate_lang(self, bundle):
translated_bundle = Bundle()
translation_resource = I4pProjectTranslationEditResource()
for language_code, language_data in bundle.data["lang"].iteritems():
if language_code not in dict(LANGUAGES):
continue
translated_bundle.data = language_data
translated_bundle.obj = bundle.obj.translate(language_code)
translation_resource.obj_create(translated_bundle)
return bundle
示例10: process
def process(self):
# Apply envelopes only to HttpResponse returning JSON
is_eligible = False
if self.response is None and self.content is None:
is_eligible = False
logger.warning('Envelope initialized without response or raw content')
elif self.content and isinstance(self.content, dict):
if not(set(['meta', 'data']) < set(self.content.keys())):
is_eligible = True
else:
logger.warning('Attempting to envelope response that is already enveloped')
if is_eligible:
self.update_data(self.content)
elif self.response:
content_type = self.response._headers.get('content-type', None)
if content_type is not None and 'json' in content_type[1]:
original_response_content = json.loads(self.response.content)
if 'meta' not in original_response_content or 'data' not in original_response_content:
is_eligible = True
else:
logger.warning('Attempting to envelope response that is already enveloped')
if is_eligible:
# Load data depending on whether its a list of object or a single object
if 'meta' in original_response_content and 'objects' in original_response_content:
self.response_data['meta']['pagination'] = original_response_content['meta']
self.update_data(original_response_content['objects'])
else:
self.update_data(original_response_content)
else:
logger.warning('Response or data can not be enveloped')
if is_eligible:
# Load form errors if present
if self.validation is not None and isinstance(self.validation, FormValidation):
bundle = Bundle()
bundle.data = self.response_data['data']
form_errors = self.validation.is_valid(bundle)
if form_errors:
self.add_errors('form', form_errors)
self.set_status(400)
self.is_modified = True
else:
logger.warning('Response or data can not be enveloped')
self.is_processed = True
示例11: test_hydrate
def test_hydrate(self):
note = Note.objects.get(pk=1)
bundle = Bundle(obj=note)
# With no value, default or nullable, we should get an ``ApiFieldError``.
field_1 = ApiField()
field_1.instance_name = 'api'
self.assertRaises(ApiFieldError, field_1.hydrate, bundle)
# The default.
field_2 = ApiField(default='foo')
field_2.instance_name = 'api'
self.assertEqual(field_2.hydrate(bundle), 'foo')
# The callable default.
def foo():
return 'bar'
field_3 = ApiField(default=foo)
field_3.instance_name = 'api'
self.assertEqual(field_3.hydrate(bundle), 'bar')
# The nullable case.
field_4 = ApiField(null=True)
field_4.instance_name = 'api'
self.assertEqual(field_4.hydrate(bundle), None)
# The readonly case.
field_5 = ApiField(readonly=True)
field_5.instance_name = 'api'
bundle.data['api'] = 'abcdef'
self.assertEqual(field_5.hydrate(bundle), None)
# A real, live attribute!
field_6 = ApiField(attribute='title')
field_6.instance_name = 'api'
bundle.data['api'] = note.title
self.assertEqual(field_6.hydrate(bundle), u'First Post!')
# Make sure it uses attribute when there's no data
field_7 = ApiField(attribute='title')
field_7.instance_name = 'notinbundle'
self.assertEqual(field_7.hydrate(bundle), u'First Post!')
# Make sure it falls back to instance name if there is no attribute
field_8 = ApiField()
field_8.instance_name = 'title'
self.assertEqual(field_7.hydrate(bundle), u'First Post!')
示例12: generate_api_key
def generate_api_key(request, userid):
api_key = None
try:
api_key = ApiKey.objects.get(user=userid)
api_key.key = api_key.generate_key()
api_key.save()
except ApiKey.DoesNotExist:
api_key = ApiKey.objects.create(user=userid)
# return created key info
if api_key is not None:
bun = Bundle()
bun.data['userid'] = userid
bun.data['api_key'] = api_key.key
ur = api.resources.UserResource()
return HttpResponse(status=201, content=ur.serialize(request, bun, ur.determine_format(request)))
示例13: delete_detail
def delete_detail(self, request, **kwargs):
from freenasUI.freeadmin.navtree import navtree
bundle = Bundle(request=request)
bundle.obj = self.obj_get(bundle=bundle, **self.remove_api_resource_names(kwargs))
if bundle.obj._meta.model._admin.delete_form:
deserialized = self.deserialize(
request,
request.body or '{}',
format=request.META.get('CONTENT_TYPE', 'application/json'),
)
Form = __import__(
f'{bundle.obj._meta.app_label}.forms',
globals(),
locals(),
[bundle.obj._meta.model._admin.delete_form],
0,
)
Form = getattr(Form, bundle.obj._meta.model._admin.delete_form)
form = Form(data=deserialized, instance=bundle.obj)
if not form.is_valid():
raise ImmediateHttpResponse(
response=self.error_response(request, form.errors)
)
# Grab the form to call delete on same as in freeadmin
m = bundle.obj._meta.model
mf = None
if not isinstance(navtree._modelforms[m], dict):
mf = navtree._modelforms[m]
else:
if mf is None:
try:
mf = navtree._modelforms[m][m._admin.edit_modelform]
except Exception:
mf = list(navtree._modelforms[m].values())[-1]
else:
mf = navtree._modelforms[m][mf]
if mf:
form = mf(instance=bundle.obj)
form.delete()
return http.HttpNoContent()
else:
return super().delete_detail(request, **kwargs)
示例14: test_hydrate
def test_hydrate(self):
note = Note()
bundle = Bundle(obj=note)
# With no value or nullable, we should get an ``ApiFieldError``.
field_1 = ForeignKey(UserResource, 'author')
self.assertRaises(ApiFieldError, field_1.hydrate, bundle)
note = Note.objects.get(pk=1)
bundle = Bundle(obj=note)
# The nullable case.
field_2 = ForeignKey(UserResource, 'author', null=True)
field_2.instance_name = 'fk'
bundle.data['fk'] = None
self.assertEqual(field_2.hydrate(bundle), None)
# Wrong resource URI.
field_3 = ForeignKey(UserResource, 'author')
field_3.instance_name = 'fk'
bundle.data['fk'] = '/api/v1/users/abc/'
self.assertRaises(NotFound, field_3.hydrate, bundle)
# A real, live attribute!
field_4 = ForeignKey(UserResource, 'author')
field_4.instance_name = 'fk'
bundle.data['fk'] = '/api/v1/users/1/'
fk_bundle = field_4.hydrate(bundle)
self.assertEqual(fk_bundle.data['username'], u'johndoe')
self.assertEqual(fk_bundle.data['email'], u'[email protected]')
self.assertEqual(fk_bundle.obj.username, u'johndoe')
self.assertEqual(fk_bundle.obj.email, u'[email protected]')
field_5 = ForeignKey(UserResource, 'author')
field_5.instance_name = 'fk'
bundle.data['fk'] = {
'username': u'mistersmith',
'email': u'[email protected]',
'password': u'foobar',
}
fk_bundle = field_5.hydrate(bundle)
self.assertEqual(fk_bundle.data['username'], u'mistersmith')
self.assertEqual(fk_bundle.data['email'], u'[email protected]')
self.assertEqual(fk_bundle.obj.username, u'mistersmith')
self.assertEqual(fk_bundle.obj.email, u'[email protected]')
# Regression - Make sure Unicode keys get converted to regular strings
# so that we can **kwargs them.
field_6 = ForeignKey(UserResource, 'author')
field_6.instance_name = 'fk'
bundle.data['fk'] = {
u'username': u'mistersmith',
u'email': u'[email protected]',
u'password': u'foobar',
}
fk_bundle = field_6.hydrate(bundle)
self.assertEqual(fk_bundle.data['username'], u'mistersmith')
self.assertEqual(fk_bundle.data['email'], u'[email protected]')
self.assertEqual(fk_bundle.obj.username, u'mistersmith')
self.assertEqual(fk_bundle.obj.email, u'[email protected]')
示例15: dehydrate
def dehydrate(self, bundle):
try:
foreign_obj = getattr(bundle.obj, self.attribute)
except ObjectDoesNotExist:
foreign_obj = None
if not foreign_obj:
if not self.null:
raise ApiFieldError("The model '%r' has an empty attribute '%s' and doesn't allow a null value." % (bundle.obj, self.attribute))
return None
self.fk_resource = self.get_related_resource(foreign_obj)
fk_bundle = Bundle(obj=foreign_obj, request=bundle.request)
# add by zzgvh
if getattr(bundle, 'related_info', False):
fk_bundle.related_info = bundle_related_data_info_factory(parent_bundle=bundle)
# end add
return self.dehydrate_related(fk_bundle, self.fk_resource)