0

我有以下设置:

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() 函数中实例化模型类?在这里,Flask 框架实例化了 FetchJob 类,因此我无法向它提供它在实例化过程中转发的参数。

我不喜欢全局变量,因为这会破坏整个设计......

4

1 回答 1

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
于 2013-07-05T18:18:49.687 回答