Dynamic enum with FastApi
Sometimes you need dynamic enumerations, such as some selector options from database, but you will find that it seems like an the enumeration can only be modified at app startup. Try this:
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) |
1 | myuan@jxtkfuwuqi ~> curl 10.242.155.222:8000 |
Enumeration constraints are still in effect while the enumeration is modified
Dynamic enum with FastApi