17-3 cookies and sessions

1. Cookies
1.What are cookies?
Key-value pairs saved in the browser!
When the server returns the response, it tells the browser the saved key-value pair! Browsers can refuse to save cookies.
2. Why are cookies needed?
HTTP requests are stateless, we need to save the state –> cookie
3. Use of cookies in Django
1. Set cookies
rep = HttpResponse(“ok”)
rep.set_cookie(“key”, “value”, max_age=xx seconds)
rep.set_signed_cookie(“key”, “value”, salt=”ooxx”, max_age=xx seconds)
2. Get cookies
request.COOKIES.get(“key”)
request.get_signed_cookie(“key”, default=””, salt=”ooxx”)

Parameters:

  • default: default value
  • salt: encryption salt
  • max_age: background control expiration time

4. Cookies have expiration time
1. If it is not set in Django, it will become invalid if you close the browser.
2. Set the timeout through max_age

5. 3 additional points:
1. How to log in and then jump back to the page you visited before

Write a login function: example

 1 def login(request):
 2 if request.method == "POST":
 3 path = request.GET.get("path")
 4 print(path)
 5 username = request.POST.get("username")
 6 pwd = request.POST.get("pwd")
 7 if username == "alex" and pwd == "123":
 8 if path:
 9 rep = redirect(path)
10 else:
11 rep = redirect("/publisher_list/")
12 rep.set_signed_cookie("hu", "hao", salt="ooxx", max_age=7)
13 return rep
14 else:
15 return HttpResponse("Incorrect username or password")
16 else:
17
18 return render(request, "login.html")

Write a decorator

from functools import wraps


# Decorator version login authentication
def login_check(func):
    @wraps(func)
    def inner(request, *args, **kwargs):
        path = request.path_info
        # Login authentication
        v = request.get_signed_cookie("hu", default="", salt="ooxx") # Get the salted cookie
        if v == "hao":
            return func(request, *args, **kwargs)
        else:
            return redirect("/login/?path={}".format(path))

    return inner

You want to visit the page, add the decorator to it

@login_check
def book_list(request):
    data = models.Book.objects.all()
    return render(request, "book_list.html", {"book_list": data})

When you finally visit, the book_list page will ask you to log in first and splice a directory after the url.

http://127.0.0.1:8001/login/?path=/book_list/, then log in successfully and jump to book_list

Note: The action in the login.html file must be empty, otherwise it cannot jump, or it must be written as {{request.get_path_info}}

2. How to apply FBV’s decorator to CBV?

Import in views

from django.utils.decorators import method_decorator

that is

 @method_decorator(login_check) Inside the brackets is the decorator function you wrote

example:

class AddBook(views.View):

    @method_decorator(login_check) # login_check is the decorator function just written
    def get(self, request):
        data = models.Publisher.objects.all()
        return render(request, "add_book.html", {"publisher_list": data})

    def post(self, request):
        book_name = request.POST.get("title")
        publisher_id = request.POST.get("publisher")
        publisher_obj = models.Publisher.objects.get(id=publisher_id)
        #Create book
        models.Book.objects.create(
            title=book_name,
            publisher_id=publisher_id
            # publisher=publisher_obj
        )
        return redirect("/book_list/")

3. Decorator repair technology –> from functools import wraps

Add @wraps(func) on the inner function. If not added by default, it will not affect the use. However, the decorated function name and annotation information cannot be viewed.

example:

from functools import wraps


def wrapper(func):
    @wraps(func) # Use built-in tools to repair decorated functions
    def inner(*args, **kwargs):
        print("haha")
        func(*args, **kwargs)
    return inner


@wrapper
def foo(arg):
    """
    This is a function that tests the decorator
    :param arg: int must be of type int
    :return: None
    """
    print("Hey hey hey" * arg)


foo(10)
print(foo.__doc__)

Two sessions

Why have a session?
1. Disadvantages of Cookied:
1. The amount of data is only 4096
2. The data is stored on the client (browser), which is not safe.

2.Session
Key-value pairs saved on the server
1. After the request comes, a random string is still generated.
2. Use a random string as the key to generate a large dictionary on the server. The actual data saved is the value.
3. Reply the random string to the browser in the form of a cookie
4. The next time the request comes again, it will carry the random string from the previous step.
5. Get a random string from the request,
6. Go to the backend and use the random string as the key to find the corresponding value.
7. What is stored in value is really useful data.
3. How to use Session in Django
1. Whether setting or obtaining the Session, they are all operated on the request object.
2. Set up Session
request.session[“key”] = “value”
3. Get session
request.session.get(“key”)
4. Other commonly used commands
?1. # Delete all data whose Session expiration date is less than the current date
request.session.clear_expired()
2. # Delete the current session data and delete the session cookies.
request.session.flush()
3. Set timeout time
request.session.set_expiry(7)
5. Commonly used configuration items (written in Settings.py)
# Globally configure session timeout
SESSION_COOKIE_AGE = 60 * 60 * 24 * 2 #7 days

# Whether to refresh the session timeout with each request
SESSION_SAVE_EVERY_REQUEST = True

example:

def login_check(func):
    @wraps(func)
    def inner(request, *args, **kwargs):
        next = request.path_info
        # Login authentication
        # Get Session
        v = request.session.get("s21")
        if v == "hao":
            return func(request, *args, **kwargs)
        else:
            return redirect("/login/?next={}".format(next))

    return inner


# Login session verification
def login(request):
    if request.method == "POST":
        next = request.GET.get("next")
        username = request.POST.get("username")
        pwd = request.POST.get("pwd")
        if username == "alex" and pwd == "123":
            if next:
                rep = redirect(next)
            else:
                rep = redirect("/secode/")
            request.session["s21"] = "hao"
            request.session.set_expiry(70)
            return rep
        else:
            return HttpResponse("Let's go")
    else:
        return render(request, "login.html")


@login_check
def index(request):
    return render(request, "index.html")


@login_check
def secode(request):
    return render(request, "secode.html")

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. MySQL entry-level skills treeDatabase compositionTable 69881 people are learning the system