簡體   English   中英

如何在twisted.web 中使用會話/cookie?

[英]how to use session/cookie in twisted.web?

我正在使用twisted.web 實現一個http 服務器。 問題來了:有登錄操作; 之后,我希望 http 服務器記住每個使用 cookie/session 的客戶端,直到用戶關閉瀏覽器。

我已經閱讀了twisted.web 文檔,但我不知道如何做到這一點。 我知道請求對象有一個名為 getSession() 的函數,然后將返回一個會話對象。 接下來是什么? 如何在多個請求期間存儲信息?

我還搜索了扭曲的郵件列表; 沒有什么非常有幫助的,我仍然很困惑。 如果有人以前用過這個,請給我解釋一下,甚至在這里放一些代碼,這樣我自己就可以理解了。 非常感謝你!

調用 getSession() 將生成一個會話並將 cookie 添加到請求中:

getSession() 源代碼

如果客戶端已經有一個會話 cookie,那么調用 getSession() 將讀取它並返回一個帶有原始會話內容的會話。 所以它對你的代碼是透明的,無論它是實際創建會話 cookie 還是只是讀取它。

會話 cookie 具有某些屬性……如果您想對 cookie 的內容進行更多控制,那么請查看 Request.addCookie(),其中 getSession() 在幕后調用。

您可以使用“request.getSession()”來獲取組件化對象。

您可以在http://twistedmatrix.com/documents/current/api/twisted.python.components.Componentized.html 中閱讀有關組件化的更多信息——使用它的基本方法是通過定義一個接口和一個實現,並推送您的對象進入會話。

請參閱此相關問題Store an instance of a connection-twisted.web 那里的答案鏈接到此博客文章http://jcalderone.livejournal.com/53680.html ,其中顯示了存儲會話訪問次數計數器的示例(感謝 jcalderone 的示例):

# in a .rpy file launched with `twistd -n web --path .`
cache()

from zope.interface import Interface, Attribute, implements
from twisted.python.components import registerAdapter
from twisted.web.server import Session
from twisted.web.resource import Resource

class ICounter(Interface):
    value = Attribute("An int value which counts up once per page view.")

class Counter(object):
    implements(ICounter)
    def __init__(self, session):
        self.value = 0

registerAdapter(Counter, Session, ICounter)

class CounterResource(Resource):
    def render_GET(self, request):
        session = request.getSession()
        counter = ICounter(session)   
        counter.value += 1
        return "Visit #%d for you!" % (counter.value,)

resource = CounterResource()

如果這看起來令人困惑,請不要擔心 - 在此處的行為有意義之前,您需要了解兩件事:

  1. Twisted (Zope) 接口和適配器
  2. 組件化

計數器值存儲在 Adapter 類中,Interface 類記錄了該類提供的內容。 可以在 Adapter 中存儲持久數據的原因是因為 Session(由 getSession() 返回)是 Componentized 的子類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM