curl - Clojure:读取 CSV 文件并将列值传递给curl

标签 curl clojure

这里是新的 clojure 用户。 。 。有点纠结。

项目目标:

  • 从 csv 文件读取数据
  • 隔离第 4 列中的值
  • 将值传递给 html 参数
  • 在curl调用中使用动态创建的url

我陷入了两个特定领域:

1)如果我取出进程文件中的 println,我开始收到有关它的错误,不知道如何处理“%”(无法解析符号:在此上下文中的%)

2)在call-curl中我似乎无法将传入的id值获取到URL的id参数中。

(defn call-curl [id]
  (let [url "-d id=%s&format=pdf&cpull=1"]
    (shell/sh "curl" "-u" "username:password" "http://wwwin-search.com/protected-cgi-bin/office2pdf.cgi" (format url id))))

(defn process-files
   "Take file name and read data"
   [file]
   (let [data (slurp file)
         rows (rest (c/parse-csv data))]
     (dorun
     (map #(println (call-curl (nth % 3 nil))) rows))))

(process-files "output.csv")

最佳答案

我怀疑发生第一个问题是因为没有 println 的代码看起来像:

(map (call-curl (nth % 3 nil)) rows)

而不是:

(map #(call-curl (nth % 3 nil)) rows)

如果您想遍历整个序列只是为了产生副作用,我建议 doseq :

(doseq [row rows]
  (call-curl (nth row 3 nil)))

或者您可以使用 run! :

(run! call-curl (map #(nth % 3 nil)))

但我认为 doseq 版本更具可读性。

对于第二个问题,我认为您需要将每个单独的参数提供给 curl 调用作为单独的字符串:它应该是

“-d”“...”

而不是

“-d ...”

我对其进行了一些重构以使其更具可读性:

(defn call-curl [id]
  (let [data (format "id=%s&format=pdf&cpull=1" id)]
    (shell/sh "curl" "-u" "username:password" "-d" data "http://wwwin-search.com/protected-cgi-bin/office2pdf.cgi")))

还有一点需要注意的是,根据您的代码,您没有传递 URL 中的参数,而是作为请求正文传递的数据。来自mancurl:

-d, --data

(HTTP) Sends the specified data in a POST request to the HTTP server, in the same way that a browser does when a user has filled in an HTML form and presses the submit button. This will cause curl to pass the data to the server using the content-type application/x-www-form-urlencoded. Compare to -F, --form.

-d, --data is the same as --data-ascii. --data-raw is almost the same but does not have a special interpretation of the @ character. To post data purely binary, you should instead use the --data- binary option. To URL-encode the value of a form field you may use --data-urlencode.

我不确定为什么您确实想要调用 curl 而不是直接从 Clojure 调用 HTTP 端点,但现在当您评论说您确实想直接执行此操作时,让我建议您使用clj-http为此目的的图书馆。在它的帮助下,事情变得如此简单:

(require '[clj-http.client :as http])

(defn call-url [id]
  (http/post "http://wwwin-search.com/protected-cgi-bin/office2pdf.cgi"
    {:basic-auth ["username" "password"]
     :form-params {:id id
                   :format "pdf"
                   :cpull 1}}))

关于curl - Clojure:读取 CSV 文件并将列值传递给curl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37052239/

相关文章:

Clojure,惰性评估问题

clojure - Clojure 中的匿名宏

PHP 和 CURL POST XML

php - 如何将额外数据存储到多 curl 信息处理程序中?

PHP 页面抓取 - cUrl 重定向问题

c# - 在 Web API 上取回 POST 数据

functional-programming - 关于闭包中词法绑定(bind)的更多解释?

clojure - 在 Clojure 中处理这种序列转换的最佳方法是什么?

clojure - 使用 Clojure 根据英语语言环境格式化 float 的字符串表示形式

json - Elasticsearch查询检索所有ID的特定类型的特定_source值