2011-05-14 51 views
4

我正在尝试解决如何获取会话和在Google App Engine中使用闪光灯的方法。有人可以使用Ring或Sandbar提供一个清晰的例子吗?我认为我有沙洲工作,特别是它不告诉我Var sandbar.stateful-session/sandbar-flash is unbound和当我转储处理程序时,我得到:flash:session,但我不确定如果这是一个沙洲会议或一个环。为了完整起见,我会提到我使用了最新版本的appengine-magic,ring,hiccup和sandbar。似乎没有任何不兼容或问题。Google App Engine中的沙坝或响铃会话的简单示例

所以一个清晰的例子最好使用flash-put!, flash-get, session-put! and session-get

一)没有很多简单易懂的例子在那里:

回答

4

我不平时喜欢回答我自己的问题,但是在这种情况下,我会因为破例。

b)为他人使用一个快速的工作示例是很好的。

注:AppEngine上魔法在这里不需要,这也将正常环会话

代码工作

;; Place in a file called session.clj in the example project 
(ns example.session 
    "Works with the normal ring sessions 
    allowing you to use side-effects to manage them") 

(declare current-session) 

(defn wrap-session! [handler] 
    (fn [request] 
    (binding [current-session (atom (or (:session request) {}))] 
     (let [response (handler request)] 
     (assoc response :session @current-session))))) 

(defn session-get 
    ([k] (session-get k nil)) 
    ([k default] (if (vector? k) 
       (get-in @current-session k) 
       (get @current-session k default)))) 

(defn session-put! 
    ([m] 
    (swap! current-session (fn [a b] (merge a m)) m)) 
    ([k v] 
    (swap! current-session (fn [a b] (merge a {k b})) v))) 

(defn session-pop! [k] 
    (let [res (get @current-session k)] 
    (swap! current-session (fn [a b] (dissoc a b)) k) 
    res)) 

(defn session-delete-key! [k] 
    (swap! current-session (fn [a b] (dissoc a b)) k)) 

(defn session-destroy! [] 
    (swap! current-session (constantly nil))) 


;; Place in a file called core.clj in the example project 
(ns example.core 
    (:use compojure.core 
     [ring.middleware.keyword-params :only [wrap-keyword-params]] 
     [ring.middleware.session :only [wrap-session]] 
     [ring.middleware.session.cookie :only [cookie-store]] 
     [example session]) 
    (:require [appengine-magic.core :as ae])) 

(declare current-session) 

(defroutes example-app-routes 
    (GET "/" _ 
     (fn [req] 
     (let [counter (session-get :counter 0)] 
      {:status 200 
      :headers {"Content-Type" "text/plain"} 
      :body (str "started: " counter)}))) 
    (GET "/inc" _ 
     (fn [req] 
     (let [counter (do 
         (session-put! :counter (inc (session-get :counter 0))) 
         (session-get :counter))] 
      {:status 200 
      :headers {"Content-Type" "text/plain"} 
      :body (str "incremented: " counter)})))) 

(def example-app-handler 
    (-> #'example-app-routes 
     wrap-keyword-params 
     wrap-session! 
     (wrap-session {:cookie-name "example-app-session" 
        :store (cookie-store)}))) 

(ae/def-appengine-app example-app #'example-app-handler) 

如何使用它

导航到http://127.0.0.1:8080/inc增量会话中的计数器和http://127.0.0.1:8080/将在会话中显示计数器的值。

包装会话!会议不需要工作,只需使用

(wrap-session {:cookie-name "example-app-session" 
        :store (cookie-store)}) 

会给你工作的功能会话。不过,我想用副作用和包装会话来管理我的会话!提供该功能。要使用类似功能的Flash,只需使用session-put!在会话中添加一个值,然后使用session-pop!将其删除。

希望有帮助。

相关问题