Flask-RESTful如何添加和传递非全局数据 [英] Flask-RESTful how to add_resource and pass it non-global data

查看:38
本文介绍了Flask-RESTful如何添加和传递非全局数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Flask-RESTful 示例应用程序 发布在此处 TODOS 集合是一个全局变量.

In the Flask-RESTful example application posted here, the TODOS collection is a global variable.

Todo 资源注册后:

api.add_resource(Todo, '/todos/<string:todo_id>')

处理Web请求时, Todo 方法访问全局 TODOS 变量.

The Todo methods access the global TODOS variable when web requests are processed.

相反,我想实例化类中的API并传递作为类变量而不是全局变量的 TODOS 集合.

Instead, I want to instantiate the API within a class and pass a TODOS collection that is a class variable rather than a global variable.

使用 Flask-RESTful 时,什么是允许 Resource 类中的方法访问调用方类提供的变量而不使用全局变量的正确方法??

When using Flask-RESTful, what is the proper way to allow methods in a Resource class to gain access to a variable provided by the calling class without using global variables?

推荐答案

好像是我第一次不了解您,您可以使用 classmethod 构造您的API.然后将其添加为资源

Looks like I didn't understand you the first time, You can just use a classmethod to construct your API. Then add it as a resource

from flask import Flask
from flask.ext.restful import Api

class SomeApi(Resource):
    def get(self):
        return self.response

    @classmethod
    def make_api(cls, response):
        cls.response = response
        return cls


class KillerApp(object):
    def __init__(self):
        self.app = Flask()
        app_api = Api(self.app)
        MyApi = SomeAPI.make_api({"key": "value"})
        app_api.add_resource(MyApi, "/api/path")

    def run(self)
        self.app.run()


KillerApp().run()

这篇关于Flask-RESTful如何添加和传递非全局数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