[英]How to use url_for with flask_restx?
我可以在flask 2.0.1 模板中使用url_for
<!-- flask-template.html -->
<button onclick="window.location.href='{{ url_for( 'testimport') }}';" >Import</button>
随着
@app.route('/import/images')
def testimport():
return "ok"
但我不能用flask-restx 0.5.1 中的资源来做到这一点。
api = Api(app, version='1.0',
title='The Restx API',
description='An API to initiate basic operations')
ns_detect = api.namespace('detect', path='/', description='Detection')
@ns_detect.route('/detect/recording')
class DetectRecording(Resource):
def post(self):
return {"status": "ok"}
谁能解释一下,如何在上面的 flask-restx 案例中正确使用url_for ?
<button value="{{ url_for( 'ns_detect.DetectRecording') }}">1</button> <!-- can't build -->
<button value="{{ Api.url_for( 'DetectRecording') }}">2</button> <!-- Api undefined -->
<button value="{{ api.url_for( 'DetectRecording') }}">3</button> <!-- api undefined -->
<button value="{{ url_for( 'ns_detect.DetectRecording') }}">4</button> <!-- can't build -->
<button value="{{ url_for( 'api.DetectRecording') }}">5</button> <!-- can't build -->
<button value="{{ url_for( 'ns_detect.DetectRecording.post') }}">6</button> <!-- can't build -->
顺便说一句:我已经安装了
Werkzeug 2.0.3
Jinja2 3.1.2
经过反复试验,我想通了,使url_for
与flask-restx一起工作需要哪个魔术键:
它是命名空间和修改后的类名的组合。
例子:
ns = api.namespace('xxx', path='/', description='some description')
@ns.route('/some/endpoint')
class DoSomething(Resource):
def post(self):
return {"status": "ok"}
然后使用url_for({{ 'xxx_do_something' }})
。
也许 flask-restx 文档会从这样的例子中受益。
一起使用flask.Blueprint
和flask_restx.Namespace
时,您必须在调用 flask.url_for 时引用蓝图、命名空间和路由的flask.url_for
名称。
如xy所述,格式为“blueprint.namespace_route_name”。 请记住,类名称中的驼峰式被解构为 snake_case。 (RouteName -> route_name,在上面的例子中)
下面的示例将 API 注册为flask.Blueprint
,将flask_restx.Api
object 注册为两个命名空间(Users 和 Books),每个命名空间都有一个 GET 路由。 两条路由都使用flask.url_for
返回它们对应的端点
# Create a Flask app
app = Flask(__name__)
# Create 'api' BLUEPRINT for the API, named "api"
blueprint = Blueprint('api', __name__)
# Create an instance of the Api class
api = Api(blueprint)
# Define the 'users' NAMESPACE
users_ns = Namespace('users', description='Users related operations')
# Define the 'UsersList' ROUTE in the 'users' NAMESPACE
@users_ns.route('/')
class UsersList(Resource):
def get(self):
return {'UsersList_url': url_for('api.users_users_list')}
# Define the 'books' NAMESPACE
books_ns = Namespace('books', description='Books related operations')
# Define the "Books" ROUTE in the 'books' NAMESPACE
@books_ns.route('/')
class Books(Resource):
def get(self):
return {'Books_url': url_for('api.books_books')}
# Register the namespaces with the API
api.add_namespace(users_ns)
api.add_namespace(books_ns)
# Register the blueprint with the Flask app
app.register_blueprint(blueprint)
if __name__ == '__main__':
app.run(debug=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.