Skip to content

Instantly share code, notes, and snippets.

@dshadow
Last active January 13, 2021 15:24
Show Gist options
  • Save dshadow/7b242f7db9a825a8aac6a9790162f03c to your computer and use it in GitHub Desktop.
Save dshadow/7b242f7db9a825a8aac6a9790162f03c to your computer and use it in GitHub Desktop.
get_method_name_from_route.py
#!/usr/bin/env python3
import uvicorn
from typing import List, Optional
from fastapi import FastAPI, Request, Depends, Security, HTTPException, status
from fastapi.routing import APIRoute
from fastapi.security.api_key import APIKeyHeader
app = FastAPI(
title='HelloWorld',
version='0.0.1'
)
app_key_header = APIKeyHeader(name="X-App-Key")
allowed_methods_for_client_1 = [ "TestMethod1", "SuperMethod" ]
class Client:
def __init__(self, id: int):
self.id = id
class load_client:
async def __call__(self, request: Request, token: str = Security(app_key_header)) -> Client:
current_method_name = request.app.state.method_names[request.scope["endpoint"].__name__]
print(f"Current method name is {current_method_name}")
if token == "testtoken":
if current_method_name in allowed_methods_for_client_1:
return Client(id = 1)
raise HTTPException(
status_code=status.HTTP_405_METHOD_NOT_ALLOWED, detail="Not allowed"
)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail="Not authorized"
)
@app.get('/something1', name="SuperMethod")
def method1(
client: Client = Depends(load_client())
):
return client.id
@app.get('/something2', name="LimitedAccessMethod")
def method2(
client: Client = Depends(load_client())
):
return client.id
app.state.method_names = {}
for route in app.routes:
if isinstance(route, APIRoute):
app.state.method_names[route.endpoint.__name__] = route.operation_id = route.name
uvicorn.run(app)
@dshadow
Copy link
Author

dshadow commented Jan 12, 2021

How to check:

curl -v -H 'X-App-Key: testtoken' http://127.0.0.1:8000/something1
curl -v -H 'X-App-Key: testtoken' http://127.0.0.1:8000/something2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment