首页 > 解决方案 > Flask:将url路径传递给类构造函数

问题描述

我正在尝试一些可能非常非正统的东西:我需要传递一个参数,该参数通过 url 路径进入基于类的 MethodView 的类构造函数。

http://127.0.0.1:5000/child/my_id_string

我想my_id_stringarg1.

我最有希望的尝试是基于这个问题,但我需要使用基于类的视图而不是函数。不幸的是,这个调用背后的逻辑比示例复杂一些,即我不能简单地重构代码以不在构造函数中使用“my_id”。

from flask import Flask, request
from flask.views import MethodView

BASE = 11
app = Flask('mybase')

class Child(MethodView):
    def __init__(self, base, arg1=None):
        self.base = base
        print('some init process, where I need arg1...')

    def get(self, arg1):
        return f'Some operation with {str(arg1)}.'

app.add_url_rule(
    '/child/<arg1>',
    'child',
    view_func=Child.as_view(
        'child_view',
        BASE,
        arg1 = request.args.get('my_id')
    ),
    methods=['GET',]
)

我的代码片段出现以下错误,因为我认为注册发生在/没有特定请求之前,对吗?希望,有人能够提供帮助。提前致谢!

RuntimeError:在请求上下文之外工作。
这通常意味着您尝试使用需要活动 HTTP 请求的功能。有关如何避免此问题的信息,请参阅有关测试的文档。

标签: pythonflask

解决方案


我对你的语法有点困惑 : app = flask("mybase") :i 使用app = flask(__name__)

但这就是我会做的。

@app.route("/child/<arg1>")
def x(arg1):
   varArg1 = arg1
   #now you have whatever is in the url will be passed into varArg1.


推荐阅读