Flask:调用一个获取资源的类

时间:2015-03-25 04:43:36

标签: python flask

我的端点如下: api.add_resource(UserForm,'/app/user/form/<int:form_id>', endpoint='user_form')

我的UserForm如下:

class UserForm(Resource):
    def get(self, form_id):
       # GET stuff here
       return user_form_dictionary

如果我有一个名为get_user_form(form_id)的函数,我想根据传入的form_id参数从UserForm的get方法中检索返回值。在Flask中是否有办法允许某种方式调用UserForm的get方法该计划?

def get_user_form(form_id):
    user_form_dictionary = # some way to call UserForm class
    # user_form_dictionary will store return dictionary from
    # user_form_dictionary, something like: {'a': 'blah', 'b': 'blah'}

1 个答案:

答案 0 :(得分:0)

我不确定是否有办法从你的应用程序中直接访问UserForm类的get方法,唯一让我想到的就是调用该资源的url但我没有&#39 ;建议这样做。

您是否有机会使用烧瓶式的扩展?如果是这样,以下内容基于网站here

建议的中间项目结构

在一个通用模块中(包含将在整个应用程序中使用的函数)

常见\ util.py

def get_user_form(form_id):
    # logic to return the form data

然后在包含UserForm类的.py中,从公共模块导入util.py文件,然后执行以下操作

class UserForm(Resource):
    def get(self, form_id):
       user_form_dictionary = get_user_form(form_id)

       # any additional logic. i try and keep it to a minimum as the function called
       # would contain it. also this way maintanence is easier

       return user_form_dictionary

然后在导入公共模块后,应用程序中的其他位置可以重复使用相同的功能。

def another_function(form_id):
    user_form_dictionary = get_user_form(form_id)
    # any additional logic. 
    # same rules as before

    return user_form_dictionary