【发布时间】:2015-06-11 19:57:52
【问题描述】:
我正在尝试使用 clj-http/client 来检索网页。看起来它有点工作,但有时我会收到这种异常
线程“main”java.lang.ClassCastException 中的异常:clojure.lang.Var$Unbound 无法转换为 clojure.lang.Named,编译:(/tmp/form-init8570082100332402765.clj:1:72)
这是一个简单的函数,它从数据库(来自 jdbc/query :row-fn)检索 url,请求 url 的内容并将其写入数据库。代理数据是随机的,仅供参考。
(defn get-source
"get content of an url"
[row]
(def my-proxy "72.159.148.20")
(def my-port 10000)
(def my-url (:url row))
(def h {"User-Agent" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/34.0"})
(try
(def my-body (:body (client/get my-url {:proxy-host my-proxy :proxy-port my-port :follow-redirects false :headers h :conn-timeout 100000})))
(catch clojure.lang.ExceptionInfo e
(prn "caught" e))
)
(write-data-to-db my-url my-body))
行的值来自简单的数据库查询:
(defn -main
"I don't do a whole lot ... yet."
[& args]
(def db-spec
{
:subprotocol "mysql"
:subname "//localhost:3306/a"
:user "user"
:password "pass"})
((jdbc/query db-spec ["SELECT url FROM main where html is null and url is not null limit 2"] :row-fn get-source)))
感谢您的健康批评,我已将我的示例修正为更正确。
(defn get-source
"get list of urls to grab in"
[row]
(let [proxy "107.161.31.220" port 8080 url (:url row)
h {"User-Agent" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/34.0"}]
(:status (client/get url {:proxy-host proxy :proxy-port port :follow-redirects false :headers h :conn-timeout 100000}))))
我希望这样会更好,我再也无法得到那个异常,所以它可能被埋在我最初带来的那个烂摊子里。
【问题讨论】:
-
没有缩进很难阅读代码。 PS:了解
let -
我在可以使用
let的地方使用def,还有什么地方可以帮助缩进?在我的屏幕上,它看起来很有意境,几乎和 clj-http 示例中的一样好。 -
行的数据结构和值是什么?
-
我刚刚添加到主帖,所以它就像
{:url "http://something"} -
"我在可以使用 let 的地方使用了 def" 你知道
def只创建可变的全局容器吗?这与 Scheme 中的 def 不同。如果你曾经使用过线程,你的代码将会做出不可预测的错误事情。
标签: exception-handling clojure