Skip to content

Commit

Permalink
Added pre-commit hooks + example for FastAPI
Browse files Browse the repository at this point in the history
  • Loading branch information
acidjunk committed Apr 8, 2020
1 parent 8319f24 commit 2919b69
Show file tree
Hide file tree
Showing 17 changed files with 169 additions and 37 deletions.
32 changes: 32 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
repos:
- repo: https://github.com/pre-commit/mirrors-isort
rev: v4.3.21
hooks:
- id: isort
additional_dependencies: [toml]
exclude: env.py
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-docstring-first
- id: check-json
- id: check-yaml
- id: debug-statements
- id: requirements-txt-fixer
- id: detect-private-key
- repo: https://gitlab.com/pycqa/flake8
rev: 3.7.9
hooks:
- id: flake8
- repo: https://github.com/pre-commit/pygrep-hooks
rev: v1.5.1
hooks:
- id: python-check-blanket-noqa
- id: python-use-type-annotations
- repo: https://github.com/ambv/black
rev: 19.10b0
hooks:
- id: black
language_version: python3.7
19 changes: 18 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,32 @@ python:
stages:
- lint
- test
- name: deploy
if: tag is present

matrix:
include:
- stage: lint
name: flake8
python: '3.7'
- stage: deploy
name: Deploy to PyPI
python: '3.7'
install: skip
script: skip

install:
- pip install tox-travis

script:
- tox
- tox

deploy:
provider: pypi
distributions: sdist
user: '__token__'
password:
secure: 'TODO'
on:
condition: $TRAVIS_BUILD_STAGE_NAME = Deploy
tags: true
2 changes: 0 additions & 2 deletions LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -174,5 +174,3 @@
of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS


2 changes: 1 addition & 1 deletion MANIFEST.in
Original file line number Diff line number Diff line change
@@ -1 +1 @@
include VERSION LICENSE
include VERSION LICENSE
4 changes: 2 additions & 2 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ Installation

Run the following command:

.. code-block::
.. code-block::
$ pip install Starlette-Opentracing
Expand All @@ -44,4 +44,4 @@ Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
limitations under the License.
40 changes: 40 additions & 0 deletions example/fastapi/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# FastAPI opentracing example

An example of using the middleware with FastAPI and instrumentation for some commonly used python libs for DB access
and external http requests. Using the `install_all_patches()` method from `opentracing_instrumentation` package gives
you a way to trace your MySQLdb, SQLAlchemy, Redis queries and more without writing boilerplate code.

It uses a local running `jaeger` instance as a tracing system. You can install `jaeger` for your OS with the info on
https://www.jaegertracing.io/download/ or start a self contained dockerized variant with:

```
docker run -d -e \
COLLECTOR_ZIPKIN_HTTP_PORT=9411 \
-p 5775:5775/udp \
-p 6831:6831/udp \
-p 6832:6832/udp \
-p 5778:5778 \
-p 16686:16686 \
-p 14268:14268 \
-p 9411:9411 \
jaegertracing/all-in-one:latest
```

When `jaeger` is up and running you can access it at: http://localhost:16686/search

Now install the requirements and start FastAPI:

```bash
python3 -m venv example
source example/bin/activate
pip install -r requirements.txt
python app.py
```

When you now access these URL's, you should see the traces in jaeger:

http://localhost:8000/

http://localhost:8000/external-api

http://localhost:8000/test-404
42 changes: 42 additions & 0 deletions example/fastapi/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import requests
import uvicorn
from fastapi import FastAPI
from jaeger_client import Config as jaeger_config
from opentracing_instrumentation.client_hooks import install_all_patches

from starlette_opentracing import StarletteTracingMiddleWare

app = FastAPI()


@app.get("/")
async def homepage():
return {"title": "Home", "content": "Home content"}


@app.get("/external-api")
def call_external_api():
# Note: Using requests instead of httpx here so you can see the effect of `install_all_patches()`
try:
r = requests.get("https://api.github.com/events")
r.raise_for_status()
except requests.exceptions.HTTPError as err:
return {"title": "Call external API", "content": {"error": str(err)}}
return {"title": "Call external API", "content": r.json()}


opentracing_config = jaeger_config(
config={
"sampler": {"type": "const", "param": 1},
"logging": False,
"local_agent": {"reporting_host": "localhost"},
},
service_name="FastAPI tracer example",
)
jaeger_tracer = opentracing_config.initialize_tracer()
install_all_patches()
app.add_middleware(StarletteTracingMiddleWare, tracer=jaeger_tracer)


if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
2 changes: 1 addition & 1 deletion example/fastapi/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ fastapi
jaeger-client
opentracing_instrumentation
requests
uvicorn
-e git://github.com/acidjunk/starlette-opentracing.git#egg=Starlette-OpenTracing
uvicorn
6 changes: 3 additions & 3 deletions example/starlette/README.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
# Starlette opentracing example

