本文整理汇总了Python中django.db.transaction.atomic方法的典型用法代码示例。如果您正苦于以下问题:Python transaction.atomic方法的具体用法?Python transaction.atomic怎么用?Python transaction.atomic使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.transaction
的用法示例。
在下文中一共展示了transaction.atomic方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: save
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def save(self, *args, **kwargs):
"""Save the model."""
name_max_len = self._meta.get_field("name").max_length
if len(self.name) > name_max_len:
self.name = self.name[: (name_max_len - 3)] + "..."
for _ in range(MAX_SLUG_RETRIES):
try:
# Attempt to save the model. It may fail due to slug conflict.
with transaction.atomic():
super().save(*args, **kwargs)
break
except IntegrityError as error:
# Retry in case of slug conflicts.
if "{}_slug".format(self._meta.db_table) in error.args[0]:
self.slug = None
continue
raise
else:
raise IntegrityError(
"Maximum number of retries exceeded during slug generation"
)
示例2: _run
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def _run(anonymizer, objs):
values = {}
replacer_attr = tuple(r[0] for r in anonymizer.replacers)
for obj in objs.iterator():
retval = anonymizer.alter_object(obj)
if retval is False:
continue
values[obj.pk] = {attname: getattr(obj, attname) for attname in replacer_attr}
query = anonymizer.create_query(replacer_attr)
query_args = anonymizer.create_query_args(values, replacer_attr)
with transaction.atomic():
with connection.cursor() as cursor:
if connection.vendor == 'postgresql':
cursor.execute('SET CONSTRAINTS ALL DEFERRED')
cursor.executemany(query, query_args)
示例3: toggle_source_tag
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def toggle_source_tag(request, evidence_id, source_id):
"""Toggle source tag for the given source and redirect to the evidence detail page for the associated evidence."""
# May want to put in a sanity check here that source_id actually corresponds to evidence_id
# Inefficient to have to do the DB lookup before making a modification. May want to have the client pass in
# whether or not they're adding/removing the tag
if request.method == 'POST':
with transaction.atomic():
source = get_object_or_404(EvidenceSource, pk=source_id)
tag = EvidenceSourceTag.objects.get(tag_name=request.POST['tag'])
user_tag = AnalystSourceTag.objects.filter(source=source, tagger=request.user, tag=tag)
if user_tag.count() > 0:
user_tag.delete()
messages.success(request, _('Removed "{name}" tag from source.').format(name=tag.tag_name))
else:
AnalystSourceTag.objects.create(source=source, tagger=request.user, tag=tag)
messages.success(request, _('Added "{name}" tag to source.').format(name=tag.tag_name))
return HttpResponseRedirect(reverse('openach:evidence_detail', args=(evidence_id,)))
else:
# Redirect to the form where the user can toggle a source tag
return HttpResponseRedirect(reverse('openach:evidence_detail', args=(evidence_id,)))
示例4: create_team
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def create_team(request):
"""Return a team creation view, or handle the form submission."""
if request.method == 'POST':
form = TeamCreateForm(request.POST)
if form.is_valid():
with transaction.atomic():
team = form.save(commit=False)
team.owner = request.user
team.creator = request.user
team.save()
team.members.add(request.user)
team.save()
return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
else:
form = TeamCreateForm()
return render(request, 'teams/create_team.html', {'form': form})
示例5: create_reminder_on
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def create_reminder_on(self, date, start_date, end_date):
if start_date > date or date > end_date:
# not timely, so ignore
return
if self.reminder_type == 'ROLE':
roles = Role.objects_fresh.filter(unit=self.unit, role=self.role).select_related('person')
recipients = [r.person for r in roles]
elif self.reminder_type in ['PERS', 'INST']:
recipients = [self.person]
else:
raise ValueError()
for recip in recipients:
ident = '%s_%s_%s' % (self.slug, recip.userid_or_emplid(), date.isoformat())
# ident length: slug (50) + userid/emplid (9) + ISO date (10) + _ (2) <= 71
rm = ReminderMessage(reminder=self, sent=False, date=date, person=recip, ident=ident)
with transaction.atomic():
try:
rm.save()
except IntegrityError:
# already been created because we got IntegrityError on rm.ident
pass
示例6: deduplicate
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def deduplicate(cls, start_date=None, end_date=None, dry_run=False):
"""
Remove any EnrolmentHistory objects that aren't adding any new information.
"""
all_ehs = EnrolmentHistory.objects.order_by('offering', 'date')
if start_date:
all_ehs = all_ehs.filter(date__gte=start_date)
if end_date:
all_ehs = all_ehs.filter(date__lte=end_date)
for off_id, ehs in itertools.groupby(all_ehs, key=lambda eh: eh.offering_id):
# iterate through EnrolmentHistory for this offering and purge any "same as yesterday" entries
with transaction.atomic():
current = next(ehs)
for eh in ehs:
if current.is_dup(eh):
if not dry_run:
eh.delete()
else:
print('delete', eh)
else:
current = eh
示例7: safely_delete
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def safely_delete(self):
"""
Do the actions to safely "delete" the activity.
"""
with transaction.atomic():
# mangle name and short-name so instructors can delete and replace
i = 1
while True:
suffix = "__%04i" % (i)
existing = Activity.objects.filter(offering=self.offering, name=self.name+suffix).count() \
+ Activity.objects.filter(offering=self.offering, short_name=self.short_name+suffix).count()
if existing == 0:
break
i += 1
# update the activity
self.deleted = True
# Truncate the names if we need to since we are adding a 6 character suffix
self.name = self.name[:24] + suffix
self.short_name = self.short_name[:9] + suffix
self.slug = None
self.save()
示例8: post
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def post(self, request, cardid=None):
data = JSONDeserializer().deserialize(request.body)
if self.action == "update_card":
if data:
card = Card(data)
card.save()
return JSONResponse(card)
if self.action == "reorder_cards":
if "cards" in data and len(data["cards"]) > 0:
with transaction.atomic():
for card_data in data["cards"]:
card = models.CardModel.objects.get(pk=card_data["id"])
card.sortorder = card_data["sortorder"]
card.save()
return JSONResponse(data["cards"])
return HttpResponseNotFound()
示例9: delete
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def delete(self, request):
mobile_survey_id = None
try:
mobile_survey_id = JSONDeserializer().deserialize(request.body)["id"]
except Exception as e:
logger.exception(e)
try:
connection_error = False
with transaction.atomic():
if mobile_survey_id is not None:
ret = MobileSurvey.objects.get(pk=mobile_survey_id)
ret.delete()
return JSONResponse({"success": True})
except Exception as e:
if connection_error is False:
error_title = _("Unable to delete collector project")
if "strerror" in e and e.strerror == "Connection refused" or "Connection refused" in e:
error_message = _("Unable to connect to CouchDB")
else:
error_message = e.message
connection_error = JSONResponse({"success": False, "message": error_message, "title": error_title}, status=500)
return connection_error
return HttpResponseNotFound()
示例10: concept_value
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def concept_value(request):
if request.method == "DELETE":
data = JSONDeserializer().deserialize(request.body)
if data:
with transaction.atomic():
value = ConceptValue(data)
value.delete_index()
value.delete()
return JSONResponse(value)
if request.method == "GET":
valueid = request.GET.get("valueid")
value = models.Value.objects.get(pk=valueid)
return JSONResponse(value)
return HttpResponseNotFound
示例11: add_mapbox_layer
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def add_mapbox_layer(
self, layer_name=False, mapbox_json_path=False, layer_icon="fa fa-globe", is_basemap=False,
):
if layer_name is not False and mapbox_json_path is not False:
with open(mapbox_json_path) as data_file:
data = json.load(data_file)
with transaction.atomic():
for layer in data["layers"]:
if "source" in layer:
layer["source"] = layer["source"] + "-" + layer_name
for source_name, source_dict in data["sources"].items():
map_source = models.MapSource.objects.get_or_create(name=source_name + "-" + layer_name, source=source_dict)
map_layer = models.MapLayer(
name=layer_name, layerdefinitions=data["layers"], isoverlay=(not is_basemap), icon=layer_icon
)
try:
map_layer.save()
except IntegrityError as e:
print("Cannot save layer: {0} already exists".format(layer_name))
示例12: perform_withdrawal
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def perform_withdrawal(self):
with transaction.atomic():
# Set the SeasonPlayer as inactive
sp, _ = SeasonPlayer.objects.get_or_create(season=self.round.season, player=self.player)
sp.is_active = False
sp.save()
# Delete pairings and give opponents byes
for pairing in self.round.loneplayerpairing_set.filter(white=self.player):
PlayerBye.objects.create(round=self.round, player=pairing.black,
type='full-point-pairing-bye')
pairing.delete()
for pairing in self.round.loneplayerpairing_set.filter(black=self.player):
PlayerBye.objects.create(round=self.round, player=pairing.white,
type='full-point-pairing-bye')
pairing.delete()
示例13: set_data_location
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def set_data_location(apps, schema_editor):
"""Create DataLocation for each Data."""
Data = apps.get_model("flow", "Data")
DataLocation = apps.get_model("flow", "DataLocation")
for data in Data.objects.all():
if os.path.isdir(
os.path.join(settings.FLOW_EXECUTOR["DATA_DIR"], str(data.id))
):
with transaction.atomic():
# Manually set DataLocation id to preserve data directory.
data_location = DataLocation.objects.create(
id=data.id, subpath=str(data.id)
)
data_location.data.add(data)
# Increment DataLocation id's sequence
if DataLocation.objects.exists():
max_id = DataLocation.objects.order_by("id").last().id
with connection.cursor() as cursor:
cursor.execute(
"ALTER SEQUENCE flow_datalocation_id_seq RESTART WITH {};".format(
max_id + 1
)
)
示例14: delete_chunked
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def delete_chunked(queryset, chunk_size=500):
"""Chunked delete, which should be used if deleting many objects.
The reason why this method is needed is that deleting a lot of Data objects
requires Django to fetch all of them into memory (fast path is not used) and
this causes huge memory usage (and possibly OOM).
:param chunk_size: Optional chunk size
"""
while True:
# Discover primary key to limit the current chunk. This is required because delete
# cannot be called on a sliced queryset due to ordering requirement.
with transaction.atomic():
# Get offset of last item (needed because it may be less than the chunk size).
offset = queryset.order_by("pk")[:chunk_size].count()
if not offset:
break
# Fetch primary key of last item and use it to delete the chunk.
last_instance = queryset.order_by("pk")[offset - 1]
queryset.filter(pk__lte=last_instance.pk).delete()
示例15: process
# 需要导入模块: from django.db import transaction [as 别名]
# 或者: from django.db.transaction import atomic [as 别名]
def process(self, file_storage_id: Optional[int] = None):
"""Process objects to clean.
When file_storage is not None process only that object.
"""
logger.debug("Starting cleanup manager run")
qset = FileStorage.objects.all()
if file_storage_id is not None:
qset = qset.filter(pk=file_storage_id)
for file_storage in qset.filter(data__isnull=True).iterator():
# Set applicable storage locations to deleting.
StorageLocation.all_objects.unreferenced_locations().filter(
file_storage=file_storage
).update(status=StorageLocation.STATUS_DELETING)
with transaction.atomic():
q_set = FileStorage.objects.filter(
id=file_storage.id
).select_for_update(skip_locked=True)
# The FileStorage object is locked or deleted, skip processing.
if not q_set.exists():
continue
self._process_file_storage(q_set.first())
logger.debug("Finished cleanup manager run")