GAE (Python3) enables data registration update / acquisition using Cloud NDB. Basically, use github samples. This time, the module of python-docs-samples \ appengine \ standard_python3 \ building-an-app \ building-an-app-2 I am creating it as a base.
Add the following to requirements.txt directly under the project.
requirements.txt
google-cloud-ndb
After adding, execute the following command in the directory directly under the project to install google-cloud-ndb.
pip install -r requirements.txt
This completes the Cloud NDB installation.
This time, we will create a module for simple data registration update acquisition processing. The contents are as follows.
main.py
import datetime
from flask import Flask, render_template
from datastore import user
app = Flask(__name__)
@app.route('/')
def root():
  #Register or update test user
  user.putData('test')
  #Get test user
  selectUsr = user.get('test')
  return render_template('index.html', user=selectUsr)
if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8080, debug=True)
datastore/user.py
import datetime
from google.cloud import ndb
#User information
class User(ndb.Model):
  #Last login date and time
  lastLoginDt = ndb.DateTimeProperty()
client = ndb.Client()
#User registration / update
def putData(idStr):
  with client.context():
    user = User(
      id=idStr,
      lastLoginDt = datetime.datetime.now())
    user.put()
#User acquisition
def get(idStr):
  with client.context():
    return ndb.Key(User, idStr).get()
Set the item with class. User registration / update and user acquisition are performed under with client.context ():. This time it is simple, but if there is no data, the process of updating the login date if registered is described.
templates/index.html
<!doctype html>
<html>
<head>
  <title>Sample</title>
  <script src="{{ url_for('static', filename='script.js') }}"></script>
  <link type="text/css" rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>
<body>
  <h1>Sample</h1>
  <h2>{{ user.lastLoginDt }}</h2>
</body>
</html>
Confirm that the login date and time of the registered and updated login user is displayed.
Do the following:
python main.py
Check http://127.0.0.1:8080/.
I was able to confirm the login date and time.
Let's take a look at the data store.
The data was registered.
When I accessed it again, I was able to confirm that the date and time were updated.
I couldn't do it very well and it took a long time, so I will describe it.
That's all for this time.
Thank you very much.
Recommended Posts