python: interact with the session in cgi scripts

杀马特。学长 韩版系。学妹 提交于 2019-12-10 15:56:56

问题


Can python cgi scripts write and read data to the session? If so how? Is there a high-level API or must I roll my own classes?


回答1:


There's no "session" on cgi. You must roll your own session handling code if you're using raw cgi.

Basically, sessions work by creating a unique cookie number and sending it on a response header to the client, and then checking for this cookie on every connection. Store the session data somewhere on the server (memory, database, disk) and use the cookie number as a key to retrieve it on every request made by the client.

However cgi is not how you develop applications for the web in python. Use wsgi. Use a web framework.

Here's a quick example using cherrypy. cherrypy.tools.sessions is a cherrypy tool that handles cookie setting/retrieving and association with data automatically:

import cherrypy

class HelloSessionWorld(object):
    @cherrypy.tools.sessions()
    def index(self):
        if 'data' in cherrypy.session:
            return "You have a cookie! It says: %r" % cherrypy.session['data']
        else:
            return "You don't have a cookie. <a href='getcookie'>Get one</a>."
    index.exposed = True

    @cherrypy.tools.sessions()
    def getcookie(self):
        cherrypy.session['data'] = 'Hello World'
        return "Done. Please <a href='..'>return</a> to see it"
    getcookie.exposed = True

application = cherrypy.tree.mount(HelloSessionWorld(), '/')

if __name__ == '__main__':
    cherrypy.quickstart(application)

Note that this code is a wsgi application, in the sense that you can publish it to any wsgi-enabled web server (apache has mod_wsgi). Also, cherrypy has its own wsgi server, so you can just run the code with python and it will start serving on http://localhost:8080/




回答2:


My 'low-cost' web hosting plan don't permit use wsgi. The 'mod_wsgi' apache module can't be used because is a shared apache server. I am developing my own class.

To not start from zero, I am experimenting the implementation of a session class available in this site: http://cgi.tutorial.codepoint.net/a-session-class



来源:https://stackoverflow.com/questions/1554250/python-interact-with-the-session-in-cgi-scripts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!