Skip to content

Instantly share code, notes, and snippets.

@edwardfung123
Created March 7, 2017 04:51
Show Gist options
  • Select an option

  • Save edwardfung123/67af8b58b11977c4c41b65e39f91b4e5 to your computer and use it in GitHub Desktop.

Select an option

Save edwardfung123/67af8b58b11977c4c41b65e39f91b4e5 to your computer and use it in GitHub Desktop.
GAE Concurrency Test2 (With transaction)
import webapp2
import logging
from google.appengine.ext import ndb
@ndb.transactional(retries=10)
def update_bank_account(key, by=1):
account = BankAccount.get_by_id(key)
if account:
account.amount += by
account.put()
return True
return False
class BankAccount(ndb.Model):
amount = ndb.IntegerProperty(default=0)
redirect_html = '''<html>
<head>
<meta http-equiv="refresh" content="1; url=http://{host}/" />
</head>
<body><pre>Will redirect you back to home page in 1 second.</pre></body>
</html>
'''
class MainHandler(webapp2.RequestHandler):
def get(self):
key = 'edward'
account = BankAccount.get_by_id(key)
if not account:
self.abort(404, 'Your account not found. may be create one?')
self.response.headers['content-type'] = 'text/plain'
self.response.write('Hello\n{} you have ${} in your account.'.format(key, account.amount))
def init(self):
model = BankAccount.get_or_insert('edward', amount=0)
model.amount = 0
model.put()
self.redirect('/')
def inc(self):
key = 'edward'
try:
update_bank_account(key, by=1)
self.response.headers['content-type'] = 'text/html'
self.response.write(redirect_html.format(host=self.request.host))
except Exception as e:
logging.exception(e)
app = webapp2.WSGIApplication([
webapp2.Route('/init', handler='main.MainHandler:init'),
webapp2.Route('/inc', handler='main.MainHandler:inc'),
('/*', MainHandler),
], debug=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment