Skip to content

Instantly share code, notes, and snippets.

@hongbo-miao
Forked from asafc/opalogger.py
Created July 9, 2021 17:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hongbo-miao/349728a314cb10692babc0bfaa8fa093 to your computer and use it in GitHub Desktop.
Save hongbo-miao/349728a314cb10692babc0bfaa8fa093 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