繁体   English   中英

相当于Falcon的“ url_for”烧瓶

[英]Flask “url_for” equivalent for Falcon

我是Falcon的新手,我想知道框架是否有类似于Flask的“ url_for”解决方案。 我已经搜索过文档,但似乎找不到与Google /堆栈搜索相关的任何内容。

为了向未使用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

由维护者证实猎鹰支持此,我周围的工作是要建立一个基础资源与静态路由和儿童的方法来构建一个链接,使用请求中的信息给定的资源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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM