0

I have the following setting:

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()

Is there a way to instantiate the Model-class inside the main()-function? Here, the Flask framework instantiates the FetchJob-class, so that I cannot provide it the parameters it forwards during the instantiation process.

I don't like to have global variables as this messes up the whole design ...

1
  • 2
    Hungarian notation? Please, just no.... Commented Jul 5, 2013 at 18:31

1 Answer 1

2

I think this should work, although I'm not familiar with 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
Sign up to request clarification or add additional context in comments.

3 Comments

I would use a classmethod on FetchJob for this instead. FetchJob.as_view() which returns a callable.
Sorry, the functools-version does not work for me. I am getting an AttributeError: 'functools.partial' object has no attribute '__name__' This corresponds to the Python docs: docs.python.org/2/library/functools.html#partial-objects. According to that, partial-objects behave differently compared to "normal" objects.
If you are looking at the edit history of my post, there was a lambda version as well — everything is the same, but this line is changning: lApi.add_resource(lambda *args, **kwargs: FetchJob(gModel, *args, **kwargs). Try this one out, and let me know if that worked for you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.