python - Flask:将url路径传递给类构造函数
问题描述
我正在尝试一些可能非常非正统的东西:我需要传递一个参数,该参数通过 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',]
)
我的代码片段出现以下错误,因为我认为注册发生在/没有特定请求之前,对吗?希望,有人能够提供帮助。提前致谢!
RuntimeError:在请求上下文之外工作。
这通常意味着您尝试使用需要活动 HTTP 请求的功能。有关如何避免此问题的信息,请参阅有关测试的文档。
解决方案
我对你的语法有点困惑 :
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.
推荐阅读
- reactjs - 剪辑路径-polyfill反应导入不起作用
- python - matplotlib,scrapy 包不能用 Pycharm 安装
- julia - 参数类型的问题
- python - 打印 R2 分数时发现样本数量不一致的输入变量:[354, 152]
- python - 如何从 JSON 文件中读取和打印浮点数据?
- python - 尝试在 python 上使用 selenium 将隐藏输入或发送键的值更改为文本字段
- jenkins - Jenkins 不能使用远程 ssh 的参数?
- vue.js - 数据在vue中文本输入字段之外发生变化时如何防止输入事件触发?
- python - 如何在模板中获取 Django 3+ 中的应用程序名称?
- perl - Cairo::SolidPattern 不是 GooCanvas2::CairoPattern 类型