我是Falcon的新手,我想知道是否有像烧瓶一样的" url_for"框架的解决方案。我已经搜索了文档,但我似乎无法找到与Google /堆栈搜索相关的内容。
为了澄清没有使用过Flask的猎鹰用户,我想动态获取已定义资源的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
的链接。
答案 0 :(得分:0)
为了关闭此主题,我现在使用此处详述的方法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)