Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
The introduction
It is not easy to achieve code with high cohesion, low coupling, clear structure, high readability, low data redundancy, high reuse, and easy to expand. Up to design patterns, down to the construction of a class, method, or function. Here I share my own code design and writing style so that we can learn from each other.
Python Code Style
We’ll start with the PEP8 code specification, but we don’t have to follow it. For example, a line cannot contain more than 79 characters.
Python Module template
- The beginning of the module specifies the encoding format
- Module documentation comments, display module information, information content is determined by yourself, such as:
- The Author, the Author
- Desc, the module description
- Date: creation time
- There is a
main()
function - There is a program main entry
if __name__ == '__main__':
#! /usr/bin/python3
# -*- coding:utf-8 -*-
# @Author: Hui
# @desc: {project main entry module}
# @Date: 2020/05/21 13:04
def main() :
print('Hello Python')
if __name__ == '__main__':
main()
Copy the code
The main() function is handy for testing the functionality of the current module.
The import import
Import, avoid using from… Import *, because this can lead to duplicate module, class, and variable names, resulting in errors.
My own import code styles come in two flavors.
From short to long
Import from short to long according to the length of the code, import from… import … , line break is optional, I’m based on from… import … The number and overall aesthetics of the preceding imports determine whether line breaks are necessary.
import os
import sys
import time
import random
import config
import pygame
import requests
import numpy as np
from PIL import Image
from threading import Thread
from datetime import datetime
Copy the code
Classification of import
Classified import, is divided into a good class in accordance with the length of the code from short to long import, mainly include:
- Python built-in modules
- Python self-built modules
- Python Third-party Libraries
# Python built-in module import
import os
import sys
import time
import random
from threading import Thread
from datetime import datetime
# Python self-built modules, third-party library imports
import config
import pygame
import requests
import numpy as np
from PIL import Image
Copy the code
The import sequence is
Python built-in modules --> Python built modules --> Python third-party librariesCopy the code
Depending on your style, imported self-built modules and Python third-party libraries can be grouped together without newlines
Imported custom modules can be added to Python’s built-in modules at smaller times, which are converted from short to long
advice
Import module code style does not need to copy to follow, we do any optimization is to make the code look better, the structure is clear, there is no need to deliberately follow the dead rules, bad rules, should live to learn and use, innovation and change, learn other people’s excellent scheme, summed up for their own.
Such as:
If the import statement is longer than the FROM import statement, follow or struggle with whether the import should precede the FROM import statement or run from short to long?
import numpy as np
import multiprocessing
from PIL import Image
Copy the code
import numpy as np
from PIL import Image
import multiprocessing
Copy the code
There is no need to be too tangled, stingy words, both import styles can be.
Naming conventions for variables
The naming convention can be considered a convention and is not absolute or mandatory for the purpose of increasing code identification and readability
Underline nomenclature
- When defining variables, to ensure that the code is formatted,
=
You should leave a space to the left and right of - in
Python
, if theThe variable nameNeed bytwo 或 More wordsWhen composing, you can name it as follows- Use lowercase letters for every word
- Words are connected by _ underscores
- Such as:
first_name
,last_name
,qq_number
,qq_password
Hump nomenclature
- When a variable name is made up of two or more words, it can also be named using hump nomenclature
- Small hump nomenclature
- The first word begins with a lowercase letter, followed by a capital letter
- Such as:
firstName
,lastName
- Big camel case nomenclature
- Every word begins with a capital letter
- Such as:
FirstName
,LastName
,CamelCase
Other languages, such as Java and C, generally use the camel name. In Python, it is recommended to use the underscore name, which complies with PEP8 specifications.
Examples of Django code
Module import
import re
import json
import logging
from django import http
from django.views import View
from django.conf import settings
from django.db import DatabaseError
from django.contrib.auth import authenticate
from django.contrib.auth import login, logout
from django_redis import get_redis_connection
from django.shortcuts import render, reverse, redirect
from goods.models import SKU
from users import constants
from users.models import User
from users.models import Address
from users.utils import generate_verify_email_url
from users.utils import check_verify_email_token
from carts.utils import merge_cart_cookie_to_redis
from meiduo_mall.utils.result import R
from meiduo_mall.utils.constants import RedisKey
from meiduo_mall.utils.constants import CookieKey
from meiduo_mall.utils.enums import StatusCodeEnum
from meiduo_mall.utils.constants import HtmlTemplate
from meiduo_mall.utils.views import LoginRequiredMixin
from meiduo_mall.utils.views import LoginRequiredJSONMixin
from meiduo_mall.utils.exceptions import BusinessException
from celery_tasks.email.tasks import celery_send_verify_email
Copy the code
This way the import looks more comfortable, the newline code is not compact, and the classification is organized.
The URL that encapsulates the HTML
Render HTML page, the HTML storage path of the overall package into a class, convenient maintenance in the future.
#! /usr/bin/python3
# -*- coding: utf-8 -*-
# @Author: Hui
# @desc: {project public constant module}
# @Date: 2021/09/25 15:57
class HtmlTemplate(object) :
""" Project HTML page template path summary class """
# page
INDEX_HTML = 'index.html'
"" User login module """
# user login
LOGIN_HTML = 'users/login.html'
# user registration
REGISTER_HTML = 'users/register.html'
# User-centric personal information
USER_CENTER_INFO_HTML = 'users/user_center_info.html'
""" Commodity Module """
# List of goods
GOODS_LIST_HTML = 'goods/list.html'
# Product Details
GOODS_DETAIL_HTML = 'goods/detail.html'
""" Shopping cart module """
# Shopping cart list
CART_LIST_HTML = 'carts/cart.html'
""" Project error HTML template """
ERRORS_404_HTML = 'errors/404.html'
Copy the code
View access and rendering
from meiduo_mall.utils.constants import HtmlTemplate
# /
class IndexView(View) :
""" Home Class View ""
def get(self, request) :
context = {
'name': 'hui'
}
return render(request, HtmlTemplate.INDEX_HTML, context)
# /login
class LoginView(View) :
"" User Login class view ""
def get(self, request) :
"" provide login interface :param request: request object :return: login interface """
return render(request, HtmlTemplate.LOGIN_HTML)
# /register
class RegisterView(View) :
"" User Registration Class view ""
def get(self, request) :
""" Provide registration page """
return render(request, HtmlTemplate.REGISTER_HTML)
Copy the code
Design and encapsulate keys for cookies and Redis
class CookieKey(object) :
"" Cookie Key constant design class ""
Login user name cookie key
USERNAME_KEY = 'username'
Cookie key for shopping cart information
CARTS_KEY = 'carts'
class RedisKey(object) :
"" redis Key Constant design class ""
# Graphic verification key
IMG_CODE_KEY = 'meiduo:img:code:{uuid}'
# SMS verification code key
SMS_CODE_KEY = 'meiduo:sms:code:{mobile}'
# SMS send mark
SMS_SEND_FLAG_KEY = 'meiduo:sms:send:flag:{mobile}'
# province data key
PROVINCES_KEY = 'meiduo:area:provinces'
# Urban data key
SUB_AREA_KEY = 'meiduo:sub_area:{area_id}'
# User product browsing history
HISTORY_BROWSE_KEY = 'meiduo:history:{user_id}'
# user shopping cart data key
USER_CARTS_KEY = 'meiduo:carts:{user_id}'
Check whether the key is checked in the shopping cart
CARTS_SELECTED_KEY = 'meiduo:cart:selected:{user_id}'
Copy the code
For example, the name of Redis key is very obvious.
Item Name Unique identifier of a service module or function'meiduo:img:code:{uuid}'
'meiduo:sms:code:{mobile}'
'meiduo:carts:{user_id}'
'meiduo:history:{user_id}'
Copy the code
There’s also a constant setting for the Settings configuration
Redis caches IP /port information
REDIS_URI = f"redis://{SERVER_IP}: 6379"
# cache alias
DEFAULT_CACHE_ALIAS = 'default'
SESSION_CACHE_ALIAS = "session"
VERIFY_CODE_CACHE_ALIAS = 'verify_code'
HISTORY_CACHE_ALIAS = 'history'
CARTS_CACHE_ALIAS = 'carts'
# cache
CACHES = {
Redis library 0 is used by default.
DEFAULT_CACHE_ALIAS: {
"BACKEND": "django_redis.cache.RedisCache"."LOCATION": f"{REDIS_URI}/ 0"."OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",}},# session, using the # 1 Redis library
SESSION_CACHE_ALIAS: {
"BACKEND": "django_redis.cache.RedisCache"."LOCATION": f"{REDIS_URI}/ 1"."OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",}},# Verification code (picture, SMS verification code), using the 2 Redis library
VERIFY_CODE_CACHE_ALIAS: {
"BACKEND": "django_redis.cache.RedisCache"."LOCATION": f"{REDIS_URI}/ 2"."OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",}},... }Copy the code
Code comparison before and after encapsulation
Before packaging
from django.conf import settings
from django_redis import get_redis_connection
from meiduo_mall.utils.constants import RedisKey
Create objects connected to Redis
redis_conn = get_redis_connection('verify_code')
img_code_key = 'meiduo:img:code:' + uuid
image_code_server = redis_conn.get(img_code_key)
Copy the code
After the encapsulation
from django.conf import settings
from django_redis import get_redis_connection
from meiduo_mall.utils.constants import RedisKey
Create objects connected to Redis
redis_conn = get_redis_connection(settings.VERIFY_CODE_CACHE_ALIAS)
img_code_key = RedisKey.IMG_CODE_KEY.format(uuid=uuid)
image_code_server = redis_conn.get(img_code_key)
Copy the code
While the amount of wrapped code adds a bit, it helps you get a faster idea of what the project is doing and improves maintainability. Instead of looking at specific modules, classes, and functions one by one, future updates can be made only in the encapsulated class.
Note: there is a lot of pseudo code in this article, mainly to show the ideas of code design and writing.
The tail language
✍ Code writes the world and makes life more interesting. ❤ ️
✍ thousands of rivers and mountains always love, ✍ go again. ❤ ️
✍ code word is not easy, but also hope you heroes support. ❤ ️