[Python+Django]初心者筆記9(如何使用session)
使用session方式跟其他程式語言很像,以home page作為範例:
先改/locallibrary/catalog/views.py的index()如下:
如此便在server side加入了session變數
# Create your views here.
from .models import Book, Author, BookInstance, Genre
def index(request):
"""
View function for home page of site.
"""
# Generate counts of some of the main objects
num_books=Book.objects.all().count()
num_instances=BookInstance.objects.all().count()
# Available books (status = 'a')
num_instances_available=BookInstance.objects.filter(status__exact='a').count()
num_authors=Author.objects.count() # The 'all()' is implied by default.
num_book_title_icontain_how = Book.objects.filter(title__icontains = 'how').count()
#這是利用session來記錄訪客的來訪次數
# Number of visits to this view, as counted in the session variable.
num_visits=request.session.get('num_visits', 0)
request.session['num_visits'] = num_visits+1
# Render the HTML template index.html with the data in the context variable
return render(
request,
#index()最後將會導向到下列這個.html檔案:index.html
'index.html',
#並且把剛剛從db取得的物件傳送到index.html
# context={'num_books':num_books,'num_instances':num_instances,'num_instances_available':num_instances_available,'num_authors':num_authors},
# context={'num_books':num_books,'num_instances':num_instances,'num_instances_available':num_instances_available,'num_authors':num_authors,'num_book_title_icontain_how':num_book_title_icontain_how},
#把session的num_visits變數也加進去
context={'num_books':num_books,'num_instances':num_instances,
'num_instances_available':num_instances_available,'num_authors':num_authors,
'num_book_title_icontain_how':num_book_title_icontain_how,'num_visits':num_visits},
)
接著再修改/locallibrary/catalog/templates/index.html,在(block content + endblock)區塊的最後加入下面這行:
讓網頁端去讀取這個訪客變數
<p>You have visited this page {{ num_visits }}{% if num_visits == 1 %} time{% else %} times{% endif %}.</p>
如此一來變可以在catalog的home page看到訪客來訪次數了:
這篇大概先這樣…
參考資料:
Django Tutorial Part 7: Sessions framework
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Sessions