url_for 对于 Flask-Admin 中基于 class 的视图
url_for for class-based views in Flask-Admin
我有一个基于 class 的管理视图:
class All_RDPs(BaseView):
@expose('/')
def index(self):
return 'ok1'
@expose('/test')
def testindex(self):
return 'ok2'
像这样在 Flask-Admin 中注册的:
admin.add_view(All_RDPs(name='dep_rdp'))
然后可以像这样从浏览器中查看:
http://localhost/admin/all_rdps/
http://localhost/admin/all_rdps/test
问题是:
- 如何为此 class 指定 URL 而不是默认生成的名称
all_rdps
?
- 如何使用
url_for
为这些端点生成 url? url_for('admin.All_RDPs.testindex')
、url_for('admin.All_RDPs')
不工作。
You can override the endpoint name by passing endpoint parameter to
the view class constructor:
admin = Admin(app)
admin.add_view(MyView(endpoint='testadmin'))
In this case, you can generate links by concatenating the view method
name with an endpoint:
url_for('testadmin.index')
If you don't override the endpoint name, the lower-case class name can
be used for generating URLs, like in:
url_for('myview.index')
For model-based views the rules differ - the model class name should
be used if an endpoint name is not provided. The ModelView also has
these endpoints by default: .index_view, .create_view, and .edit_view.
So, the following urls can be generated for a model named "User":
# List View
url_for('user.index_view')
# Create View (redirect back to index_view)
url_for('user.create_view', url=url_for('user.index_view'))
# Edit View for record #1 (redirect back to index_view)
url_for('user.edit_view', id=1, url=url_for('user.index_view'))
我有一个基于 class 的管理视图:
class All_RDPs(BaseView):
@expose('/')
def index(self):
return 'ok1'
@expose('/test')
def testindex(self):
return 'ok2'
像这样在 Flask-Admin 中注册的:
admin.add_view(All_RDPs(name='dep_rdp'))
然后可以像这样从浏览器中查看:
http://localhost/admin/all_rdps/
http://localhost/admin/all_rdps/test
问题是:
- 如何为此 class 指定 URL 而不是默认生成的名称
all_rdps
? - 如何使用
url_for
为这些端点生成 url?url_for('admin.All_RDPs.testindex')
、url_for('admin.All_RDPs')
不工作。
You can override the endpoint name by passing endpoint parameter to the view class constructor:
admin = Admin(app) admin.add_view(MyView(endpoint='testadmin'))
In this case, you can generate links by concatenating the view method name with an endpoint:
url_for('testadmin.index')
If you don't override the endpoint name, the lower-case class name can be used for generating URLs, like in:
url_for('myview.index')
For model-based views the rules differ - the model class name should be used if an endpoint name is not provided. The ModelView also has these endpoints by default: .index_view, .create_view, and .edit_view. So, the following urls can be generated for a model named "User":
# List View url_for('user.index_view') # Create View (redirect back to index_view) url_for('user.create_view', url=url_for('user.index_view')) # Edit View for record #1 (redirect back to index_view) url_for('user.edit_view', id=1, url=url_for('user.index_view'))