Skip to content

Instantly share code, notes, and snippets.

@asafc
Created July 8, 2021 21:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save asafc/036ead38d8711e4376a02c98d39877a3 to your computer and use it in GitHub Desktop.
Save asafc/036ead38d8711e4376a02c98d39877a3 to your computer and use it in GitHub Desktop.
Example fastapi server that accept OPA decision logs and prints them to the console
"""
you may run this example with uvicorn, by using this command:
uvicorn opalogger:app --reload
"""
import gzip
from typing import Callable, List
from fastapi import Body, FastAPI, Request, Response
from fastapi.routing import APIRoute
class GzipRequest(Request):
async def body(self) -> bytes:
if not hasattr(self, "_body"):
body = await super().body()
if "gzip" in self.headers.getlist("Content-Encoding"):
body = gzip.decompress(body)
self._body = body
return self._body
class GzipRoute(APIRoute):
def get_route_handler(self) -> Callable:
original_route_handler = super().get_route_handler()
async def custom_route_handler(request: Request) -> Response:
request = GzipRequest(request.scope, request.receive)
return await original_route_handler(request)
return custom_route_handler
app = FastAPI()
app.router.route_class = GzipRoute
@app.post("/logs", include_in_schema=False)
async def print_opa_logs(request: Request):
content = await request.json()
print("OPA LOGS:")
print(content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment