我是Falcon的新手,我想知道是否有类似Flask的"url_for"解决方案。我已经搜索了文档,但我似乎找不到与谷歌/堆栈搜索相关的任何内容。
为了向没有使用过Flask的Falcon用户澄清,我想动态获取已定义资源的URL。我专门尝试通过在我的有效负载中包含指向我的资源的链接来实现资源扩展,这样前端就不必构造任何 URL。
法典:
class PostResource(object):
def on_get(self, req, resp, post_id):
"""Fetch single post resource."""
resp.status = falcon.HTTP_200
post_dto = post_to_dto(get_post(post_id))
# TODO: find url_to alternative for falcon: specify post resource location
post_dto.href = ''
resp.body = to_json(PostDtoSerializer, post_dto)
class PostCollectionResource(object):
def on_get(self, req, resp):
"""
Fetch grid view for all post resources.
Note: This endpoint support pagination, pagination arguments must be provided via query args.
"""
resp.status = falcon.HTTP_200
# TODO: add hrefs for each post for end ui
post_collection_dto = PostCollectionDto(
posts=[post_to_dto(post, comments=False) for post in get_posts(
start=req.params.get('start', None), count=req.params.get('count', None)
)])
resp.body = to_json(PostCollectionDtoSerializer, post_collection_dto)
def on_post(self, req, resp):
"""Create a new post resource."""
resp.status = falcon.HTTP_201
payload = req.stream.read()
user = req.context.get('user')
create_post(user._id, from_json(PostFormDtoSerializer, payload))
# TODO: find url_to alternative for falcon: redirect to on_get
resp.set_header('Location', '')
后收集示例:
[
{
"href": ".../post/000000/",
"links": [
"rel": "like",
"href": ".../post/000000/like"
],
"title": "Foobar",
...
}
]
我希望能够生成指向PostResource
的链接。
关闭这个线程,我现在使用这里详述的方法 https://github.com/neetjn/py-blog/issues/16。
正如维护者所证实的那样,Falcon 不支持这一点,我的解决方法是使用静态路由和子方法创建一个基本资源,以使用请求req
参数中的信息构建指向给定资源的链接。
例:
class BaseResource(object):
route = ''
@classmethod
def url_to(cls, host, **kwargs) -> str:
return f'{host}{cls.route.format(**kwargs)}'
。
class PostResource(BaseResource):
route = '/v1/post/{post_id}'
def on_get(self, req, res):
pass
class PostCollectionResource(BaseResource):
route = '/v1/posts/'
def on_get(self, req, res):
posts = get_posts()
for post in posts:
post.href = PostResource.url_to(req.netloc, post_id=post.id)