Home Backend Development Python Tutorial 在Python的Django框架的视图中使用Session的方法

在Python的Django框架的视图中使用Session的方法

Jun 10, 2016 pm 03:08 PM
django session

SessionMiddleware 激活后,每个传给视图(view)函数的第一个参数``HttpRequest`` 对象都有一个 session 属性,这是一个字典型的对象。 你可以象用普通字典一样来用它。 例如,在视图(view)中你可以这样用:

# Set a session value:
request.session["fav_color"] = "blue"

# Get a session value -- this could be called in a different view,
# or many requests later (or both):
fav_color = request.session["fav_color"]

# Clear an item from the session:
del request.session["fav_color"]

# Check if the session has a given key:
if "fav_color" in request.session:
 ...

Copy after login

其他的映射方法,如 keys() 和 items() 对 request.session 同样有效:

下面是一些有效使用Django sessions的简单规则:

用正常的字符串作为key来访问字典 request.session , 而不是整数、对象或其它什么的。

Session字典中以下划线开头的key值是Django内部保留key值。 框架只会用很少的几个下划线 开头的session变量,除非你知道他们的具体含义,而且愿意跟上Django的变化,否则,最好 不要用这些下划线开头的变量,它们会让Django搅乱你的应用。

比如,不要象这样使用`` _fav_color`` 会话密钥(session key):

request.session['_fav_color'] = 'blue' # Don't do this!

Copy after login

不要用一个新对象来替换掉 request.session ,也不要存取其属性。 可以像Python中的字典那样使用。 例如:

request.session = some_other_object # Don't do this!

request.session.foo = 'bar' # Don't do this!

Copy after login

我们来看个简单的例子。 这是个简单到不能再简单的例子:在用户发了一次评论后将has_commented设置为True。 这是个简单(但不很安全)的、防止用户多次评论的方法。

def post_comment(request):
 if request.method != 'POST':
  raise Http404('Only POSTs are allowed')

 if 'comment' not in request.POST:
  raise Http404('Comment not submitted')

 if request.session.get('has_commented', False):
  return HttpResponse("You've already commented.")

 c = comments.Comment(comment=request.POST['comment'])
 c.save()
 request.session['has_commented'] = True
 return HttpResponse('Thanks for your comment!')

Copy after login

下面是一个很简单的站点登录视图(view):

def login(request):
 if request.method != 'POST':
  raise Http404('Only POSTs are allowed')
 try:
  m = Member.objects.get(username=request.POST['username'])
  if m.password == request.POST['password']:
   request.session['member_id'] = m.id
   return HttpResponseRedirect('/you-are-logged-in/')
 except Member.DoesNotExist:
  return HttpResponse("Your username and password didn't match.")

Copy after login

下面的例子将登出一个在上面已通过`` login()`` 登录的用户:

def logout(request):
 try:
  del request.session['member_id']
 except KeyError:
  pass
 return HttpResponse("You're logged out.")

Copy after login

注意

在实践中,这是很烂的用户登录方式,稍后讨论的认证(authentication )框架会帮你以更健壮和有利的方式来处理这些问题。 这些非常简单的例子只是想让你知道这一切是如何工作的。 这些实例尽量简单,这样你可以更容易看到发生了什么
设置测试Cookies

就像前面提到的,你不能指望所有的浏览器都可以接受cookie。 因此,为了使用方便,Django提供了一个简单的方法来测试用户的浏览器是否接受cookie。 你只需在视图(view)中调用 request.session.set_test_cookie(),并在后续的视图(view)、而不是当前的视图(view)中检查 request.session.test_cookie_worked() 。

虽然把 set_test_cookie() 和 test_cookie_worked() 分开的做法看起来有些笨拙,但由于cookie的工作方式,这无可避免。 当设置一个cookie时候,只能等浏览器下次访问的时候,你才能知道浏览器是否接受cookie。

检查cookie是否可以正常工作后,你得自己用 delete_test_cookie() 来清除它,这是个好习惯。 在你证实了测试cookie已工作了之后这样操作。

这是个典型例子:

