Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion managed_vms/cloudsql/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import datetime
import os
import socket

from flask import Flask, request
from flask.ext.sqlalchemy import SQLAlchemy
Expand All @@ -22,6 +23,15 @@
app = Flask(__name__)


def is_ipv6(addr):
"""Checks if a given address is an IPv6 address."""
try:
socket.inet_pton(socket.AF_INET6, addr)
return True
except socket.error:
return False


# [START example]
# Environment variables are defined in app.yaml.
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['SQLALCHEMY_DATABASE_URI']
Expand All @@ -41,8 +51,16 @@ def __init__(self, timestamp, user_ip):

@app.route('/')
def index():
user_ip = request.remote_addr

# Keep only the first two octets of the IP address.
if is_ipv6(user_ip):
user_ip = ':'.join(user_ip.split(':')[:2])
else:
user_ip = '.'.join(user_ip.split('.')[:2])

visit = Visit(
user_ip=request.remote_addr,
user_ip=user_ip,
timestamp=datetime.datetime.utcnow()
)

Expand Down
20 changes: 19 additions & 1 deletion managed_vms/datastore/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
# limitations under the License.

import datetime
import socket

from flask import Flask, request
from gcloud import datastore
Expand All @@ -21,14 +22,31 @@
app = Flask(__name__)


def is_ipv6(addr):
"""Checks if a given address is an IPv6 address."""
try:
socket.inet_pton(socket.AF_INET6, addr)
return True
except socket.error:
return False


# [START example]
@app.route('/')
def index():
ds = datastore.Client()

user_ip = request.remote_addr

# Keep only the first two octets of the IP address.
if is_ipv6(user_ip):
user_ip = ':'.join(user_ip.split(':')[:2])
else:
user_ip = '.'.join(user_ip.split('.')[:2])

entity = datastore.Entity(key=ds.key('visit'))
entity.update({
'user_ip': request.remote_addr,
'user_ip': user_ip,
'timestamp': datetime.datetime.utcnow()
})

Expand Down