asgi-server-timing-middleware

Overview

ASGI Server-Timing middleware

An ASGI middleware that wraps the excellent yappi profiler to let you measure the execution time of any function or coroutine in the context of an HTTP request, and return it as a standard Server-Timing HTTP header.

Sample configurations

Here are some example configurations for various frameworks and libraries. Feel free to combine them as needed.

FastAPI

fastapi_app.add_middleware(ServerTimingMiddleware, calls_to_track={
	"1deps": (fastapi.routing.solve_dependencies,),
	"2main": (fastapi.routing.run_endpoint_function,),
	"3valid": (pydantic.fields.ModelField.validate,),
	"4encode": (fastapi.encoders.jsonable_encoder,),
	"5render": (
		fastapi.responses.JSONResponse.render,
		fastapi.responses.ORJSONResponse.render,
	),
})

Starlette

from starlette.middleware import Middleware

middleware = [
  Middleware(ServerTimingMiddleware, calls_to_track={
	  # TODO: ...
  }),
]

starlette_app = Starlette(routes=routes, middleware=middleware)

SQLAlchemy

fastapi_app.add_middleware(ServerTimingMiddleware, calls_to_track={
	"db_exec": (sqlalchemy.engine.base.Engine.execute,),
	"db_fetch": (
		sqlalchemy.engine.ResultProxy.fetchone,
		sqlalchemy.engine.ResultProxy.fetchmany,
		sqlalchemy.engine.ResultProxy.fetchall,
	),
})

More Frameworks

Feel free to submit PRs containing examples for more libraries and ASGI frameworks.

Caveats

  • Only the end-to-end time is reported for both functions and coroutines, so it's not possible to tell from the metrics when a coroutine took a long time because the event loop thread got stalled (though asyncio's debug mode can help).
  • The profiler's memory is not freed over time, and only gets cleared when it exceeds a given threshold (50MB by default). When memory gets cleared, data collected for all ongoing requests is lost, so the timing for these will be incorrect.
  • Executing the same task multiple times in parallel (such as with asyncio.gather()) will report the duration as if they had been executed sequentially.
  • The minimum version of Python supported is 3.7, since this middleware makes use of PEP 567 context variables to track which function call belongs to which request, and the Python 3.6 backport doesn't have asyncio support.

Special Thanks

  • Sümer Cip (@sumerc), for creating and maintaininng yappi, as well as being very responsive and open to adding all the new features needed to make this work.
  • David Montague (@dmontagu) for his involvement in shaping this middleware at every step of the way.
A simple api written in python/fastapi that serves movies from a cassandra table.

A simple api written in python/fastapi that serves movies from a cassandra table. 1)clone the repo 2)rename sample_global_config_.py to global_config.

Sreeraj 1 Aug 26, 2021
Example of integrating Poetry with Docker leveraging multi-stage builds.

Poetry managed Python FastAPI application with Docker multi-stage builds This repo serves as a minimal reference on setting up docker multi-stage buil

Michael Oliver 266 Dec 27, 2022
Backend logic implementation for realworld with awesome FastAPI

Backend logic implementation for realworld with awesome FastAPI

Nik 2.2k Jan 08, 2023
Admin Panel for GinoORM - ready to up & run (just add your models)

Gino-Admin Docs (state: in process): Gino-Admin docs Play with Demo (current master 0.2.3) Gino-Admin demo (login: admin, pass: 1234) Admin

Iuliia Volkova 46 Nov 02, 2022
python template private service

Template for private python service This is a cookiecutter template for an internal REST API service, written in Python, inspired by layout-golang. Th

UrvanovCompany 15 Oct 02, 2022
A rate limiter for Starlette and FastAPI

SlowApi A rate limiting library for Starlette and FastAPI adapted from flask-limiter. Note: this is alpha quality code still, the API may change, and

Laurent Savaete 565 Jan 02, 2023
Web Version of avatarify to democratize even further

Web-avatarify for image animations This is the code base for this website and its backend. This aims to bring technology closer to everyone, just by a

Carlos Andrés Álvarez Restrepo 66 Nov 09, 2022
I'm curious if pydantic + fast api can be sensibly used with DDD + hex arch methodology

pydantic-ddd-exploration I'm curious if pydantic + fast api can be sensibly used with DDD + hex arch methodology Prerequisites nix direnv (nix-env -i

Olgierd Kasprowicz 2 Nov 17, 2021
An image validator using FastAPI.

fast_api_image_validator An image validator using FastAPI.

Kevin Zehnder 7 Jan 06, 2022
REST API with FastAPI and SQLite3.

REST API with FastAPI and SQLite3

Luis Quiñones Requelme 2 Mar 14, 2022
Backend Skeleton using FastAPI and Sqlalchemy ORM

Backend API Skeleton Based on @tiangolo's full stack postgres template, with some things added, some things removed, and some things changed. This is

David Montague 18 Oct 31, 2022
Mnist API server w/ FastAPI

Mnist API server w/ FastAPI

Jinwoo Park (Curt) 8 Feb 08, 2022
signal-cli-rest-api is a wrapper around signal-cli and allows you to interact with it through http requests

signal-cli-rest-api signal-cli-rest-api is a wrapper around signal-cli and allows you to interact with it through http requests. Features register/ver

Sebastian Noel Lübke 31 Dec 09, 2022
Piccolo Admin provides a simple yet powerful admin interface on top of Piccolo tables

Piccolo Admin Piccolo Admin provides a simple yet powerful admin interface on top of Piccolo tables - allowing you to easily add / edit / filter your

188 Jan 09, 2023
The base to start an openapi project featuring: SQLModel, Typer, FastAPI, JWT Token Auth, Interactive Shell, Management Commands.

The base to start an openapi project featuring: SQLModel, Typer, FastAPI, JWT Token Auth, Interactive Shell, Management Commands.

Bruno Rocha 251 Jan 09, 2023
Generate FastAPI projects for high performance applications

Generate FastAPI projects for high performance applications. Based on MVC architectural pattern, WSGI + ASGI. Includes tests, pipeline, base utilities, Helm chart, and script for bootstrapping local

Radosław Szamszur 274 Jan 08, 2023
fastapi-crud-sync

Developing and Testing an API with FastAPI and Pytest Syncronous Example Want to use this project? Build the images and run the containers: $ docker-c

59 Dec 11, 2022
Deploy an inference API on AWS (EC2) using FastAPI Docker and Github Actions

Deploy an inference API on AWS (EC2) using FastAPI Docker and Github Actions To learn more about this project: medium blog post The goal of this proje

Ahmed BESBES 60 Dec 17, 2022
Ready-to-use and customizable users management for FastAPI

FastAPI Users Ready-to-use and customizable users management for FastAPI Documentation: https://frankie567.github.io/fastapi-users/ Source Code: https

François Voron 2.4k Jan 01, 2023
FastAPI framework plugins

Plugins for FastAPI framework, high performance, easy to learn, fast to code, ready for production fastapi-plugins FastAPI framework plugins Cache Mem

RES 239 Dec 28, 2022