An example of using the middleware with Starlette and instrumentation for some commonly used python libs for DB access
and external http requests. Using the `install_all_patches()` method from `opentracing_instrumentation` package gives
An example of using the middleware with Starlette and instrumentation for some commonly used python libs for DB access
and external http requests. Using the `install_all_patches()` method from `opentracing_instrumentation` package gives
you a way to trace your MySQLdb, SQLAlchemy, Redis queries and more without writing boilerplate code.

It uses a local running `jaeger` instance as a tracing system. You can install `jaeger` for your OS with the info on
It uses a local running `jaeger` instance as a tracing system. You can install `jaeger` for your OS with the info on
https://www.jaegertracing.io/download/ or start a self contained dockerized variant with:

```
Expand Down
27 changes: 12 additions & 15 deletions example/starlette/app.py
Original file line number Diff line number Diff line change
@@ -1,41 +1,38 @@
import requests
import uvicorn
from jaeger_client import Config as jaeger_config
from opentracing_instrumentation.client_hooks import install_all_patches
from starlette.applications import Starlette
from starlette.responses import JSONResponse

from jaeger_client import Config as jaeger_config
from opentracing_instrumentation.client_hooks import install_all_patches
from starlette_opentracing import StarletteTracingMiddleWare


import uvicorn


app = Starlette(debug=True)

@app.route('/')

@app.route("/")
async def homepage(request):
return JSONResponse({'title': 'Home', 'content': 'Home content'})
return JSONResponse({"title": "Home", "content": "Home content"})


@app.route('/external-api')
@app.route("/external-api")
def call_external_api(request):
# Note: Using requests instead of httpx here so you can see the effect of `install_all_patches()`
try:
r = requests.get('https://api.github.com/events')
r = requests.get("https://api.github.com/events")
r.raise_for_status()
except requests.exceptions.HTTPError as err:
return JSONResponse({'title': 'Call external API', 'content': {"error": str(err)}})
return JSONResponse({'title': 'Call external API', 'content': r.json()})
return JSONResponse({"title": "Call external API", "content": {"error": str(err)}})
return JSONResponse({"title": "Call external API", "content": r.json()})


@app.exception_handler(404)
async def not_found(r, exc):
context = {"method": r.method, "client": r.client, "url": r.url.path, "query_params": {**r.query_params}}
response = {'title': 'Page not found', 'content': 'Page not found', 'context':{**context}}
response = {"title": "Page not found", "content": "Page not found", "context": {**context}}
return JSONResponse(response, status_code=404)



opentracing_config = jaeger_config(
config={
"sampler": {"type": "const", "param": 1},
Expand All @@ -49,4 +46,4 @@ async def not_found(r, exc):
app.add_middleware(StarletteTracingMiddleWare, tracer=jaeger_tracer)

if __name__ == "__main__":
uvicorn.run(app, host='0.0.0.0', port=8000)
uvicorn.run(app, host="0.0.0.0", port=8000)
2 changes: 1 addition & 1 deletion example/starlette/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ jaeger-client
opentracing_instrumentation
requests
starlette
uvicorn
-e git://github.com/acidjunk/starlette-opentracing.git#egg=Starlette-OpenTracing
uvicorn
4 changes: 2 additions & 2 deletions requirements-test.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# add dependencies in setup.py

-r requirements.txt


-e .[tests]
-r requirements.txt
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
# add dependencies in setup.py

-e .
16 changes: 13 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from setuptools import setup

"""
Starlette-OpenTracing
---------------------
This extension provides simple integration of OpenTracing in Starlette applications.
"""
from setuptools import setup

version = open("VERSION").read().strip()
setup(
name="Starlette-OpenTracing",
Expand All @@ -24,7 +24,17 @@
platforms="any",
install_requires=["starlette", "opentracing>=2.0,<3"],
extras_require={
"tests": ["black", "flake8", "flake8-quotes", "isort", "mock", "pytest", "pytest-cov", "requests"],
"tests": [
"black",
"flake8",
"flake8-quotes",
"isort",
"mock",
"pre-commit",
"pytest",
"pytest-cov",
"requests",
],
},
classifiers=[
"Environment :: Web Environment",
Expand Down
3 changes: 0 additions & 3 deletions starlette_opentracing/middleware.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
from urllib.parse import urlunparse

import opentracing
from opentracing.ext import tags


Expand Down
1 change: 0 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import pytest

from starlette.applications import Starlette
from starlette.responses import PlainTextResponse
from starlette.testclient import TestClient
Expand Down
2 changes: 1 addition & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,4 @@ commands = flake8 starlette_opentracing tests
[testenv]
extras = tests
commands =
pytest
pytest

0 comments on commit 2919b69

Please sign in to comment.