def login(request):

 # If we submitted the form...
 if request.method == 'POST':

  # Check that the test cookie worked (we set it below):
  if request.session.test_cookie_worked():

   # The test cookie worked, so delete it.
   request.session.delete_test_cookie()

   # In practice, we'd need some logic to check username/password
   # here, but since this is an example...
   return HttpResponse("You're logged in.")

  # The test cookie failed, so display an error message. If this
  # were a real site, we'd want to display a friendlier message.
  else:
   return HttpResponse("Please enable cookies and try again.")

 # If we didn't post, send the test cookie along with the login form.
 request.session.set_test_cookie()
 return render_to_response('foo/login_form.html')

Copy after login

注意

再次强调,内置的认证函数会帮你做检查的。

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to check django version How to check django version Dec 01, 2023 pm 02:25 PM

Steps to check the Django version: 1. Open a terminal or command prompt window; 2. Make sure Django has been installed. If Django is not installed, you can use the package management tool to install it and enter the pip install django command; 3. After the installation is complete , you can use python -m django --version to check the Django version.

How to solve session failure How to solve session failure Oct 18, 2023 pm 05:19 PM

Session failure is usually caused by the session lifetime expiration or server shutdown. The solutions: 1. Extend the lifetime of the session; 2. Use persistent storage; 3. Use cookies; 4. Update the session asynchronously; 5. Use session management middleware.

Solution to PHP Session cross-domain problem Solution to PHP Session cross-domain problem Oct 12, 2023 pm 03:00 PM

Solution to the cross-domain problem of PHPSession In the development of front-end and back-end separation, cross-domain requests have become the norm. When dealing with cross-domain issues, we usually involve the use and management of sessions. However, due to browser origin policy restrictions, sessions cannot be shared by default across domains. In order to solve this problem, we need to use some techniques and methods to achieve cross-domain sharing of sessions. 1. The most common use of cookies to share sessions across domains

Django Framework Pros and Cons: Everything You Need to Know Django Framework Pros and Cons: Everything You Need to Know Jan 19, 2024 am 09:09 AM

Django is a complete development framework that covers all aspects of the web development life cycle. Currently, this framework is one of the most popular web frameworks worldwide. If you plan to use Django to build your own web applications, then you need to understand the advantages and disadvantages of the Django framework. Here's everything you need to know, including specific code examples. Django advantages: 1. Rapid development-Djang can quickly develop web applications. It provides a rich library and internal

Django vs. Flask: A comparative analysis of Python web frameworks Django vs. Flask: A comparative analysis of Python web frameworks Jan 19, 2024 am 08:36 AM

Django and Flask are both leaders in Python Web frameworks, and they both have their own advantages and applicable scenarios. This article will conduct a comparative analysis of these two frameworks and provide specific code examples. Development Introduction Django is a full-featured Web framework, its main purpose is to quickly develop complex Web applications. Django provides many built-in functions, such as ORM (Object Relational Mapping), forms, authentication, management backend, etc. These features allow Django to handle large

How to check django version How to check django version Nov 30, 2023 pm 03:08 PM

How to check the django version: 1. To check through the command line, enter the "python -m django --version" command in the terminal or command line window; 2. To check in the Python interactive environment, enter "import django print(django. get_version())" code; 3. Check the settings file of the Django project and find a list named INSTALLED_APPS, which contains installed application information.

What is the difference between django versions? What is the difference between django versions? Nov 20, 2023 pm 04:33 PM

The differences are: 1. Django 1.x series: This is an early version of Django, including versions 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8 and 1.9. These versions mainly provide basic web development functions; 2. Django 2.x series: This is the mid-term version of Django, including 2.0, 2.1, 2.2 and other versions; 3. Django 3.x series: This is the latest version series of Django. Including versions 3.0, 3, etc.

How to upgrade Django version: steps and considerations How to upgrade Django version: steps and considerations Jan 19, 2024 am 10:16 AM

How to upgrade Django version: steps and considerations, specific code examples required Introduction: Django is a powerful Python Web framework that is continuously updated and upgraded to provide better performance and more features. However, for developers using older versions of Django, upgrading Django may face some challenges. This article will introduce the steps and precautions on how to upgrade the Django version, and provide specific code examples. 1. Back up project files before upgrading Djan

See all articles