【问题标题】:Compojure - avoid "manual" URL formatting when using redirectCompojure - 使用重定向时避免“手动”URL 格式
【发布时间】:2016-01-21 02:34:22
【问题描述】:

使用 Compojure,除了必须格式化请求 URL 之外,还有其他方法可以重定向到定义的路由之一吗?

例如,在以下简化的defroutes 声明中:

(defroutes app-routes
  ; ...
  (GET "/something-that-may-redirect" [query-param]
    ; parse `query-param` into `arg1` and `arg2` and:
    (ring.util.response/redirect (format "/another-route?param1=%s&param2=%s" arg1 arg2))
  (GET "/another-route" [param1 param2] ...)
  ; ...

在这里,我必须格式化要重定向到的 URL(通常还处理转义),以便稍后 Compojure 本身解析该 URL 并提取 param1param2 的值。

所以问题是是否有一种方法可以重定向并让 Compojure 格式化请求 URL,知道它已经有关于参数的信息?一些简单的事情:

(redirect "/another-route" arg1 arg2)

这会将 URL itlsef 格式化为:

"/another-route?param1=[value of arg1]&param2=[value of arg2]"

附:这个想法本身肯定不是新的。其他一些 Web 框架具有类似的功能 - 例如,使用 Python 的 Flask Web 框架,可以使用url_for 从基本路径和查询参数值中创建格式良好且转义的 URL:

# for example, in Python's Flask framework
url_for('route-name', param1='value1', param2='value2')

【问题讨论】:

  • 我不明白您所说的“将查询参数解析为 arg1 和 arg2”是什么意思。你把/path?query-param=x解构成x,你需要什么解析?
  • 是的,我不是在谈论解析——问题是关于格式化。
  • 你不能只取整个查询字符串并执行(str "/another-route?" query-string)吗?
  • 嗯,这就是我的问题的重点——首先如何获取查询字符串。我当然可以自己格式化 - 这是选项之一;我的问题是 - 如何做到最好和最简单。是否有专门为此制作的东西,还是我们需要自己格式化 URL?其他一些 Web 框架具有类似的功能 - 例如,使用 Python 的 Flask Web 框架,可以使用url_for (flask.pocoo.org/docs/0.10/quickstart/#url-building) 从基本路径和查询参数值中创建格式良好的转义 URL。
  • @dbasch 我已将上面的问题更新为更清楚 - 感谢您的提问!

标签: clojure compojure ring


【解决方案1】:

我相信这是一个重复的问题How to convert map to URL query string in Clojure/Compojure/Ring?

此代码将实现发布者寻求的目标。

(defroutes app-routes
  (GET "/something-that-may-redirect" [arg1 arg2]
       (redirect (str "/another-route" "?" (ring.util.codec/form-encode {:param1 arg1 :param2 arg2}))))
  (GET "/another-route" response (str response)))

【讨论】:

  • 谢谢,这样很好。
【解决方案2】:

您可以使用整个请求并提取查询字符串,而不是解构参数,然后重定向到附加查询字符串的新 url:

  (GET "/foo" req
   (ring.util.response/redirect (str "/bar?" (:query-string req))))

【讨论】:

  • 哦,对不起,我想我没有表达我的真正意思——我不需要重用另一个查询字符串,而是构建一个全新的查询字符串,可能有不同的查询集参数。
猜你喜欢
  • 1970-01-01
  • 2012-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-24
  • 1970-01-01
  • 1970-01-01
  • 2016-10-20
相关资源
最近更新 更多