How do I start a session in a Python web application?

前端 未结 5 1884
盖世英雄少女心
盖世英雄少女心 2020-12-10 08:18

This question is based on this answer.

I\'m looking for a function similar to PHP\'s session_start() for Python. I want to access a dictionary like

相关标签:
5条回答
  • 2020-12-10 08:36

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

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

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

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

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

    0 讨论(0)
  • 2020-12-10 08:36

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

    http://docs.djangoproject.com/en/dev/topics/http/sessions/

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

    http://code.activestate.com/recipes/325484/

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

    0 讨论(0)
  • 2020-12-10 08:38

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

    http://beaker.groovie.org/

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

    0 讨论(0)
  • 2020-12-10 08:47

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

    #!/usr/local/bin/python3 
    # SheBang C:/Apps/Python0306/python.exe 
    
    import os, cgi, sys 
    sys.stderr = sys.stdout 
    import cgitb 
    cgitb.enable()                       
    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")]     
    lst_PostValues.pop()
    lst_PostValues.pop()  
    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>") 
    
    try:
        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'>")    
    except:
          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>") 
    
    try:            
        print ("Menu Button Selected: " + str(lst_Matrix[0][1]))
    except: 
        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>") 
    
    0 讨论(0)
  • 2020-12-10 08:49

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

    Here's how 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)
        c.save()
        request.session['has_commented'] = True
        return HttpResponse('Thanks for your comment!')
    

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

    0 讨论(0)
提交回复
热议问题