FastAPI main 未执行

FastAPI main not executed

from fastapi import FastAPI
import person

app = FastAPI()

local_database = []

@app.get('/')
def index():
    """Return the todo"""
    return "Use: URL/docs to access API documentation"

@app.get('/people')
def get_people():
    if not local_database:    
        return 'Database empty'
    
    people_info = [person for person in local_database]
    return people_info

@app.post('/people')
def create_person(person: person.Person):
    local_database.append(person)
    return 'Added new person to database'

@app.get("/people/{person_id}")
def read_all_infos(person_id: int):
    try:
        return local_database[person_id]
    except IndexError as e:
        return repr(e)
        # This is much better than any str()-like solutions, because it actually includes the type of exception.
        
@app.get("/people/information/salary")
def read_salary(name: str, gender: str, age: int, password: str):    
    
    for pers in local_database:
        if (    pers.name == name 
            and pers.gender == gender 
            and password == "123456"
            ):
            return pers.salary
    
    return 'Could not find your person'

@app.get("/people/information/gender")
def read_gender(name: str):
    print(name)
    for pers in local_database:
        if pers.name == name:
            return pers

    return 'Could not find your person'

# maybe needed
def populate_database():
    dummy_person1 = person.Person(salary = 55000, gender="male", name ="Jack", age = 22)
    dummy_person2 = person.Person(salary = 120000, gender="female", name ="Rose", age = 42)
    local_database.append(dummy_person1)    
    local_database.append(dummy_person2)    

if __name__ == '__main__':
    populate_database()
    

我的目标是使用 FastAPI 与本地内存数据库通信以进行测试。然而,在我的主要我想 运行 populate_database() 将 class Person 的一些实例添加到列表中。

然后我想使用 HTTP 请求 GET 来接收 local_data。 不幸的是,local_database 列表未填充。我希望数据库中有 2 个 Person 实例。 知道为什么 local_database 列表没有填充吗?

如果模块 运行 来自标准输入、脚本或交互式提示,则其 __name__ 被设置为 "__main__"1

实际上,populate_database 仅在您通过 python <filename> 运行 执行它时执行,但您可能 运行 使用 uvicorn 执行它或另一个将其作为普通模块执行的 运行ner。

尝试将 populate_database 呼叫移动到 if __name__ = "__main__" 警卫之外。