Skip to content
This repository was archived by the owner on Sep 17, 2025. It is now read-only.

Commit abe9a69

Browse files
authored
Add hello world example (#73)
1 parent b106545 commit abe9a69

12 files changed

Lines changed: 648 additions & 4 deletions

File tree

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Copyright 2017, OpenCensus Authors
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.
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# Copyright 2017, OpenCensus Authors
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 django import forms
16+
17+
18+
class HelloForm(forms.Form):
19+
fname = forms.CharField(max_length=40)
20+
lname = forms.CharField(max_length=40)
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
# Copyright 2017, OpenCensus Authors
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+
"""Django settings for test app."""
16+
17+
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
18+
import os
19+
20+
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21+
SECRET_KEY = 'secret_key_for_test'
22+
23+
ALLOWED_HOSTS = ['*']
24+
25+
# Application definition
26+
INSTALLED_APPS = (
27+
'django.contrib.admin',
28+
'django.contrib.auth',
29+
'django.contrib.contenttypes',
30+
'django.contrib.sessions',
31+
'django.contrib.messages',
32+
'django.contrib.staticfiles',
33+
'opencensus.trace.ext.django',
34+
)
35+
36+
MIDDLEWARE_CLASSES = (
37+
'django.contrib.sessions.middleware.SessionMiddleware',
38+
'django.middleware.common.CommonMiddleware',
39+
'django.middleware.csrf.CsrfViewMiddleware',
40+
'django.contrib.auth.middleware.AuthenticationMiddleware',
41+
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
42+
'django.contrib.messages.middleware.MessageMiddleware',
43+
'django.middleware.clickjacking.XFrameOptionsMiddleware',
44+
'django.middleware.security.SecurityMiddleware',
45+
'opencensus.trace.ext.django.middleware.OpencensusMiddleware',
46+
)
47+
48+
ROOT_URLCONF = 'app.urls'
49+
50+
TEMPLATES = [
51+
{
52+
'BACKEND': 'django.template.backends.django.DjangoTemplates',
53+
'DIRS': [
54+
os.path.join(BASE_DIR, 'app', 'templates'),
55+
],
56+
'APP_DIRS': True,
57+
'OPTIONS': {
58+
'context_processors': [
59+
'django.template.context_processors.debug',
60+
'django.template.context_processors.request',
61+
'django.contrib.auth.context_processors.auth',
62+
'django.contrib.messages.context_processors.messages',
63+
],
64+
},
65+
},
66+
]
67+
68+
OPENCENSUS_TRACE = {
69+
'SAMPLER': 'opencensus.trace.samplers.always_on.AlwaysOnSampler',
70+
'EXPORTER': 'opencensus.trace.exporters.stackdriver_exporter.StackdriverExporter',
71+
'PROPAGATOR': 'opencensus.trace.propagation.google_cloud_format.'
72+
'GoogleCloudFormatPropagator',
73+
}
74+
75+
OPENCENSUS_TRACE_PARAMS = {
76+
'SAMPLING_RATE': 0.5,
77+
}
78+
79+
# Internationalization
80+
# https://docs.djangoproject.com/en/1.8/topics/i18n/
81+
82+
LANGUAGE_CODE = 'en-us'
83+
84+
TIME_ZONE = 'UTC'
85+
86+
USE_I18N = True
87+
88+
USE_L10N = True
89+
90+
USE_TZ = True
91+
92+
93+
# Static files (CSS, JavaScript, Images)
94+
# https://docs.djangoproject.com/en/1.8/howto/static-files/
95+
96+
STATIC_ROOT = 'static'
97+
STATIC_URL = '/static/'
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
<!--Copyright 2017, OpenCensus Authors-->
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+
<!DOCTYPE html>
16+
<html lang="en">
17+
<body>
18+
<form action="greetings" method="POST">{% csrf_token %}
19+
First Name:<br>
20+
<input type="fname" name="fname">
21+
<br>
22+
Last Name:<br>
23+
<input type="lname" name="lname">
24+
<input type="submit" value="Submit">
25+
</body>
26+
</html>
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Copyright 2017, OpenCensus Authors
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+
"""project_name URL Configuration
16+
17+
The `urlpatterns` list routes URLs to views. For more information please see:
18+
https://docs.djangoproject.com/en/1.8/topics/http/urls/
19+
Examples:
20+
Function views
21+
1. Add an import: from my_app import views
22+
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
23+
Class-based views
24+
1. Add an import: from other_app.views import Home
25+
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
26+
Including another URLconf
27+
1. Add an import: from blog import urls as blog_urls
28+
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
29+
"""
30+
from django.conf.urls import include, url
31+
from django.contrib import admin
32+
33+
import app.views
34+
35+
36+
urlpatterns = [
37+
url(r'^admin/', include(admin.site.urls)),
38+
url(r'^$', app.views.home),
39+
url(r'^greetings$', app.views.greetings),
40+
url(r'^_ah/health$', app.views.health_check),
41+
url(r'^request$', app.views.get_request_header),
42+
url(r'^mysql$', app.views.mysql_trace),
43+
url(r'^postgresql$', app.views.postgresql_trace),
44+
url(r'^trace_requests', app.views.trace_requests),
45+
url(r'^sqlalchemy_mysql$', app.views.sqlalchemy_mysql_trace),
46+
url(r'^sqlalchemy_postgresql$', app.views.sqlalchemy_postgresql_trace),
47+
]
Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
# Copyright 2017, OpenCensus Authors
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 django.http import HttpResponse
16+
from django.shortcuts import render
17+
18+
from .forms import HelloForm
19+
20+
from opencensus.trace import config_integration
21+
22+
import mysql.connector
23+
import psycopg2
24+
import sqlalchemy
25+
26+
import time
27+
import os
28+
import requests
29+
30+
DB_HOST = 'localhost'
31+
32+
# MySQL settings
33+
MYSQL_PASSWORD = os.environ.get('SYSTEST_MYSQL_PASSWORD')
34+
35+
# PostgreSQL settings
36+
POSTGRES_PASSWORD = os.environ.get('SYSTEST_POSTGRES_PASSWORD')
37+
38+
INTEGRATIONS = ['mysql', 'postgresql', 'sqlalchemy', 'requests']
39+
40+
config_integration.trace_integrations(INTEGRATIONS)
41+
42+
43+
def home(request):
44+
return render(request, 'home.html')
45+
46+
47+
def greetings(request):
48+
if request.method == 'POST':
49+
form = HelloForm(request.POST)
50+
51+
if form.is_valid():
52+
first_name = form.cleaned_data['fname']
53+
last_name = form.cleaned_data['lname']
54+
return HttpResponse(
55+
"Hello, {} {}".format(first_name, last_name))
56+
else:
57+
return render(request, 'home.html')
58+
59+
return render(request, 'home.html')
60+
61+
62+
def trace_requests(request):
63+
response = requests.get('http://www.google.com')
64+
return HttpResponse(str(response.status_code))
65+
66+
67+
def mysql_trace(request):
68+
try:
69+
conn = mysql.connector.connect(
70+
host=DB_HOST,
71+
user='root',
72+
password=MYSQL_PASSWORD)
73+
cursor = conn.cursor()
74+
75+
query = 'SELECT 2*3'
76+
cursor.execute(query)
77+
78+
result = []
79+
80+
for item in cursor:
81+
result.append(item)
82+
83+
return HttpResponse(str(result))
84+
85+
except Exception:
86+
msg = "Query failed. Check your env vars for connection settings."
87+
return HttpResponse(msg, status=500)
88+
89+
90+
def postgresql_trace(request):
91+
try:
92+
conn = psycopg2.connect(
93+
host=DB_HOST,
94+
user='postgres',
95+
password=POSTGRES_PASSWORD,
96+
dbname='postgres')
97+
cursor = conn.cursor()
98+
99+
query = 'SELECT 2*3'
100+
cursor.execute(query)
101+
102+
result = []
103+
104+
for item in cursor.fetchall():
105+
result.append(item)
106+
107+
return HttpResponse(str(result))
108+
109+
except Exception:
110+
msg = "Query failed. Check your env vars for connection settings."
111+
return HttpResponse(msg, status=500)
112+
113+
114+
def sqlalchemy_mysql_trace(request):
115+
try:
116+
engine = sqlalchemy.create_engine(
117+
'mysql+mysqlconnector://{}:{}@{}'.format(
118+
'root', MYSQL_PASSWORD, DB_HOST))
119+
conn = engine.connect()
120+
121+
query = 'SELECT 2*3'
122+
123+
result_set = conn.execute(query)
124+
125+
result = []
126+
127+
for item in result_set:
128+
result.append(item)
129+
130+
return HttpResponse(str(result))
131+
132+
except Exception:
133+
msg = "Query failed. Check your env vars for connection settings."
134+
return HttpResponse(msg, status=500)
135+
136+
137+
def sqlalchemy_postgresql_trace(request):
138+
try:
139+
engine = sqlalchemy.create_engine(
140+
'postgresql://{}:{}@{}/{}'.format(
141+
'postgres', POSTGRES_PASSWORD,
142+
DB_HOST, 'postgres'))
143+
conn = engine.connect()
144+
145+
query = 'SELECT 2*3'
146+
147+
result_set = conn.execute(query)
148+
149+
result = []
150+
151+
for item in result_set:
152+
result.append(item)
153+
154+
return HttpResponse(str(result))
155+
156+
except Exception:
157+
msg = "Query failed. Check your env vars for connection settings."
158+
return HttpResponse(msg, status=500)
159+
160+
161+
def health_check(request):
162+
return HttpResponse("ok", status=200)
163+
164+
165+
def get_request_header(request):
166+
return HttpResponse(request.META.get('HTTP_X_CLOUD_TRACE_CONTEXT'))
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# Copyright 2017, OpenCensus Authors
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+
import os
16+
import sys
17+
18+
if __name__ == "__main__":
19+
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "app.settings")
20+
21+
from django.core.management import execute_from_command_line
22+
23+
execute_from_command_line(sys.argv)

0 commit comments

Comments
 (0)