Created
July 8, 2021 21:16
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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