Add mailbox back-end logic

1. Add mailbox interface design and definition

1. Request mode

options plan
Request method PUT
Request the address /emails/

2. Request parameters

Parameter names type Whether will pass instructions
email string is email

3. Response result: JSON

field instructions
code Status code
errmsg The error message

2. Add mailbox backend logic implementation

"" def put(self, request): Json_dict = JSON.loads (request.body.decode()) email = json_dict. Get ('email') # check if not email: Return HTTP. HttpResponseForbidden (' missing email parameters') if not re. The match (r '^ [a - z0-9] [\ w \ \ -] * @ [a - z0-9 \] + (\. [a-z] {2, 5})} {1, 2 $', Email) : return HTTP. HttpResponseForbidden (' parameter wrong email ') # assignment email field try: request.user.email = email request.user.save() except Exception as e: logger.error(e) return http.JsonResponse({'code': Return http. jsonResponse ({'code': retcode. OK, 'errmsg': 'mailbox added successfully '})

3. Check whether the user is logged in and return JSON

Important Note:

  • Only when the user is logged in can they be bound to the mailbox.
  • At this time, the data type of the backend interaction is JSON, so it is necessary to determine whether the user is logged in and return JSON to the user.

Solution a:

  • Use the Django user authentication systemis_authenticated()
"" def put(self, request): JSON if not request.user.is_authenticated(): return http. jsonResponse ({'code': Retcode. sessionErr, 'errmsg': 'User not logged in '}) pass

Scheme 2:

  • Custom returns JSONlogin_requiredA decorator
  • inmeiduo_mall.utils.views.pyIn the
Def login_required_json(view_func): """ "Decorator that determines if the user is logged in and returns json :param view_func: Decorated view function :return: Json, view_func """ # restore view_func name and document @Wraps (view_func) def wrapper(request, *args, **kwargs): If not request.user.is_authenticated(): return http.jsonResponse ({'code': Retcode. sessionErr, 'errmsg': 'User not logged in '}) else: Return view_func(request, *args, **kwargs) return wrapper class loginRequiredJsonMixin (object): "" @classmethod def as_view(CLS, **initkwargs): view = super().as_view(**initkwargs) return login_required_json(view)

LoginRequiredJSONMixinThe use of

Class EmailView(loginRequiredJsonMixin, View): """ "def put(self, request): """ """ "implementation add mailbox logic """ "# check whether the user is logged in and return JSON pass

Djangos configuration for sending mail

1. Django sends email flow analysis

Introduction to the send_mall() method

  • Location:

    • indjango.core.mailThe module provides thesend_mail()To send mail.
  • Method parameters:

    • send_mail(subject, message, from_email, recipient_list, html_message=None)
