Object Oriented Python with Flask Server?

后端 未结 5 1894
悲哀的现实
悲哀的现实 2021-02-04 02:18

I\'m using Flask to expose some data-crunching code as a web service. I\'d like to have some class variables that my Flask functions can access.

Let me walk you through

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-04 02:40

    a bit late but heres a quick implementation that i use to register routes at init time

    from flask import Flask,request,render_template
    from functools import partial
    
    
    registered_routes = {}
    def register_route(route=None):
        #simple decorator for class based views
        def inner(fn):
            registered_routes[route] = fn
            return fn
        return inner
    
    class MyServer(Flask):
        def __init__(self,*args,**kwargs):
            if not args:
                kwargs.setdefault('import_name',__name__)
            Flask.__init__(self,*args ,**kwargs)
            # register the routes from the decorator
            for route,fn in registered_routes.items():
                partial_fn = partial(fn,self)
                partial_fn.__name__ = fn.__name__
                self.route(route)(partial_fn)
    
    
        @register_route("/")
        def index(self):
            return render_template("my_template.html")
    
    if __name__ == "__main__":
        MyServer(template_folder=os.path.dirname(__file__)).run(debug=True)
    

提交回复
热议问题