将参数传递给由框架实例化的类? (Python烧瓶)

时间:2013-07-05 18:06:43

标签: python flask

我有以下设置:

import sys 

from flask import Flask
from flask.ext import restful

from model import Model

try:
    gModel = Model(int(sys.argv[1]))
except IndexError, pExc:
    gModel = Model(100)


def main():
    lApp = Flask(__name__)
    lApi = restful.Api(lApp)
    lApi.add_resource(FetchJob, '/')
    lApp.run(debug=True)


class FetchJob(restful.Resource):
    def get(self):
        lRange = gModel.getRange()
        return lRange


if __name__ == '__main__':
    main()

有没有办法在main()函数中实例化Model-class?这里,Flask框架实例化了FetchJob类,因此我无法在实例化过程中为它提供转发的参数。

我不喜欢有全局变量,因为这会弄乱整个设计......

1 个答案:

答案 0 :(得分:2)

我认为这应该有用,虽然我不熟悉Flask:

import functools

def main():
    try:
        gModel = Model(int(sys.argv[1]))
    except IndexError as pExc:
        gModel = Model(100)
    lApp = Flask(__name__)
    lApi = restful.Api(lApp)
    lApi.add_resource(functools.partial(FetchJob, gModel), '/')
    lApp.run(debug=True)


class FetchJob(restful.Resource):

    def __init__(self, obj, *args, **kwargs):
        restfult.Resource.__init__(self, *args, **kwargs)
        self.obj = obj

    def get(self):
        lRange = self.obj.getRange()
        return lRange