python:在cgi脚本中与会话进行交互 [英] python: interact with the session in cgi scripts

查看:119
本文介绍了python:在cgi脚本中与会话进行交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

python cgi脚本可以向会话写入和读取数据吗?如果可以,怎么办?有高级API还是我必须自己滚动类?

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?

推荐答案

没有 会话放在 cgi 上。如果您使用的是原始 cgi ,则必须滚动自己的会话处理代码。

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

基本上,会话通过创建一个唯一的cookie号,然后将其在响应标头上发送给客户端,然后在每个连接上检查此cookie。将会话数据存储在服务器上的某个位置(内存,数据库,磁盘)上,并使用cookie号作为密钥,以便在客户端发出的每个请求中都可以检索它。

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.

但是 cgi 不是用python开发Web应用程序的方式。使用 wsgi 。使用网络框架。

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

以下是使用 cherrypy 的简单示例>。 cherrypy.tools.sessions 是一个很好奇的工具,可自动处理cookie设置/检索以及与数据的关联:

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)

请注意,此代码是 wsgi 应用程序,从某种意义上讲,您可以将其发布到任何启用了 wsgi 的Web服务器(Apache具有 mod_wsgi )。另外,cherrypy有自己的 wsgi 服务器,因此您只需使用python运行代码,它将开始在 http:// localhost:8080 /

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/

这篇关于python:在cgi脚本中与会话进行交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