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
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
46 changes: 24 additions & 22 deletions appengine/flexible/analytics/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,52 +24,54 @@


# Environment variables are defined in app.yaml.
GA_TRACKING_ID = os.environ['GA_TRACKING_ID']
GA_TRACKING_ID = os.environ["GA_TRACKING_ID"]


def track_event(category, action, label=None, value=0):
data = {
'v': '1', # API Version.
'tid': GA_TRACKING_ID, # Tracking ID / Property ID.
"v": "1", # API Version.
"tid": GA_TRACKING_ID, # Tracking ID / Property ID.
# Anonymous Client Identifier. Ideally, this should be a UUID that
# is associated with particular user, device, or browser instance.
'cid': '555',
't': 'event', # Event hit type.
'ec': category, # Event category.
'ea': action, # Event action.
'el': label, # Event label.
'ev': value, # Event value, must be an integer
'ua': 'Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14'
"cid": "555",
"t": "event", # Event hit type.
"ec": category, # Event category.
"ea": action, # Event action.
"el": label, # Event label.
"ev": value, # Event value, must be an integer
"ua": "Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14",
}

response = requests.post(
'https://www.google-analytics.com/collect', data=data)
response = requests.post("https://www.google-analytics.com/collect", data=data)

# If the request fails, this will raise a RequestException. Depending
# on your application's needs, this may be a non-error and can be caught
# by the caller.
response.raise_for_status()


@app.route('/')
@app.route("/")
def track_example():
track_event(
category='Example',
action='test action')
return 'Event tracked.'
track_event(category="Example", action="test action")
return "Event tracked."


@app.errorhandler(500)
def server_error(e):
logging.exception('An error occurred during a request.')
return """
logging.exception("An error occurred during a request.")
return (
"""
An internal error occurred: <pre>{}</pre>
See logs for full stacktrace.
""".format(e), 500
""".format(
e
),
500,
)


if __name__ == '__main__':
if __name__ == "__main__":
# This is used when running locally. Gunicorn is used to run the
# application on Google App Engine. See entrypoint in app.yaml.
app.run(host='127.0.0.1', port=8080, debug=True)
app.run(host="127.0.0.1", port=8080, debug=True)
# [END gae_flex_analytics_track_event]
16 changes: 7 additions & 9 deletions appengine/flexible/analytics/main_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

@pytest.fixture
def app(monkeypatch):
monkeypatch.setenv('GA_TRACKING_ID', '1234')
monkeypatch.setenv("GA_TRACKING_ID", "1234")

import main

Expand All @@ -31,17 +31,15 @@ def app(monkeypatch):
@responses.activate
def test_tracking(app):
responses.add(
responses.POST,
re.compile(r'.*'),
body='{}',
content_type='application/json')
responses.POST, re.compile(r".*"), body="{}", content_type="application/json"
)

r = app.get('/')
r = app.get("/")

assert r.status_code == 200
assert 'Event tracked' in r.data.decode('utf-8')
assert "Event tracked" in r.data.decode("utf-8")

assert len(responses.calls) == 1
request_body = responses.calls[0].request.body
assert 'tid=1234' in request_body
assert 'ea=test+action' in request_body
assert "tid=1234" in request_body
assert "ea=test+action" in request_body
43 changes: 26 additions & 17 deletions appengine/flexible/datastore/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,50 +33,59 @@ def is_ipv6(addr):


# [START gae_flex_datastore_app]
@app.route('/')
@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])
user_ip = ":".join(user_ip.split(":")[:2])
else:
user_ip = '.'.join(user_ip.split('.')[:2])
user_ip = ".".join(user_ip.split(".")[:2])

entity = datastore.Entity(key=ds.key('visit'))
entity.update({
'user_ip': user_ip,
'timestamp': datetime.datetime.now(tz=datetime.timezone.utc)
})
entity = datastore.Entity(key=ds.key("visit"))
entity.update(
{
"user_ip": user_ip,
"timestamp": datetime.datetime.now(tz=datetime.timezone.utc),
}
)

ds.put(entity)
query = ds.query(kind='visit', order=('-timestamp',))
query = ds.query(kind="visit", order=("-timestamp",))

results = []
for x in query.fetch(limit=10):
try:
results.append('Time: {timestamp} Addr: {user_ip}'.format(**x))
results.append("Time: {timestamp} Addr: {user_ip}".format(**x))
except KeyError:
print("Error with result format, skipping entry.")

output = 'Last 10 visits:\n{}'.format('\n'.join(results))
output = "Last 10 visits:\n{}".format("\n".join(results))

return output, 200, {"Content-Type": "text/plain; charset=utf-8"}


return output, 200, {'Content-Type': 'text/plain; charset=utf-8'}
# [END gae_flex_datastore_app]


@app.errorhandler(500)
def server_error(e):
logging.exception('An error occurred during a request.')
return """
logging.exception("An error occurred during a request.")
return (
"""
An internal error occurred: <pre>{}</pre>
See logs for full stacktrace.
""".format(e), 500
""".format(
e
),
500,
)


