Development process
The development model uses a front-end separation model, and as a back-end developer we focus only on backend business logic development:
Omit the configuration section of the Project framework setup file ....
One: User part
In the project development, we need to use the user model class User,django authentication system to provide the user model classes and users of the relevant operation methods; The custom user model needs to add extra fields when the user model does not meet our requirements.
Such as:
Define user model classes for users in the creation of a good app models.py.
Class User (Abstractuser):
"" User model Class "" "
Mobile = models. Charfield (max_length=11, Unique=true, verbose_name= ' mobile phone number ')
Class Meta:
db_table = ' Tb_users '
Verbose_name = ' user '
Verbose_name_plural = Verbose_name
Our custom user model classes are not directly recognized by Django's authentication system, and we need to tell the Django authentication system in the configuration file to use our custom model classes.
Setting in a configuration file
Auth_user_model = ' users. User '
The settings for the Auth_user_model parameter are delimited by dots. The name of the application. Model class name.
User Registration Verification code gets the interface logic settings:
Import Random
From django.shortcuts Import Render
From rest_framework.views import Apiview
From Rest_framework.response Import response
From rest_framework import status
From Django_redis import get_redis_connection
From verifications Import constants
From meiduo_mall.libs.yuntongxun.sms import CCP
# Create your views here.
# Get Logger
Import logging
Logger = Logging.getlogger (' Django ')
# get/sms_codes/(? P<MOBILE>1[3-9]\D{9})/
Class Smscodeview (Apiview):
def get (self, request, mobile):
"""
Get SMS Verification Code:
1. Generate SMS Verification Code content
2. Save SMS Verification code content in Redis with ' mobile ' as key and SMS CAPTCHA content as value
3. Send SMS verification code using cloud communication
4. Return reply, send SMS successfully
"""
# Determine if a text message was sent to ' mobile ' within 60s
Redis_conn = get_redis_connection (' verify_codes ')
Send_flag = Redis_conn.get (' send_flag_%s '% mobile)
If Send_flag:
Return Response ({' message ': ' Send sms Too often '}, status=status. Http_400_bad_request)
# 1. Generate SMS Verification code content, randomly generate a 6-digit number
Sms_code = '%06d '% random.randint (0, 999999)
# 2. Save SMS Verification code content in Redis with ' mobile ' as key and SMS CAPTCHA content as value
# redis_conn.set (' <key> ', ' <value> ', ' <expires> ')
# Redis_conn.setex (' <key> ', ' <expires> ', ' <value> ')
# Redis Pipeline: You can add multiple Redis commands to a pipeline, and then execute them once
PL = Redis_conn.pipeline ()
# Add a command to a pipeline
Pl.setex (' sms_%s '% Mobile, constants.sms_code_redis_expires, Sms_code)
# set up a tag to send SMS to ' mobile '
Pl.setex (' send_flag_%s '% mobile, constants. Send_sms_code_interval, 1)
# Execute a command in the pipeline
Pl.execute ()
# 3. Send SMS verification code using cloud communication
expires = constants.sms_code_redis_expires//60
# try:
# res = CCP (). send_template_sms (Mobile, [Sms_code, expires], constants.sms_code_temp_id)
# except Exception as E:
# Logger.error (' Mobile:%s, sending SMS exception '% mobile)
# return Response ({' message ': ' Send SMS Exception '}, Status=status. http_503_service_unavailable)
#
# if Res! = 0:
# # Send SMS Failed
# return Response ({' message ': ' Send SMS Exception '}, Status=status. http_503_service_unavailable)
# Send SMS Task
From Celery_tasks.sms.tasks import Send_sms_code
Send_sms_code.delay (Mobile, Sms_code, expires)
# 4. Return answer, send SMS successfully
Return Response ({' message ': ' OK '})
Knowledge points used: Celery asynchronous task queue
##### 4. Celery Asynchronous Task queue
Essence:
? Use a process or a calling function to implement Asynchrony.
Basic concepts:
? Issuer: Issue all performed tasks (tasks are functions).
? (Man-in-the-middle) Task queue: Stores the task information to be performed.
? Processor: That is, the work process or the association, is responsible for listening to the task queue, the discovery task executes the corresponding task function.
Characteristics:
? 1) Task senders and handlers can be distributed across different computers, exchanging information through intermediaries.
? 2) tasks in the task queue are sorted, and the task that is added first is executed first.
Use:
? 1) Install pip install celery
? 2) Create the Celery object and configure the man-in-the-middle address
? From celery import celery
? Celery_app = Celery (' demo ')
? Configuration file: Broker_url= ' man-in-the-middle address '
? Celery_app.config_from_object (' config file path ')
? 3) Defining task functions
? @celery_app. Task (name= ' My_first_task ')
? Def my_task (A, B):
? Print (' Task function is executed ')
? ...
? 4) Start worker
? Celery-a ' celery_app file path ' worker-l info
? 5) Issue a task
? My_task.delay (2, 3)
Problems encountered:
Cross-Domain requests:
We need to add support for cross-domain access for the backend, and to use Cors to resolve backend support for cross-domain access (django-cors-headers extension), with different domain names at the back end;
##### 3. Cross-Domain requests
Browser of the same origin policy: * * protocol, host IP and port ports the same address is the same origin, otherwise non-homologous * *.
When the requested page address and the requested address are not of the same origin, the request is a cross-domain request * *.
When the request is initiated, if the browser discovers that the request is a cross-domain request, the following information is added in the requested header:
> Origin: Source Request IP Address
>
> Example: origin:http://www.meiduo.site:8080
In the response returned by the requested server, if the response header contains the following information:
> access-control-allow-origin: Source Request IP Address
>
> Example: access-control-allow-origin:http://www.meiduo.site:8080
Then the browser considers that the requested server supports cross-domain requests from the source address, otherwise it is not considered to be supported, and the browser rejects the request directly.
Solution process:
Installation
Pip Install Django-cors-headers
Add an App
Installed_apps = (
...
' Corsheaders ',
...
)
Middle tier settings
Middleware = [
' Corsheaders.middleware.CorsMiddleware ',
...
]
Add White List
# CORS
Cors_origin_whitelist = (
' 127.0.0.1:8080 ',
' localhost:8080 ',
' www.meiduo.site:8080 ',
)
Cors_allow_credentials = True # Allow cookies to be carried
Any domain name that appears in the whitelist can access the backend interface
Cors_allow_credentials indicates whether the backend supports operation of cookies (not yet continued) in cross-domain access
The basic process of developing a web-based shopping site with the Django framework and the knowledge points used to summarize 1