Last active
July 23, 2022 04:23
-
-
Save myuanz/03f3e350fb165ec3697a22b559a7eb50 to your computer and use it in GitHub Desktop.
Dynamic enum with FastApi
This file contains 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
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
blog: https://myuan.fun/dynamic-enum-with-fastapi/