Skip to content

Commit

Permalink
Merge pull request #33 from infrastackai/python-package
Browse files Browse the repository at this point in the history
python package, ci, and examples for django, flask, and fastapi
  • Loading branch information
aykutgk authored Oct 15, 2024
2 parents a275bb5 + cd5dffc commit d0f0258
Show file tree
Hide file tree
Showing 37 changed files with 1,222 additions and 3 deletions.
42 changes: 42 additions & 0 deletions .github/workflows/publish-pip.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
name: Release Python package

on:
push:
branches:
- main
paths:
- 'packages/python/otel/**'

jobs:
release:
name: Release SDK to PyPI
runs-on: ubuntu-latest
defaults:
run:
working-directory: packages/python/otel

steps:
- name: Checkout repository
uses: actions/checkout@v3
with:
fetch-depth: 0
token: ${{ secrets.RELEASE_PAT }}

- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.x'

- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install build twine
- name: Build package
run: python -m build

- name: Publish to PyPI
env:
TWINE_USERNAME: __token__
TWINE_PASSWORD: ${{ secrets.PYPI_API_TOKEN }}
run: twine upload dist/*
56 changes: 56 additions & 0 deletions .github/workflows/test-pip.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
name: Test Python package

on:
pull_request:
branches:
- main
paths:
- 'packages/python/otel/**'

jobs:
build-and-test:
name: Build and Test infrastackotel Package
runs-on: ubuntu-latest

defaults:
run:
working-directory: packages/python/otel

strategy:
matrix:
python-version: ['3.8', '3.9', '3.10', '3.11']

steps:
- name: Checkout Repository
uses: actions/checkout@v3

- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}

- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -e .[all]
pip install pytest
- name: Run Linter
run: |
pip install flake8
flake8 . --ignore E501,W503
- name: Run Tests
env:
INFRASTACK_TAGS: '[{"key": "env", "value": "test"}]'
run: pytest

- name: Build package
run: |
pip install build
python -m build
- name: Check distribution
run: |
pip install twine
twine check dist/*
30 changes: 30 additions & 0 deletions examples/django/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# infrastack.ai Django Example App

This is an example Django app integrated with [InfraStack](https://infrastack.ai) for observability.

Follow along [our documentation](https://docs.infrastack.ai/documentation/integrate-opentelemetry-for-django-with-infrastack) for more information.

## Getting Started

First, set up your environment:

1. Clone this repository
2. Install dependencies:
```bash
pip install infrastackotel
```
3. Export your InfraStack API key as an environment variable:
```
export INFRASTACK_API_KEY=your_api_key_here
```

Then, build and run the server with the following command:
```bash
python manage.py runserver
```
Populate some traffic by creating and listing users:
```bash
curl -X POST http://localhost:8000/users/ -H "Content-Type: application/json" -d '{"name":"George","age":77}'
curl http://localhost:8000/users/
```
Go to the [InfraStack dashboard](https://app.infrastack.ai) and see the traces.
Empty file.
16 changes: 16 additions & 0 deletions examples/django/djangoexample/asgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
"""
ASGI config for djangoexample project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/howto/deployment/asgi/
"""

import os

from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoexample.settings")

application = get_asgi_application()
129 changes: 129 additions & 0 deletions examples/django/djangoexample/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
"""
Django settings for django project.
Generated by 'django-admin startproject' using Django 5.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-h(9!oijr-f0z130v5(1t416_x68sjcd6i$ntfb-@+06ln_))!^"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"users",

]

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",
]

ROOT_URLCONF = "djangoexample.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",
],
},
},
]

WSGI_APPLICATION = "djangoexample.wsgi.application"


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

DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "mydatabase",
"USER": "myuser",
"PASSWORD": "mypassword",
"HOST": "localhost",
"PORT": "5432",
}
}


# Password validation
# https://docs.djangoproject.com/en/5.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]


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

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.1/howto/static-files/

STATIC_URL = "static/"

# Default primary key field type
# https://docs.djangoproject.com/en/5.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
24 changes: 24 additions & 0 deletions examples/django/djangoexample/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""
URL configuration for django project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
path("admin/", admin.site.urls),
path("users/", include("users.urls")),
]
25 changes: 25 additions & 0 deletions examples/django/djangoexample/wsgi.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""
WSGI config for django project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.1/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application
from infrastackotel import Configuration, Infrastack

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoexample.settings")

config = Configuration(
service_name="infrastack-django-example",
)

infrastack = Infrastack.configure(config)
infrastack.instrument_django()
infrastack.instrument_psycopg()

application = get_wsgi_application()
22 changes: 22 additions & 0 deletions examples/django/manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys


def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoexample.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)


if __name__ == "__main__":
main()
9 changes: 9 additions & 0 deletions examples/django/users/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from django.db import models


class User(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()

def __str__(self):
return self.name
7 changes: 7 additions & 0 deletions examples/django/users/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from django.urls import path

from . import views

urlpatterns = [
path('', views.user_list, name='user_list'),
]
24 changes: 24 additions & 0 deletions examples/django/users/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import json

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from .models import User


@csrf_exempt
def user_list(request):
if request.method == 'GET':
users = list(User.objects.all().values('id', 'name', 'age'))
return JsonResponse(users, safe=False)
elif request.method == 'POST':
try:
data = json.loads(request.body)
user = User.objects.create(name=data['name'], age=data['age'])
return JsonResponse({'id': user.id, 'name': user.name, 'age': user.age}, status=201)
except json.JSONDecodeError:
return JsonResponse({'error': 'Invalid JSON'}, status=400)
except KeyError:
return JsonResponse({'error': 'Missing required fields'}, status=400)
else:
return JsonResponse({'error': 'Method not allowed'}, status=405)
Loading

0 comments on commit d0f0258

Please sign in to comment.