通过特定ID恢复CherryPy中的会话

时间:2014-07-01 10:32:11

标签: session cherrypy

我正在使用CherryPy进行RESTful Web服务。由于客户端并不总是浏览器并且可能无法存储cookie,因此我计划获取CherryPy的会话ID并通过HTTP GET / POST作为令牌传递。当客户端使用此令牌(会话ID)向CherryPy发送请求时,它可以像cookie一样恢复会话,服务器端可以获得身份验证或任何有状态数据。

我的问题是,如何按特定ID恢复CherryPy会话?

2 个答案:

答案 0 :(得分:0)

#!/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)

答案 1 :(得分:0)

受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)

希望这有帮助!