|
| 1 | +# Copyright 2015 Google Inc. All Rights Reserved. |
| 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 | +"""This sample shows how to connect to PostgreSQL running on Cloud SQL. |
| 16 | +
|
| 17 | +See the documentation for details on how to setup and use this sample: |
| 18 | + https://cloud.google.com/appengine/docs/flexible/python\ |
| 19 | + /using-cloud-sql-postgres |
| 20 | +""" |
| 21 | + |
| 22 | +import datetime |
| 23 | +import logging |
| 24 | +import os |
| 25 | +import socket |
| 26 | + |
| 27 | +from flask import Flask, request |
| 28 | +from flask_sqlalchemy import SQLAlchemy |
| 29 | +import sqlalchemy |
| 30 | + |
| 31 | + |
| 32 | +app = Flask(__name__) |
| 33 | + |
| 34 | + |
| 35 | +def is_ipv6(addr): |
| 36 | + """Checks if a given address is an IPv6 address.""" |
| 37 | + try: |
| 38 | + socket.inet_pton(socket.AF_INET6, addr) |
| 39 | + return True |
| 40 | + except socket.error: |
| 41 | + return False |
| 42 | + |
| 43 | + |
| 44 | +# [START example] |
| 45 | +# Environment variables are defined in app.yaml. |
| 46 | +app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['SQLALCHEMY_DATABASE_URI'] |
| 47 | +app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False |
| 48 | + |
| 49 | +db = SQLAlchemy(app) |
| 50 | + |
| 51 | + |
| 52 | +class Visit(db.Model): |
| 53 | + id = db.Column(db.Integer, primary_key=True) |
| 54 | + timestamp = db.Column(db.DateTime()) |
| 55 | + user_ip = db.Column(db.String(46)) |
| 56 | + |
| 57 | + def __init__(self, timestamp, user_ip): |
| 58 | + self.timestamp = timestamp |
| 59 | + self.user_ip = user_ip |
| 60 | + |
| 61 | + |
| 62 | +@app.route('/') |
| 63 | +def index(): |
| 64 | + user_ip = request.remote_addr |
| 65 | + |
| 66 | + # Keep only the first two octets of the IP address. |
| 67 | + if is_ipv6(user_ip): |
| 68 | + user_ip = ':'.join(user_ip.split(':')[:2]) |
| 69 | + else: |
| 70 | + user_ip = '.'.join(user_ip.split('.')[:2]) |
| 71 | + |
| 72 | + visit = Visit( |
| 73 | + user_ip=user_ip, |
| 74 | + timestamp=datetime.datetime.utcnow() |
| 75 | + ) |
| 76 | + |
| 77 | + db.session.add(visit) |
| 78 | + db.session.commit() |
| 79 | + |
| 80 | + visits = Visit.query.order_by(sqlalchemy.desc(Visit.timestamp)).limit(10) |
| 81 | + |
| 82 | + results = [ |
| 83 | + 'Time: {} Addr: {}'.format(x.timestamp, x.user_ip) |
| 84 | + for x in visits] |
| 85 | + |
| 86 | + output = 'Last 10 visits:\n{}'.format('\n'.join(results)) |
| 87 | + |
| 88 | + return output, 200, {'Content-Type': 'text/plain; charset=utf-8'} |
| 89 | +# [END example] |
| 90 | + |
| 91 | + |
| 92 | +@app.errorhandler(500) |
| 93 | +def server_error(e): |
| 94 | + logging.exception('An error occurred during a request.') |
| 95 | + return """ |
| 96 | + An internal error occurred: <pre>{}</pre> |
| 97 | + See logs for full stacktrace. |
| 98 | + """.format(e), 500 |
| 99 | + |
| 100 | + |
| 101 | +if __name__ == '__main__': |
| 102 | + # This is used when running locally. Gunicorn is used to run the |
| 103 | + # application on Google App Engine. See entrypoint in app.yaml. |
| 104 | + app.run(host='127.0.0.1', port=8080, debug=True) |
0 commit comments