如何在Flask路由启动之前运行功能?

时间:2017-10-05 13:04:26

标签: python flask

我需要在Flask路由开始工作之前执行调用功能。我应该把函数放在服务启动时调用它。我做了:

class Dish {
    string Name { get; set; }
    //Additional properties and/or methods would go here
}

//...

Dictionary<int, Dish> dishes = new Dictionary<int, Dish> {
    { 1, new Dish { Name = "Pasta Bolognese" } },
    { 2, new Dish { Name = "Pizza Napolitana" } },
    { 35, new Dish { Name = "Pizza Funghi" } },
    { 36, new Dish { Name = "Pizza Carbonara" } }
}

int id = Convert.ToInt32(Console.ReadLine());

//...

bool hasDish = dishes.TryGet( id, out Dish selectedDish);

if (hasDish)
{
    Console.WriteLine($"{selectedDish.Name} is added to your list.");
    //You can extend your Dish class with further properties and methods and use them here
}
else
{
    Console.WriteLine($"{id} is not available.");
}

1 个答案:

答案 0 :(得分:4)

如果我是你,我会把它放在创建应用程序的功能中,例如:

def checkIfDBExists(): # it is my function
    if not DBFullPath.exists():
         print("Local DB do not exists")
    else:
         print("DB is exists")

def create_app():
    checkIfDBExists()
    return Flask(__name__)

app = create_app()

当您发现任何设置错误时,这将允许您执行任何必要的步骤。您还可以在该功能中执行路由。我已经写了这样的功能来分开这个过程here

def register_urls(app):
    app.add_url_rule('/', 'index', index)
    return app