Django requests
-
1. Common request methods
The default page requests are get requests. In view functions, request is the request passed to the view, which contains the parameters of the request
Common request methods get and POST:
-
Get: The default get request is displayed on the route in plain text. The format of get is? To split a key-value pair, begin with the form of a key equal to a value, and begin with &. This is usually used to obtain resources from the server www.baidu.com/s?wd= ssam&rsv…
-
Post: Request data is sent hidden, with higher security. Typically used to submit resources to the server
-
-
2. Request object
In the view function, Request is the request object passed to the view, which contains all information about the request
def index(request):
return render(request, "index.html")
Copy the code
The request object is of type django.http.HttpRequest. The common properties are shown in the table below:
methods | instructions |
---|---|
request.GET | A method to get the get request data |
request.POST | A method to get the POST request data |
request.FILES | Method of getting file upload request data |
request.method | Method to get the request |
request.META | Detailed parameters of the request |
request.META.OS | Requester system |
request.META.HTTP_USER_AGENT | User request header that returns the browser version requested |
request.META.HTTP_HOST | Requested host |
request.META.HTTP_REFERER | Source of request |
Second, the CSRF
Cross-site request forgery is an attack method that tricks users into performing unintended actions on currently logged Web applications
With a little help from social engineering (such as sending a link via E-mail or chat), an attacker might trick the user of a Web application into performing an action of the attacker’s choosing
Django forms
-
The HTML form
attribute instructions action Submitted address, default is the current route method The default method for submission is GET name Used as the identifier for parameter transmission submit Data for the current form is automatically submitted -
The back-end processing
def register(request): "" "register "" " if request.method == "GET": # GET jump to page return render(request, "register.html") else: # POST handles the submission # get parameters name = request.POST.get("name") password = request.POST.get("password") Create an object and add it # Seller.objects.create( # name=name, # password=encryption_md5(password) #) # create object seller = Seller() seller.name = name seller.password = encryption_md5(password) # new seller.save() # response return HttpResponse("Registration successful") Copy the code
-
Comment out CSRF middleware CSRF cross-site request forgery: An operation on a specified web site using a cookie that is still active in the current browser. Initially, it targeted transfers to bank websites
-
In any Post request, Django sends the user a string of identifiers at the beginning of the request. Each request is different. If CSRF is not added, a CSRF error will occur
-
Use Django’s CSRF validation
Render {% csrf_token %} render {% csrf_token %} render {% csrf_token %} render {% csrf_token %} render {% csrf_token %} render {% csrf_token %} render {% csrf_token %}
In the first line inside the form, insert the CSRF checksum using {% csrf_token %}
Djangos express classes
-
Introduction to Form classes
User forms are a basic feature on the Web side, and the large, comprehensive Django framework naturally comes with the basic Form object Form Form functionality already in place:
Automatically generate HTML form elements
2. Check the validity of form data (backend verification)
3. Redisplay form if validation error (data will not reset)
4. Data type conversion (converting character data to the corresponding Python type)
1. Front-end validation: When Django form class objects are rendered to a template, they become HTML attached property tags. These are properties, typically HTML5 properties, that can be interacted with
from django import forms from django.core.validators import RegexValidator,ValidationError
Create a form class
from django import forms from django.core.validators import ValidationError, RegexValidator class LoginForm(forms.Form): """ Form class for login authentication """ name = forms.CharField( required=True, max_length=10, min_length=2, error_messages={ "required":"Username Required"."max_length":"No more than 10 user names."."min_length":"Username must be at least two digits." }) password = forms.CharField( required=True, error_messages={ "required": "Password required",})Copy the code
(2) Template page
<div class="form-group"> <input type="text" class="form-control form-control-user" name="name" id="username" Placeholder =" username "value="{{login_form.data.name}}"> <label>{{login_form.errors.name.0}}</label> </div>Copy the code
(3), the view
def login(request): Login "" "" "" login_form = LoginForm() if request.method == "GET": # GET jump to page return render(request, "login.html", locals()) else: # POST handles the submission Get the parameters and put them into the form for verification login_form = LoginForm(request.POST) Check whether the verification is successful if login_form.is_valid(): Verify success # get parameters name = login_form.cleaned_data.get("name") password = login_form.changed_data("password") # query seller = Seller.objects.filter(name=name, password=encryption_md5(password)).first() # judgment if seller: return redirect("/index/") else: return redirect("/login/") else: return render(request, "login.html", locals()) Copy the code
Django form validation
When validating a Field, you can pass in a Validators parameter to specify validators. There are many validators to further filter the data, but many validators can already be specified with this Field or with some parameters
For example, EmailValidator can be specified by EmailField, or MaxValueValidator can be specified by the max_value parameter
Here are some common validators:
The validator | describe |
---|---|
MaxValueValidator | Verification maximum |
MinValueValidator | Verification minimum |
MinLengthValidator | Verification minimum length |
MaxLengthValidator | Verification maximum length |
EmailValidator | Verify whether it is a mailbox format |
URLValidator | Verify that it is in URL format |
RegexValidator | Validation of regular expressions |
-
Custom check
Djangos Form classes also provide custom validation for specific fields. In the Form class, instance methods are defined with the name “clearN_ validated field name.” If validation fails, a ValidationError is raised, otherwise the value is returned normally
Exception information can be displayed in the front end
-
forms.py
# Custom validator class MyValidator: def __call__(self, value): """ Custom validation :param value: value indicates the data to be validated :return: If ValidationError indicates validation failure normal end table validation passes """ datas = ["sb"."xx"] for data in datas: ifvalue.find(data) ! =- 1: raise ValidationError("Username must not contain sensitive words.") class RegisterForm(forms.Form): """ Form class to register for validation """ name = forms.CharField( required=True, validators=[ # 2-10 digit character number underscore RegexValidator(R "^ [a zA - Z0-9 _] {2, 10} $"."User names must be 2-10 alphanumeric underscores."), # Custom validator MyValidator() ], error_messages={ "required": "Username Required", } ) password = forms.CharField( required=True, error_messages={ "required": "Password required"})Copy the code
#### djangos session mechanismCopy the code
-
cookie
Set time: the default is UTC, 8 hours out of our current local time. TIME_ZONE = ‘Asia/Shanghai’ USE_TZ = False
The operation of the cookie
Response can be obtained by: (1) Response = HttpResponse(” xx “) (2) Response = render(request, “xx.html”) (3) response = redirect(” /index “)
Cookie Response. set_cookie(key, value, validity period) The validity period is in seconds
Delete cookie response.delete_cookie
Cookie request.cookie.get(key)
-
sesison
Sessions are implemented based on cookies. The default configuration in Django stores session data to the database. Set up the session
The operation of the session
Session [key] = Value The validity period is 2 weeks by default. You can modify request.session.set_expiry(time) in seconds
Get session request.session.get(key)
Request.session.clear () deletes all key pairs
Consider several cases where the server does not get a session:
1. The client did not send the sessionID. 2. The client sent the sessionID, but the sessionID was not found in the database