我正在通過CherryPy執行RESTful Web服務。由於客戶端並不總是瀏覽器,並且可能無法存儲cookie,所以我打算獲取CherryPy的會話標識並通過HTTP GET/POST將其作爲標記傳遞給它。當客戶端向CherryPy發送帶有此令牌(會話ID)的請求時,它可以像Cookie一樣進行會話恢復,服務器端可以獲得認證或任何有狀態的數據。通過特定標識在CherryPy中恢復會話
我的問題是,如何通過特定的ID恢復CherryPy會話?
我正在通過CherryPy執行RESTful Web服務。由於客戶端並不總是瀏覽器,並且可能無法存儲cookie,所以我打算獲取CherryPy的會話標識並通過HTTP GET/POST將其作爲標記傳遞給它。當客戶端向CherryPy發送帶有此令牌(會話ID)的請求時,它可以像Cookie一樣進行會話恢復,服務器端可以獲得認證或任何有狀態的數據。通過特定標識在CherryPy中恢復會話
我的問題是,如何通過特定的ID恢復CherryPy會話?
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import cherrypy.lib
config = {
'global' : {
'server.socket_host' : '127.0.0.1',
'server.socket_port' : 8080,
'server.thread_pool' : 4
}
}
class App:
@cherrypy.expose
@cherrypy.config(**{'tools.sessions.on': True})
def counter(self):
if 'counter' not in cherrypy.session:
cherrypy.session['counter'] = 0
cherrypy.session['counter'] += 1
return 'Counter: {0}<br/>Session key: {1}'.format(
cherrypy.session['counter'],
cherrypy.request.cookie['session_id'].value
)
@cherrypy.expose
def recreate(self, token):
'''You can try open it from another browser
once set the value in /counter
'''
cherrypy.request.cookie['session_id'] = token
cherrypy.lib.sessions.init()
# now it should be ready
return 'Counter: {0}'.format(cherrypy.session['counter'])
if __name__ == '__main__':
cherrypy.quickstart(App(), '/', config)
受saaj的啓發,我找到了一個可行的解決方案。試試這個......
import cherrypy.lib
config = {
'global' : {
'server.socket_host' : '127.0.0.1',
'server.socket_port' : 8080,
'server.thread_pool' : 4,
'tools.sessions.on': True,
'tools.sessions.storage_type': "file",
'tools.sessions.storage_path': "adf"
}
}
class Helloworld:
@cherrypy.expose
def make(self, token=''):
'''You can try open it from another browser
once set the value in /counter
'''
if(token == ''):
cherrypy.lib.sessions.init()
# take this token and put in the url 127.0.0.1:8080/make/ + token
return cherrypy.session.id
else:
#send two requests with the token. 1. to set a session var
# and 2. to retrieve the var from session
cherrypy.lib.sessions.init(self, id=token)
print('do something')
# on the second request check the value after init and it's HI!
cherrypy.session['something'] = 'HI'
return token
if __name__ == '__main__':
cherrypy.quickstart(Helloworld(), '/', config)
希望這有助於!
他提到請求不是來自瀏覽器,也不能使用cookie來存儲會話ID。 –
嗨saaj,我專注於設置cookie ['session_id'] =令牌並調用init()。經過測試後,它無法正常工作,無法恢復存在的會話內容。 PS。我正在使用curl和HTTP GET來測試令牌。 – Takol
@AndrewKloos你的評論是不相關的,因爲代碼是僞造與客戶端功能無關的請求cookie。 – saaj