0

是否有解决方案可以在继承 werkzeug BaseConverter 类的类中获取应用程序上下文?

这是我在 Flask 中运行的示例:

from werkzeug.routing import BaseConverter
class CodeConverter(BaseConverter):
    app = None
    
    def to_python(self, value):
        # Create an app context to get value from db
        # and instantiate a class X as obj
        return obj
    
    def to_url(self, obj):
        value = obj.code
        title = obj.title
        return "%s/%s"%(value, title)

def crate_app():
    ...
    app.url_map.converters['code'] = CodeConverter
    CodeConverter.app = app
    ...
4

1 回答 1

0

好吧,这对我有用。

from werkzeug.routing import BaseConverter
class CodeConverter(BaseConverter):
    app = None

    async def get_object(self, app, value):
        async with app.app_context():
            # and instantiate a class X as obj
            return obj

    def to_python(self, value):
        pool = concurrent.futures.ThreadPoolExecutor()
        result = pool.submit(asyncio.run, self.get_object(self.__class__.app, value)).result()
        return result

    def to_url(self, obj):
        value = obj.code
        title = obj.title
        return "%s/%s"%(value, title)

def crate_app():
    ...
    app.url_map.converters['code'] = CodeConverter
    CodeConverter.app = app
    ...
于 2020-08-03T21:26:24.367 回答