我正在尝试一些可能非常非正统的事情:我需要传递一个参数,该参数通过 url 路径传入基于类的 MethodView 的类构造函数。
http://127.0.0.1:5000/child/my_id_string
我想将
my_id_string
作为 arg1
传递给以下构造函数。
我最有希望的尝试是基于这个问题,但我需要使用基于类的视图而不是函数。不幸的是,这个调用背后的逻辑比示例更复杂,即我不能简单地重构代码以不在构造函数中使用“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',]
)
我按原样收到以下代码片段错误,因为我认为注册发生在/没有特定请求之前,这是正确的吗? 希望,有人能够提供帮助。预先感谢!
运行时错误:在请求上下文之外工作。
这通常意味着您尝试使用所需的功能 活动的 HTTP 请求。请参阅有关测试的文档 有关如何避免此问题的信息。
我对你的语法有点困惑:
app = flask("mybase")
:我用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.
我也有同样的问题。我的解决方案如下所示:
@api.doc("""Return a report by method name""")
@api.route("/reports/<method_name>")
class ReportByMethod(Reporter):
def __init__(self, method_name):
self.method_name = method_name
super().__init__()
def get(self, method_name):
return ['method_name']
就我的(有限的)测试而言,