if __name__ == '__main__':
if __name__ == "__main__":
# This is used when running locally. Gunicorn is used to run the
# application on Google App Engine. See entrypoint in app.yaml.
app.run(host='127.0.0.1', port=8080, debug=True)
app.run(host="127.0.0.1", port=8080, debug=True)
4 changes: 2 additions & 2 deletions appengine/flexible/datastore/main_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ def test_index():
main.app.testing = True
client = main.app.test_client()

r = client.get('/', environ_base={'REMOTE_ADDR': '127.0.0.1'})
r = client.get("/", environ_base={"REMOTE_ADDR": "127.0.0.1"})
assert r.status_code == 200
assert 'Last 10 visits' in r.data.decode('utf-8')
assert "Last 10 visits" in r.data.decode("utf-8")
2 changes: 2 additions & 0 deletions appengine/flexible/disk/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,8 @@ def index():

output = f"Instance: {instance_id}\nSeen:{seen}"
return output, 200, {"Content-Type": "text/plain; charset=utf-8"}


# [END example]


Expand Down
10 changes: 3 additions & 7 deletions appengine/flexible/django_cloudsql/noxfile_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,14 @@

TEST_CONFIG_OVERRIDE = {
# You can opt out from the test for specific Python versions.
'ignored_versions': ["2.7"],

"ignored_versions": ["2.7"],
# An envvar key for determining the project id to use. Change it
# to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a
# build specific Cloud project. You can also use your own string
# to use your own Cloud project.
'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT',
"gcloud_project_env": "GOOGLE_CLOUD_PROJECT",
# 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT',

# A dictionary you want to inject into your test. Don't put any
# secrets here. These values will override predefined values.
'envs': {
'DJANGO_SETTINGS_MODULE': 'mysite.settings'
},
"envs": {"DJANGO_SETTINGS_MODULE": "mysite.settings"},
}
2 changes: 1 addition & 1 deletion appengine/flexible/django_cloudsql/polls/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@


class PollsConfig(AppConfig):
name = 'polls'
name = "polls"
3 changes: 2 additions & 1 deletion appengine/flexible/django_cloudsql/polls/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@

class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
pub_date = models.DateTimeField("date published")


class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)


# Create your models here.
4 changes: 2 additions & 2 deletions appengine/flexible/django_cloudsql/polls/test_polls.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@

class PollViewTests(TestCase):
def test_index_view(self):
response = self.client.get('/')
response = self.client.get("/")
assert response.status_code == 200
assert 'Hello, world' in str(response.content)
assert "Hello, world" in str(response.content)
2 changes: 1 addition & 1 deletion appengine/flexible/django_cloudsql/polls/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,5 @@
from . import views

urlpatterns = [
re_path(r'^$', views.index, name='index'),
re_path(r"^$", views.index, name="index"),
]
2 changes: 2 additions & 0 deletions appengine/flexible/extending_runtime/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ def fortune():
"""
output = subprocess.check_output("/usr/games/fortune")
return output, 200, {"Content-Type": "text/plain; charset=utf-8"}


# [END example]


Expand Down
3 changes: 1 addition & 2 deletions appengine/flexible/hello_world_django/helloworld/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,4 @@


def index(request):
return HttpResponse(
'Hello, World. This is Django running on Google App Engine')
return HttpResponse("Hello, World. This is Django running on Google App Engine")
64 changes: 32 additions & 32 deletions appengine/flexible/hello_world_django/project_name/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'qgw!j*bpxo7g&o1ux-(2ph818ojfj(3c#-#*_8r^8&hq5jg$3@'
SECRET_KEY = "qgw!j*bpxo7g&o1ux-(2ph818ojfj(3c#-#*_8r^8&hq5jg$3@"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
Expand All @@ -45,63 +45,63 @@
# Application definition

INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'helloworld'
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"helloworld",
)

MIDDLEWARE = (
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
"django.middleware.security.SecurityMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
)

ROOT_URLCONF = 'project_name.urls'
ROOT_URLCONF = "project_name.urls"

TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]

WSGI_APPLICATION = 'project_name.wsgi.application'
WSGI_APPLICATION = "project_name.wsgi.application"


# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": os.path.join(BASE_DIR, "db.sqlite3"),
}
}


# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'
LANGUAGE_CODE = "en-us"

TIME_ZONE = 'UTC'
TIME_ZONE = "UTC"

USE_I18N = True

Expand All @@ -113,4 +113,4 @@
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

STATIC_URL = '/static/'
STATIC_URL = "/static/"
4 changes: 2 additions & 2 deletions appengine/flexible/hello_world_django/project_name/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,6 @@


urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', helloworld.views.index),
url(r"^admin/", include(admin.site.urls)),
url(r"^$", helloworld.views.index),
]
Loading