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

前端 未结 5 1935
盖世英雄少女心
盖世英雄少女心 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条回答
  •  萌比男神i
    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.)

提交回复
热议问题