|
| 1 | +# Copyright 2022 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from flask import Flask, render_template, request |
| 16 | +from google.appengine.api import app_identity, users |
| 17 | +from google.appengine.ext import ndb |
| 18 | + |
| 19 | +app = Flask(__name__) |
| 20 | + |
| 21 | + |
| 22 | +class Visit(ndb.Model): |
| 23 | + 'Visit entity registers visitor IP address & timestamp' |
| 24 | + visitor = ndb.StringProperty() |
| 25 | + timestamp = ndb.DateTimeProperty(auto_now_add=True) |
| 26 | + |
| 27 | +def store_visit(remote_addr, user_agent): |
| 28 | + 'create new Visit entity in Datastore' |
| 29 | + Visit(visitor='{}: {}'.format(remote_addr, user_agent)).put() |
| 30 | + |
| 31 | +def fetch_visits(limit): |
| 32 | + 'get most recent visits' |
| 33 | + return Visit.query().order(-Visit.timestamp).fetch(limit) |
| 34 | + |
| 35 | + |
| 36 | +@app.route('/') |
| 37 | +def root(): |
| 38 | + 'main application (GET) handler' |
| 39 | + store_visit(request.remote_addr, request.user_agent) |
| 40 | + visits = fetch_visits(10) |
| 41 | + |
| 42 | + # put together users context for web template |
| 43 | + user = users.get_current_user() |
| 44 | + context = { # logged in |
| 45 | + 'who': user.nickname(), |
| 46 | + 'admin': '(admin)' if users.is_current_user_admin() else '', |
| 47 | + 'sign': 'Logout', |
| 48 | + 'link': '/_ah/logout?continue=https://%s/' % \ |
| 49 | + app_identity.get_default_version_hostname() |
| 50 | + } if user else { # not logged in |
| 51 | + 'who': 'user', |
| 52 | + 'admin': '', |
| 53 | + 'sign': 'Login', |
| 54 | + 'link': users.create_login_url('/'), |
| 55 | + } |
| 56 | + |
| 57 | + # add visits to context and render template |
| 58 | + context['visits'] = visits |
| 59 | + return render_template('index.html', **context) |
0 commit comments