本文整理匯總了Python中google.appengine.ext.ndb.transactional方法的典型用法代碼示例。如果您正苦於以下問題:Python ndb.transactional方法的具體用法?Python ndb.transactional怎麽用?Python ndb.transactional使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類google.appengine.ext.ndb
的用法示例。
在下文中一共展示了ndb.transactional方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: add_to_queue
# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import transactional [as 別名]
def add_to_queue(self, url=None, target_state='queued', countdown=0):
"""
Adds job to task queue and transactionally updates state to 'queued'
and saves job.
Does nothing if state is not 'scheduled'.
"""
if self.state != 'scheduled':
logging.warn('tried to add job {} with state {}, to queue, '
'doing nothing'.format(self.key, self.state))
return
if url is None:
url = self.queue_url
logging.debug(u'scheduling job {} for {}'.format(self.key,
self.user_email))
taskqueue.add(url=url,
payload=json.dumps({'key': self.key.urlsafe()}),
queue_name=self.queue_name,
countdown=countdown,
transactional=True)
self.state = target_state
self.put()
示例2: add_note
# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import transactional [as 別名]
def add_note():
page_name = flask.request.args.get('page_name', 'default')
note_title = flask.request.form['note_title']
note_text = flask.request.form['note_text']
parent = parent_key(page_name)
choice = random.randint(0, 1)
if choice == 0:
# Use transactional function
# [START calling]
note_key = ndb.Key(Note, note_title, parent=parent)
note = Note(key=note_key, content=note_text)
# [END calling]
if pick_random_insert(note_key, note) is False:
return ('Already there<br><a href="%s">Return</a>'
% flask.url_for('main_page', page_name=page_name))
return flask.redirect(flask.url_for('main_page', page_name=page_name))
elif choice == 1:
# Use get_or_insert, which is transactional
note = Note.get_or_insert(note_title, parent=parent, content=note_text)
if note.content != note_text:
return ('Already there<br><a href="%s">Return</a>'
% flask.url_for('main_page', page_name=page_name))
return flask.redirect(flask.url_for('main_page', page_name=page_name))
示例3: enqueue_process_change_task
# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import transactional [as 別名]
def enqueue_process_change_task(auth_db_rev):
"""Transactionally adds a call to 'process_change' to the task queue.
Pins the task to currently executing version of BACKEND_MODULE module
(defined in config.py).
Added as AuthDB commit callback in get_backend_routes() below.
"""
assert ndb.in_transaction()
conf = config.ensure_configured()
try:
# Pin the task to the module and version.
taskqueue.add(
url='/internal/auth/taskqueue/process-change/%d' % auth_db_rev,
queue_name=conf.PROCESS_CHANGE_TASK_QUEUE,
headers={'Host': modules.get_hostname(module=conf.BACKEND_MODULE)},
transactional=True)
except Exception as e:
logging.error(
'Problem adding "process-change" task to the task queue (%s): %s',
e.__class__.__name__, e)
raise
示例4: authorize_reader
# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import transactional [as 別名]
def authorize_reader(email):
"""Allows the given user to fetch AuthDB Google Storage file.
Raises:
Error if reached GCS ACL entries limit or GCS call fails.
"""
@ndb.transactional
def add_if_necessary():
readers = _list_authorized_readers()
if email in readers:
return
if len(readers) >= _MAX_ACL_ENTRIES:
raise Error('Reached the soft limit on GCS ACL entries')
reader = AuthDBReader(
key=_auth_db_reader_key(email),
authorized_at=utils.utcnow())
reader.put()
add_if_necessary()
_update_gcs_acls()
示例5: AdoptProjects
# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import transactional [as 別名]
def AdoptProjects(dst_user_id, src_user_id):
"""Transfer project ownership to a new user."""
@ndb.transactional(xg=True)
def _AdoptProject(project_key, dst_user_key, src_user_key):
prj, dst_user, src_user = ndb.get_multi([project_key, dst_user_key,
src_user_key])
if project_key not in src_user.projects:
# another concurrent request and transaction beat us to it
return
src_user.projects.remove(project_key)
dst_user.projects.append(project_key)
prj.owner = dst_user_key.id()
prj.writers.remove(src_user_key.id())
prj.writers.append(dst_user_key.id())
ndb.put_multi([prj, dst_user, src_user])
src_user = GetUser(src_user_id)
if not src_user or not src_user.projects:
return
dst_user = GetOrCreateUser(dst_user_id)
for project_key in src_user.projects:
# slow, but transactionable
_AdoptProject(project_key, dst_user.key, src_user.key)
示例6: testDoInsertRow_Repeats_InsideTransaction
# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import transactional [as 別名]
def testDoInsertRow_Repeats_InsideTransaction(self, mock_get):
attempts = 3
mock_get.side_effect = [None] + [True] * (attempts - 1)
@ndb.transactional
def _RepeatedInserts():
for _ in xrange(attempts):
now = datetime.datetime.utcnow()
row_values = {'aaa': True, 'bbb': 4, 'timestamp': now}
TEST_TABLE._DoInsertRow(**row_values)
_RepeatedInserts()
self.assertEqual(1, self.mock_send_to_bigquery.call_count)
self.assertTrue(tables.monitoring.row_insertions.Success.called)
self.mock_send_to_bigquery.reset_mock()
示例7: Approve
# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import transactional [as 別名]
def Approve(exm_key, details=None):
"""Transitions an Exemption to the APPROVED state.
Args:
exm_key: The NDB Key of the Exemption entity.
details: Optional list of strings describing the rationale.
Raises:
InvalidStateChangeError: If the desired state cannot be transitioned to from
the current state.
"""
host_id = exemption_models.Exemption.GetHostId(exm_key)
logging.info('Approving Exemption for Host %s', host_id)
# Verify that the desired state change is still valid.
exm = exm_key.get()
if not exm.CanChangeToState(_STATE.APPROVED):
raise InvalidStateChangeError('%s to %s' % (exm.state, _STATE.APPROVED))
_DisableLockdown(exm_key)
exemption_models.Exemption.ChangeState(
exm_key, _STATE.APPROVED, details=details)
notify.DeferUpdateEmail(
exm_key, _STATE.APPROVED, details=details, transactional=True)
示例8: Deny
# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import transactional [as 別名]
def Deny(exm_key, details=None):
"""Transitions an Exemption to the DENIED state.
Args:
exm_key: The NDB Key of the Exemption entity.
details: Optional list of strings describing the rationale.
Raises:
InvalidStateChangeError: If the desired state cannot be transitioned to from
the current state.
"""
host_id = exemption_models.Exemption.GetHostId(exm_key)
logging.info('Denying Exemption for Host %s', host_id)
# Verify that the desired state change is still valid.
exm = exm_key.get()
if not exm.CanChangeToState(_STATE.DENIED):
raise InvalidStateChangeError('%s to %s' % (exm.state, _STATE.DENIED))
exemption_models.Exemption.ChangeState(
exm_key, _STATE.DENIED, details=details)
notify.DeferUpdateEmail(
exm_key, _STATE.DENIED, details=details, transactional=True)
示例9: Expire
# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import transactional [as 別名]
def Expire(exm_key):
"""Transitions an Exemption to the EXPIRED state.
Args:
exm_key: The NDB Key of the Exemption entity.
Raises:
InvalidStateChangeError: If the desired state cannot be transitioned to from
the current state.
"""
host_id = exemption_models.Exemption.GetHostId(exm_key)
logging.info('Expiring Exemption for Host %s', host_id)
# Verify that the desired state change is still valid.
exm = exm_key.get()
if not exm.CanChangeToState(_STATE.EXPIRED):
raise InvalidStateChangeError('%s to %s' % (exm.state, _STATE.EXPIRED))
_EnableLockdown(exm_key)
exemption_models.Exemption.ChangeState(exm_key, _STATE.EXPIRED)
notify.DeferUpdateEmail(exm_key, _STATE.EXPIRED, transactional=True)
示例10: Revoke
# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import transactional [as 別名]
def Revoke(exm_key, details):
"""Transitions an Exemption to the REVOKED state.
Args:
exm_key: The NDB Key of the Exemption entity.
details: List of strings describing the rationale.
Raises:
InvalidStateChangeError: If the desired state cannot be transitioned to from
the current state.
"""
host_id = exemption_models.Exemption.GetHostId(exm_key)
logging.info('Revoking Exemption for Host %s', host_id)
# Verify that the desired state change is still valid.
exm = exm_key.get()
if not exm.CanChangeToState(_STATE.REVOKED):
raise InvalidStateChangeError('%s to %s' % (exm.state, _STATE.REVOKED))
_EnableLockdown(exm_key)
exemption_models.Exemption.ChangeState(
exm_key, _STATE.REVOKED, details=details)
notify.DeferUpdateEmail(
exm_key, _STATE.REVOKED, details=details, transactional=True)
示例11: stream_rows_wrapper
# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import transactional [as 別名]
def stream_rows_wrapper(self):
"""Streams rows ensuring that it is transactional."""
deferred.defer(
bigquery_row_model.BigQueryRow.stream_rows, _transactional=True)
示例12: post
# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import transactional [as 別名]
def post(self):
amount = int(self.request.get('amount'))
# This task should run at most once per second because of the datastore
# transaction write throughput.
@ndb.transactional
def update_counter():
counter = Counter.get_or_insert(COUNTER_KEY, count=0)
counter.count += amount
counter.put()
update_counter()
示例13: insert_if_absent_taskq
# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import transactional [as 別名]
def insert_if_absent_taskq(note_key, note):
taskqueue.add(url=flask.url_for('taskq_worker'), transactional=True)
# do insert
# [END taskq]
fetch = note_key.get()
if fetch is None:
note.put()
return True
return False
示例14: store_and_enqueue_verify_task
# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import transactional [as 別名]
def store_and_enqueue_verify_task(entry, task_queue_host):
entry.put()
taskqueue.add(
url='/internal/taskqueue/verify/%s' % entry.key.id(),
params={'req': os.environ['REQUEST_LOG_ID']},
queue_name='verify',
headers={'Host': task_queue_host},
transactional=True,
)
示例15: bootstrap
# 需要導入模塊: from google.appengine.ext import ndb [as 別名]
# 或者: from google.appengine.ext.ndb import transactional [as 別名]
def bootstrap(cls, name, length=32):
"""Creates a secret if it doesn't exist yet.
Args:
name: name of the secret.
length: length of the secret to generate if secret doesn't exist yet.
Returns:
Instance of AuthSecret (creating it if necessary) with random secret set.
"""
# Note that 'get_or_insert' is a bad fit here. With 'get_or_insert' we'd
# have to call os.urandom every time we want to get a key. It's a waste of
# time and entropy.
key = ndb.Key(
cls, name,
parent=ndb.Key(AuthSecretScope, 'local', parent=root_key()))
entity = key.get()
if entity is not None:
return entity
@ndb.transactional
def create():
entity = key.get()
if entity is not None:
return entity
logging.info('Creating new secret key %s', name)
entity = cls(
key=key,
values=[os.urandom(length)],
modified_by=get_service_self_identity())
entity.put()
return entity
return create()
################################################################################
## IP whitelist.