No Cookie: how to implement session?

I V wrongbad at gmail.com
Wed Mar 29 16:32:27 EST 2006


Sullivan WxPyQtKinter wrote:
> As you said, ....There is no solution? I mean, tracing a real session
> without using tricks like hidden field and cookies in CGI script?

As people have said, this isn't a limitation of python, it's a feature
of HTTP. You might want to consider whether you actually need sessions
- see if you can design your application to use REST (see e.g.
http://www.xfront.com/REST-Web-Services.html , or there's lots of
information on Google).

People have also mentioned this in passing, but third alternative to
cookies and hidden fields is to use a session key in the query string -
this can be used for GET requests, so would work in redirects as well
as form submissions. Try:

http://yoursite.example/page?session=key

Then you need to remember, whenever you include a link to your site
that should retain the session information to add the session key to
the URL. You could define a function:

def session_url(url, key, **params={}):
    qstring = "%s=%s" % ('session', urllib.quote(key))
    for (name, value) in params.items():
        qstring += "&%s=%s" %(urllib.quote(name), urllib.quote(value))
    return qstring

And use it like:

#Do redirect
print "Location: " + session_url('new_page', session_key)

Or:

# Redirect to a page that loads the item called 'anitem'
print "Location: " + session_url('new_page', session_key, {'item',
'anitem'})

If you want to link to this URL in an HTML page, you need to remember
to escape the '&' character:

print "<a href='%s'>Edit item %s</a>" % (cgi.escape(session_url('edit',
session_key, {'item', item_name})), item_name)

Then, if you need to submit a form, you can add the key as a hidden
field.




More information about the Python-list mailing list