【问题标题】:Declare fast api, python's object声明 fastapi,python 对象
【发布时间】:2021-01-06 06:55:54
【问题描述】:

我们可以声明一个继承 basemodel 的模型并在其中放入一个值,而不是普通的 Python 模型吗?

我可以强制创建 PyTimeZoneSetting 模型,但我可以使用现有的 TimeZoneSetting 吗?

    from pydantic import BaseModel
    from typing import List, Optional

    class TimeZoneSetting(BaseModel):
        time_zone: str
        type: int
        sync_time: Optional[str] = None
        time_server: Optional[str] = None
        time_set_type: Optional[int] = None

    class PyTimeZoneSetting():
        time_zone: str
        type: int
        sync_time: str
        time_server: str
        time_set_type: str

    def update_system_timezone():
        !Here, I want to create a TimeZoneSetting model and put in a value.!

【问题讨论】:

    标签: python-3.x fastapi pydantic


    【解决方案1】:

    我不太确定您的意图,但我会尝试提供一个可以满足您需求的示例。

    以下是一些初始化 Pydantic 模型的方法:

    # initialize every field one by one
    model_instance = TimeZoneSetting(time_zone="foo", type=1, sync_time="bar")
    
    # provide your dict object
    kwargs = {"time_zone": "foo", "type": 1}
    model_instance = TimeZoneSetting(**kwargs)
    

    这是更新模型的方法,其中每个字段都作为类的属性到达:

    model_instance.time_zone = "bar"
    

    这是让你成为 dict 模型的方法:

    model_instance.dict()
    

    【讨论】:

    • 谢谢。我需要设置时区,我想自己设置系统时间或者使用ntpdate来同步服务器。您提供的答案帮助我解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 2013-03-22
    • 2013-10-12
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    相关资源
    最近更新 更多