簡體   English   中英

如何加快 python 中 rest api 的開發?

[英]How to speed up development of rest api in python?

我正在嘗試使用 FastApi 和 sqlAchemy 創建后端應用程序。 我有很多與數據庫有關系的實體。 所以,我的問題是:如何加快開發速度? 現在我為每個實體代碼編寫:

@app.get("/holidays")
def getHolidays():
    session = Session(bind=engine)
    holidays: List[Holiday] = session.query(Holiday).all()
    return [x.to_json() for x in holidays]

@app.get("/exclusive_operations")
def getExclusiveOperations():
    session = Session(bind=engine)
    exclusive_operations: List[ExclusiveOperation] = session.query(ExclusiveOperation).all()
    return [x.to_json() for x in exclusive_operations]

@app.get('/category_descriptions')
def getCategoryDescr():
    session = Session(bind=engine)
    category_descrs: List[CategoryDescr] = session.query(CategoryDescr).all()
    return [x.to_json() for x in category_descrs]

因此,如果我想創建所有 crud 操作,我需要為 3 個實體創建 12 個典型方法。 也許存在另一種解決方案?

它是 Python - 作為一種動態語言,函數和方法是在運行時創建的。 “@app.get”裝飾器是在應用程序中注冊您的視圖,而不是它們存在於模塊的頂層。

因此,您可以創建一個 for 循環來簡單地重新創建和注冊每個實體的視圖 - 它可以在模塊級別或 function 內部完成。

(很高興記住“@xxxx”裝飾器語法只是調用裝飾器的語法糖,將裝飾的 function 作為其唯一參數)

for Entity, name in [(Holiday, "holidays"), (ExclusiveOperation, "exclusive_operations"), (CategoryDescr, "category_descriptions")]:
    def freeze_var_wrapper(Entity, name): 
        # this intermediary function is needed, otherwise the Entity and name
        # variables would be always up-to-date inside the view function
        # and always point to the last value in the external for-loop after
        # it finished execution:
        def view():
            session = Session(bind=engine)
            entities = session.query(Entity).all()
            return [x.to_json() for x in entities]
        # optional, may facilitate debugging:
        view.__name__ = f"get{Entity.__name__}s"
        # actually registers the view function with the framework:
        # (could be done in the same line, without the "view_registrer" var)
        view_registrer = app.get(f"/{name}")
        view_registrer(view)
    
    freeze_var_wrapper(Entity, name)

還有其他方法可以刪除樣板並看起來更優雅 - 例如使用 class inheritance 和一個適當的__init__subclass__在基礎 ZA2F2ED4F8EBC2CBB4C21A29DC40,我們將注冊框架,如果不使用“即使 AB61DZ”每個 class 的方法,這只是一個可調用的):


class BaseView:
    Entity: cls 
    view_name: str

    def __init_subclass__(cls, *args, **kw):
        super().__init_subclass__(*args, **kw)
        app.get(f"/{cls.view_name}")(cls.view)
        # above, cls.view is bound to the subclass being processed, therefore 
        # the class attributes as defined in each class body are used inside the method

        # this could easily register post, delete and detail views as well
        
    @classmethod
    def view(cls);
        session = Session(bind=engine)
        entities = session.query(cls.Entity).all()
        return [x.to_json() for x in entities]
    
class HolydayView(BaseView):
    Entity = Holyday
    view_name = "holydays"
    # thats is just it.

class ExclusiveOperationView(BaseView):
    Entity = ExclusiveOperation
    view_name = "exclusive_operations"
    
class CatewgoryDescriptionView(BaseView):
    Entity = CategoryDescription
    view_name = "category_descriptions"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM