[ACCEPTED]-How do I start a session in a Python web application?-session

Accepted answer
Score: 10

Let me address some things that might be 44 related to your question...it may not be 43 relevant for you, but I think others might 42 come here with the exact same question and 41 might benefit from my (limited) experience...because 40 I also had this question at one time.

Speaking 39 as someone who went from PHP to Python (and 38 never looked back), I think it's useful 37 to understand how sessions work under the 36 hood. It's probably not a good idea to implement 35 your own session framework unless you (a) want 34 to understand more about sessions management 33 by doing or (b) need something that existing 32 frameworks don't offer.

Wikipedia is always a good 31 place to start. Bottom line: session data 30 gets stored somewhere on the server and 29 indexed by a unique identifier (hash of 28 some sort). This identifier gets passed 27 back and forth between the client and server, usually 26 as a cookie or as part of the query string 25 (the URL). For security's sake, you'll 24 want to use an SSL connection or validate 23 the session ID with some other piece of 22 data (e.g. IP address). By default PHP 21 stores sessions as files, but on a shared 20 server that could pose a security risk, so 19 you might want to override the session engine 18 so you store sessions in a database. Python 17 web frameworks have similar functionality.

When 16 I started doing web programming in Python, I 15 noticed two things. First, PHP wrapped 14 a lot of magic into the language, making 13 it easy for a beginning programmer (me in 12 2003) to learn the language, but not teaching 11 me much about how everything worked. Therefore, I 10 found myself researching many topics about 9 web applications, specifically database 8 connection pooling, URL mapping, sessions, and 7 threading. PHP (and Django, from what I 6 understand) abstract that away for you. Second, PHP 5 is a really crappy language ;) but it gets 4 the job done!!

Personally I use CherryPy 3 for web development. It has session management 2 as a "tool" that you can turn 1 on.

Score: 8

As someone who comes from PHP and is working 12 his way into Python I can tell you that 11 Django is a good way to start dealing with Python 10 on the web. This is especially true if 9 you've been using MVC frameworks in PHP. That said, Django has 8 built in support for session management 7 and is documented here:


And, out of curiousity, I 6 took a look around for session management 5 with plain python and found this:


Judging 4 by the comments, it would seem that you're 3 better off using one of the tried and true 2 frameworks to handle this for you. If you're 1 not interested in Django you can also checkout some of the others

Score: 5

You might consider looking into the Beaker 9 library for Python which isn't tied to any 8 one web framework an will work in a WSGI 7 compatible environment:


Beaker is a library 6 for caching and sessions for use with web 5 applications and stand-alone Python scripts 4 and applications. It comes with WSGI middleware 3 for easy drop-in use with WSGI based web 2 applications, and caching decorators for 1 ease of use with any Python based application.

Score: 3

Python is not a web language in itself like 12 PHP, so it has not built in web features. There 11 are many modules that add this functionality 10 however, but then you'll have to be specific 9 about which one you're using.

Here's how 8 you could use it with the Django framework, for example:

def post_comment(request, new_comment):
    if request.session.get('has_commented', False):
        return HttpResponse("You've already commented.")
    c = comments.Comment(comment=new_comment)
    request.session['has_commented'] = True
    return HttpResponse('Thanks for your comment!')

In simpler 7 web frameworks there might not be session 6 support. Sessions aren't impossible to implement 5 yourself, but you can probably find a stand-alone 4 module that adds support by receiving/sending 3 the session id to it (the session id is 2 stored in a cookie, which almost all web 1 frameworks have some kind of support for.)

Score: 0

This works with Python 3.6 on Osx with Apache 2 and zero frameworks. Just straight up Cgi 1 Bin.

# SheBang C:/Apps/Python0306/python.exe 

import os, cgi, sys 
sys.stderr = sys.stdout 
import cgitb 
from http import cookies 
from urllib.request import urlopen 

import urllib 
import urllib.request
import urllib.parse
import http.cookiejar

import requests 

import datetime    
import random      

ary_CgiData = cgi.FieldStorage() 
lst_PostValues = [("Alpha","Bravo"), ("Charlie","Delta")]     
str_Line = ""
variable = ""
value = ""
r = ""
for key in ary_CgiData.keys():  
    variable = str(key)
    value = str(ary_CgiData.getvalue(variable))
    lst_PostValues.append([variable, value]) 

lst_Matrix = lst_PostValues 
str_HtmlTable = "<table border=1>" 
int_R    = 0 
int_C    = 0 
int_Rows = len(lst_Matrix) 
if int_Rows > 0:
    int_Cols = len(lst_Matrix[0]) 
    while (int_R < int_Rows):  
        str_HtmlTable = str_HtmlTable + "<tr>" 
        for int_C in range(int_Cols): 
            str_HtmlTable = str_HtmlTable + "<td>" + str(lst_Matrix[int_R][int_C]) + "</td>"
        str_HtmlTable = str_HtmlTable + "</tr>" 
        int_R = int_R + 1 
    str_HtmlTable = str_HtmlTable + "</table>"    
str_MenuSelectList = str_HtmlTable

print ("Content-Type: text/html\n\n") 
print ("<html>") 

    if str(lst_Matrix[0][1]) == "AddCookies":
        print ("<meta http-equiv='Set-Cookie' content='TestUniversity=ABCDEFGHIJK9876543210;expires=Wednesday, 08-Aug-2025 23:59:59 GMT'>")
    if str(lst_Matrix[0][1]) == "DeleteCookies":
        print ("<meta http-equiv='Set-Cookie' content='TestUniversity=ABCDEFGHIJK9876543210;expires=Wednesday, 08-Aug-1990 23:59:59 GMT'>")    
      int_X = 0

str_CookieTest001 = "" 
handler = {} 
if 'HTTP_COOKIE' in os.environ: 
    cookies = os.environ['HTTP_COOKIE'] 
    cookies = cookies.split('; ') 

    for cookie in cookies: 
        cookie = cookie.split('=') 
        handler[cookie[0]] = cookie[1] 

for k in handler: 
    str_CookieTest001 += (k + " = " + handler[k] + "<br>") 

print ("</head>")
print ("<title>Enter Some Title Here </title>") 
print ("<body>") 
print ("<br><center>Test Example </center><br>") 
print ("<form action='012_SubmittedCode.py' method='post' >") 
print ("<table border=1>") 
print ("<tr><td><center><input type='submit' value='AddCookies' name='MenuSelect'></td>") 
print ("<td><input type='submit' value='DeleteCookies' name='MenuSelect' ></td></tr>") 
print ("</table>") 
print ("<hr><hr>") 
print ("</form>") 
print ("<hr><hr>")

print ("</form>") 

    print ("Menu Button Selected: " + str(lst_Matrix[0][1]))
    int_X = 1

print ("<hr><br>")
print ("Menu Option Selected:<br>") 
print (str_MenuSelectList)
print ("<br><hr>")

print ("############ Cookie Return array Method of Choice ############<br><hr>") 
print (str_CookieTest001) 
print ("<hr><hr>")
print ("</body>")
print ("</html>") 

More Related questions