Recipient list: HTML _message Multimedia email body, no doubt an HTML string. (Recipient: small potatoes, small potatoes, small potatoes, small potatoes, small potatoes, small potatoes, small potatoes, small potatoes, small potatoes, small potatoes, small potatoes, small potatoes.

2. Prepare to send the email server

1. Click to enter the “Settings” interface

2. Click to enter the “Client Authorization Password” interface

3. Open the Authorization Code and complete the verification message

4. Fill in the Authorization Code

5. Complete the setting of Authorization Code

6. Configure the mail server

EMAIL_BACKEND = 'django. Core. Mail. Backends. SMTP. EmailBackend' # designated mail backend EMAIL_HOST = 'smtp.163.com' email # host EMAIL_PORT = # EMAIL_HOST_USER = '[email protected]' # EMAIL_HOST_PASSWORD = 'hmmeiduo123' # EMAIL_HOST_USER = '[email protected]' # EMAIL_HOST_PASSWORD = 'hmmeiduo123' # EMAIL_HOST_USER = '[email protected]' Unregistered login password EMAIL_FROM = '[email protected]>' # sender's head

Send email for verification

Important Note:

  • Sending a mailbox verification email is a time-consuming operation that does not block the response of Mido Mall, so you need to send the email asynchronously.
  • Let’s continue to use Celery for asynchronous tasks.

1. Define and invoke the sending mail asynchronous task

1. Define sending mail tasks

@celery_app.task(bind=True, name='send_verify_email', retry_backoff=3) def send_verify_email(self, to_email, Verify_url): """ "Send verification email: param to_email: recipient email: param verify_url: Verification link :return: Html_message = '<p> Dear user! </p> "\ '<p> Thank you for using the mall. </p>' \ '<p> Your mailbox is: %s. Please click the link to activate your email address: < / p > '\' < p > < a href = "% s" > % s < a > < / p > '% (to_email verify_url, verify_url) try: send_mail(subject, "", settings.EMAIL_FROM, [to_email], html_message=html_message) except Exception as e: Retry (exc=e, max_retry =3)

2. Register the task of sending email: main.py

  • For the asynchronous task of sending mail, we use Django’s configuration file.
  • So we need to modify Celery’s startup file main.py.
  • Specify a Django configuration file that Celery can read.
  • Finally, remember to register for the task of adding a new email
Import OS if not os.getenv('DJANGO_SETTINGS_MODULE'); import OS if not os.getenv('DJANGO_SETTINGS_MODULE'); Os. environ['DJANGO_SETTINGS_MODULE'] = 'meiduo_mal.settings.dev' # Create celery instance celery_app = celery ('meiduo') # Celery_app.config_from_object (' Celery_tasks.config ') # Automate the Celery task registration celery_app.autodiscover_tasks(['celery_tasks.sms', 'celery_tasks.email'])

3. Invoke the Send Mail asynchronous task

Try: request.user.email = Email request.user.save() except Exception as E: logger.error(e) return http.JsonResponse({'code': RETCODE.DBERR, 'errmsg': 'Failed to add mailbox '}) # asynchronously send verifying message verify_url =' Message verifying link 'send_verify_email.delay(email, Return http. jsonResponse ({'code': retcode.ok, 'errmsg': 'mailbox added successfully '})

4. Start the Celery

$ celery -A celery_tasks.main worker -l info

2. Generate email verification link

1. Define the method of generating mailbox verification link

Def generate_verify_email_url(user): "" Generate email authentication link :param user: current login user: return: verify_url """ serializer = Serializer(settings.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES) data = {'user_id': user.id, 'email': user.email} token = serializer.dumps(data).decode() verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token return verify_url

2. Configure relevant parameters

# email verification link EMAIL_VERIFY_URL = 'http://www.shagncheng.site:8000/emails/verification/'

3. Use email to verify links

verify_url = generate_verify_email_url(request.user)
send_verify_email.delay(email, verify_url)

Verify the mailbox backend logic

1. Verify mailbox interface design and definition

1. Request mode

options plan
Request method GET
Request the address /emails/verification/

2. Request parameters: query parameters

Parameter names type Whether will pass instructions
token string is Mailbox activation link

3. Response result: HTML

field instructions
Email verification failed Response to error message
Email verification successful Redirect to the user center

2. Verify the link to extract user information

Def check_verify_email_token(token): "" user, None """ serializer = Serializer(settings.SECRET_KEY, expires_in=constants.VERIFY_EMAIL_TOKEN_EXPIRES) try: data = serializer.loads(token) except BadData: return None else: user_id = data.get('user_id') email = data.get('email') try: user = User.objects.get(id=user_id, email=email) except User.DoesNotExist: return None else: return user

3. Verify the mailbox back-end logic implementation

The core of validating a mailbox is to put the user’s
email_activeField set to
True

Class verifyEmailView (View): """ "def get(self, request): GET ('token') # Check if the token is null and expired, extract user if not token: Return the HTTP. HttpResponseBadRequest (' lack of token) user = check_verify_email_token (token) if not the user: Return HTTP. HttpResponseForbidden (' invalid token ') # modify email_active evaluates to True try: user.email_active = True user.save() except Exception as e: Logger. The error (e) return HTTP. HttpResponseServerError (' activation mail failure ') # return E-mail verification results return redirect (reverse (' users: the info))

Concerned about the public number: test old Han, reply: mall, access to complete the project code