def close_task(self, task_result=""):
"""Close the task and save result."""
if task_result:
self.result = task_result
self.save()
try:
self.__lock(self.worker_id, new_state=TASK_STATES["CLOSED"], initial_states=(TASK_STATES["OPEN"], ))
except (MultipleObjectsReturned, ObjectDoesNotExist):
raise Exception("Cannot close task %d, state is %s" % (self.id, self.get_state_display()))
self.logs.gzip_logs()
python类MultipleObjectsReturned()的实例源码
def cancel_task(self, user=None, recursive=True):
"""Cancel the task."""
if user is not None and not user.is_superuser:
if self.owner.username != user.username:
raise Exception("You are not task owner or superuser.")
try:
self.__lock(self.worker_id, new_state=TASK_STATES["CANCELED"], initial_states=(TASK_STATES["FREE"], TASK_STATES["ASSIGNED"], TASK_STATES["OPEN"], TASK_STATES["CREATED"]))
except (MultipleObjectsReturned, ObjectDoesNotExist):
raise Exception("Cannot cancel task %d, state is %s" % (self.id, self.get_state_display()))
if recursive:
for task in self.subtasks():
task.cancel_task(recursive=True)
self.logs.gzip_logs()
def interrupt_task(self, recursive=True):
"""Set the task state to interrupted."""
try:
self.__lock(self.worker_id, new_state=TASK_STATES["INTERRUPTED"], initial_states=(TASK_STATES["OPEN"], ))
except (MultipleObjectsReturned, ObjectDoesNotExist):
raise Exception("Cannot interrupt task %d, state is %s" % (self.id, self.get_state_display()))
if recursive:
for task in self.subtasks():
task.interrupt_task(recursive=True)
self.logs.gzip_logs()
def timeout_task(self, recursive=True):
"""Set the task state to timeout."""
try:
self.__lock(self.worker_id, new_state=TASK_STATES["TIMEOUT"], initial_states=(TASK_STATES["OPEN"], ))
except (MultipleObjectsReturned, ObjectDoesNotExist):
raise Exception("Cannot interrupt task %d, state is %s" % (self.id, self.get_state_display()))
if recursive:
for task in self.subtasks():
task.interrupt_task(recursive=True)
self.logs.gzip_logs()
def fail_task(self, task_result=""):
"""Fail this task and save result."""
if task_result:
self.result = task_result
self.save()
try:
self.__lock(self.worker_id, new_state=TASK_STATES["FAILED"], initial_states=(TASK_STATES["OPEN"], ))
except (MultipleObjectsReturned, ObjectDoesNotExist):
raise Exception("Cannot fail task %i, state is %s" % (self.id, self.get_state_display()))
self.logs.gzip_logs()
def get_gift_num(self, gift):
try:
tmp = IncludedGift.objects.get(gift_set=self, gift=gift)
return tmp.count
except (IncludedGift.DoesNotExist, MultipleObjectsReturned):
return 0
def get_exclusive_user(self, event):
if self.inventory.multiple_assignments:
return None
try:
return UsedItem.objects.get(item=self, helper__event=event,
timestamp_returned=None).helper
except UsedItem.DoesNotExist:
raise NotAssigned
except MultipleObjectsReturned:
raise InvalidMultipleAssignment()
def from_schedule(cls, schedule):
spec = {'event': schedule.event,
'latitude': schedule.lat,
'longitude': schedule.lon}
try:
return cls.objects.get(**spec)
except cls.DoesNotExist:
return cls(**spec)
except MultipleObjectsReturned:
cls.objects.filter(**spec).delete()
return cls(**spec)
def from_schedule(cls, schedule, period=SECONDS):
every = max(schedule.run_every.total_seconds(), 0)
try:
return cls.objects.get(every=every, period=period)
except cls.DoesNotExist:
return cls(every=every, period=period)
except MultipleObjectsReturned:
cls.objects.filter(every=every, period=period).delete()
return cls(every=every, period=period)
def from_schedule(cls, schedule):
spec = {'minute': schedule._orig_minute,
'hour': schedule._orig_hour,
'day_of_week': schedule._orig_day_of_week,
'day_of_month': schedule._orig_day_of_month,
'month_of_year': schedule._orig_month_of_year}
try:
return cls.objects.get(**spec)
except cls.DoesNotExist:
return cls(**spec)
except MultipleObjectsReturned:
cls.objects.filter(**spec).delete()
return cls(**spec)
def put_detail(self, request, **kwargs):
"""
Either updates an existing resource or creates a new one with the
provided data.
Calls ``obj_update`` with the provided data first, but falls back to
``obj_create`` if the object does not already exist.
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.
If an existing resource is modified and
``Meta.always_return_data = False`` (default), return ``HttpNoContent``
(204 No Content).
If an existing resource is modified and
``Meta.always_return_data = True``, return ``HttpAccepted`` (200
OK).
"""
if django.VERSION >= (1, 4):
body = request.body
else:
body = request.raw_post_data
deserialized = self.deserialize(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)
try:
updated_bundle = self.obj_update(bundle=bundle, **self.remove_api_resource_names(kwargs))
if not self._meta.always_return_data:
return http.HttpNoContent()
else:
updated_bundle = self.full_dehydrate(updated_bundle)
updated_bundle = self.alter_detail_data_to_serialize(request, updated_bundle)
return self.create_response(request, updated_bundle)
except (NotFound, MultipleObjectsReturned):
updated_bundle = self.obj_create(bundle=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_response(request, updated_bundle, response_class=http.HttpCreated, location=location)
def patch_detail(self, request, **kwargs):
"""
Updates a resource in-place.
Calls ``obj_update``.
If the resource is updated, return ``HttpAccepted`` (202 Accepted).
If the resource did not exist, return ``HttpNotFound`` (404 Not Found).
"""
request = convert_post_to_patch(request)
basic_bundle = self.build_bundle(request=request)
# We want to be able to validate the update, but we can't just pass
# the partial data into the validator since all data needs to be
# present. Instead, we basically simulate a PUT by pulling out the
# original data and updating it in-place.
# So first pull out the original object. This is essentially
# ``get_detail``.
try:
obj = self.cached_obj_get(bundle=basic_bundle, **self.remove_api_resource_names(kwargs))
except ObjectDoesNotExist:
return http.HttpNotFound()
except MultipleObjectsReturned:
return http.HttpMultipleChoices("More than one resource is found at this URI.")
bundle = self.build_bundle(obj=obj, request=request)
bundle = self.full_dehydrate(bundle)
bundle = self.alter_detail_data_to_serialize(request, bundle)
# Now update the bundle in-place.
if django.VERSION >= (1, 4):
body = request.body
else:
body = request.raw_post_data
deserialized = self.deserialize(request, body, format=request.META.get('CONTENT_TYPE', 'application/json'))
self.update_in_place(request, bundle, deserialized)
if not self._meta.always_return_data:
return http.HttpAccepted()
else:
bundle = self.full_dehydrate(bundle)
bundle = self.alter_detail_data_to_serialize(request, bundle)
return self.create_response(request, bundle, response_class=http.HttpAccepted)