Skip to content

Instantly share code, notes, and snippets.

@myuanz
Last active July 23, 2022 04:23
Show Gist options
  • Save myuanz/03f3e350fb165ec3697a22b559a7eb50 to your computer and use it in GitHub Desktop.
Save myuanz/03f3e350fb165ec3697a22b559a7eb50 to your computer and use it in GitHub Desktop.
Dynamic enum with FastApi
from random import randint
from fastapi import FastAPI
from enum import Enum
app = FastAPI()
class DynamicEnum(Enum):
pass
@app.get("/")
async def root(e: DynamicEnum):
return {"e": e}
@app.get("/rand-enum")
async def rand_enum():
class EmptyEnum(Enum): pass
global DynamicEnum
new_enum = EmptyEnum(
'DynamicEnum',
{
**{f'{k}-{randint(0, 10)}': f'value-{randint(0, 100)}' for k in range(5)}
}
)
DynamicEnum._member_map_ = new_enum._member_map_
DynamicEnum._member_names_ = new_enum._member_names_
DynamicEnum._value2member_map_ = new_enum._value2member_map_
# It doesn't work because fastapi always holds a reference to the original enum
# DynamicEnum = new_enum
return {"message": DynamicEnum._member_map_}
if __name__ == "__main__":
import uvicorn
uvicorn.run("test-enum:app", host='0.0.0.0', debug=True, reload=True, workers=1)
@myuanz
Copy link
Author

myuanz commented Jul 23, 2022

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