Some knowledge points of Django - rich text - cache - image upload - Middleware - aspect oriented programming, etc

Static file configuration

  • In setting At the bottom of Py is a folder called static, which is mainly used to load some resources used in the template for global use

  • This static file is mainly used to configure CSS, HTML, images, font files, etc

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR,'static')
]
  • After that, in the template, first load the static file, and then call static, so you do not need to write the absolute full path.

Picture upload

  • The file is stored in request In the files property
  • enctype = 'multipart / from data' needs to be added to the form upload file
  • File upload must use POST request mode

storage

  • Create uploadfiles in the static folder to store the uploaded files
  • Configure in settings, MEDIA_ROOT=os.path.join(BASE_DIR, r’static/uploadefiles)
  • In development, we usually store it in the table of associated users
def upload_file(request):
    if request.method == "POST":
        icon = request.FILES.get("icon")
        with open("/----/static/img/icon.jpg", "wb") as save_file:
            for part in icon.chuncks():
                save_file.write(part)
                save_file.flush()
        return HttpResponse("File uploaded successfully")
  • Django comes with
# models
class UserModel(models.Model):
    u_name = models.CharField(max_length=16)
    # upload_to relative path, relative to MEDIA_ROOT media root
    u_icon = models.ImageField(upload_to='%Y/%m/%d/icons')
# Settings
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/upload')
# Terminal
pip install pillow -i
# Store pictures
def image_field(request):
    if request.method == "POST":
        username = request.POST.get("username")
        icon = request.POST.get("icon")
        user = User()
        user.u_name = username
        user.i_icon = icon
        user.save()
        return HttpResponse(---)
        
# Read picture
def mine(request):
    username = request.GET.get("username")
    user = User.objects.get(u_name=username)
    data = {
        "username": username,
        "url": "/static/upload" + user.u_icon.url
    }
    return ----

cache

  • The core purpose of caching framework
    • Less code
    • uniformity
    • Scalability
  • Improve server response speed
  • Store the operation data that has been executed, and get the data directly from the cache when getting the data again within a certain period of time
  • The ideal solution is to use memory level cache
  • Django built-in caching framework
    • Memcached based cache
    • Use database for caching
    • Use file system for caching
    • Use local memory for caching
    • Provide cache extension interface

Cache configuration

  • Create cache table

    python manage.y createcachetable [table_name]
    
    • Cache configuration
    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
            'LOCATION': 'my_cache_table',
            'TIMEOUT': 60*5,
            # The following parts may not be filled in  
            'OPTIONS': {
                'MAX_ENTRIES': '300',
            },
            # Leading string
            'KEY_PREFIX': 'rock',
            'VERSION': '1',
        }
    }
    
  • Use of cache

    • Use in view (most used scenes)
    • @cache_page()
      • Time seconds, cache time
      • cache configuration, default
      • key_prefix prefix string
  • Cache bottom

    • Get cache (multiple)

    • from django.core.cache import caches
      cache = caches['cache_name']
      
    • Get cache (single)

    • from django.core.cache import cache
      
  • Cache operation

    • cache.set
      • key
      • value
      • timeout
    • get
    • add
    • get_or_set
    • get_many
    • set_many
    • delete
    • delete_many
    • clear
    • incr increase
      • Incr (key, value) add value to the value corresponding to key
    • decr reduction
      • Decr (key, value) reduces value from the value corresponding to key
      • If value is not written, it changes to 1 by default

Using Redis for caching

  • There are two common implementations

  • pip install django-redis

    • http://django-redis-chs.readthedocs.io/zh_CN/latest/#djangodjango-redis-cache
  • pip install django-redis-cache

  • https://pypi.python.org/pypi/django-redis-cache/

  • The configuration is basically consistent with the built-in cache configuration

    • CACHES = {
          'default': {
              'BACKEND': 'django_redis.cache.RedisCache',
              'LOCATION': 'redis://127.0.0.1:6379/1',
              'OPTIONS': {
                  'CLIENT_CLASS': 'django_redis.client.DefaultClient',
              },
          }
      }
      

aop facing section

  • Middleware: it is a lightweight, low-level plug-in that can intervene in Django's request and response process (aspect oriented programming)

  • The essence of middleware is a python class

  • Realize statistical function

    • Statistical ip
    • Statistical browser
  • Realize weight control

    class HelloMiddle(MiddlewareMixin):
        def process_request(self, request):
            print(request.META.get('REMOTE_ADDR'))
            ip = request.META.get('REMOTE_ADDR')
            if ip == '127.0.0.1':
                return HttpResponse("Congratulations, rich fool")
            else:
                return HttpResponse('hhh')
    
    • blacklist
    • White list
  • Realize reverse climbing

    • Anti reptile

      class HelloMiddle(MiddlewareMixin):
          def process_request(self, request):
              ip = request.META.get('REMOTE_ADDR')
              if request.path == "/app/getticket/":
                  result = cache.get(ip)
                  if result:
                      return HttpResponse('You visit too often')
                  cache.set(ip, ip, timeout=10)
      
      class HelloMiddle(MiddlewareMixin):
          def process_request(self, request):
              ip = request.META.get('REMOTE_ADDR')
              requests = cache.get(ip, [])
              black_list = cache.get(ip, [])
              if ip in black_list:
                  return HttpResponse('You have been hacked and cannot be operated')
              while requests and time.time() - requests[-1] > 60:
                  requests.pop()
              request.insert(0, time.time(), timeout=60)
              cache.set(ip, requests, timeout=60)
              if len(requests) >=30:
                  black_list.append(ip)
                  cache.set('black', black_list, timeout=60*60*24)
                  return HttpResponse('You have been hacked')
              if len(requests) >= 10:
                  return HttpResponse('Too many requests')
              
      
      • You can only search once in ten seconds
  • Friendly interface

  • Friendly application interaction

middleware

  • Call order
    • When middleware is registered, it is a list
    • If we do not return at the tangent point, the middleware will execute in turn
    • If the middleware is not directly executed, we will not directly execute it
  • Tangent point
    • process_request
    • process_view
    • process_template_response
    • process_response
    • process_exception

Cut in function

  • __ init __ : Without parameters, the server will automatically call when responding to the first request. The user determines whether to enable the middleware
  • process_request(self, request): it is called before the view is executed. It will be called on each request. It does not actively return or return the HttpResponse object
  • process_ template_ Reply (self, request, response): it is called just after the view is executed. Each request will be called. It does not actively return or return the HttpResponse object
  • process_response(self, request, response): all responses are called before they are returned to the browser, and each request is invoked without initiatively returning or returning HttpResponse objects.
  • process_exception(self, request, exception): called when the view throws an exception. It does not actively return or return the HttpResponse object
    def process_exception(self, request, exception):
        print(request)
        print(exception)
        return HttpResponse('error')
  • Custom middleware process

    • Create a middleware directory under the project directory

    • Create a python file in the directory

    • Import the base class of Middleware in python file

      • from django.utils.deprecation import MiddlewareMixin
        
    • In the class, according to the functional requirements, create the entry requirement class and rewrite the entry point method

      • class LearAOP(MiddlewareMixin):
            def process_request(self.request):
                print('request Path of', request.GET.path)
        
    • In MIDDLEWARE.middleware configuration, add File name Class name

paging

  • django provides pagination tools, which exist in django In core

    • Paginator data paging tool
    • Page a specific page
  • Paginator:

    • Object to create Paginator (data set, number of data per page)
    • Properties:
      • Total count objects
      • num_ Total pages
      • page_range page list, starting from 1
  • Get a page object using the page (integer) method

    • object_list all data objects on the current page
    • Number the page number value of the current page
    • Paginator the Paginator object associated with the current page
    • Common errors
      • InvalidPage: page() passes an invalid page number
      • Pagenotaninteger: the page() passed is not an integer
      • Empty: the value passed by page() is valid, but there is no data
    • custom
    def get_students(request):
        page = request.GET.get('page', 1)
        per_page = request.GET.get('per_page', 10)
      students = Student.objects.all()[per_page*(page-1): page*per_page]
        data = {
          'students': students
        }
        return render(request----)
    
    • django built in
    def get_students(request):
        page = request.GET.get('page', 1)
      per_page = request.GET.get('per_page', 10)
        students = Student.objects.all()
        paginator = Paginator(students, per_page)
        page_object = paginator.page(page)
        data = {
            "page_object": page_object,
            "page_range": paginator.page_range,
        }
        return render(request----)
    

Verification Code

  • The verification code needs to use the drawing pilot
  • Core Image, ImageDraw, ImageFont
def login(request):
    receive_code = request.POST.get('verify_code')
    store_code = request.session.get('verify_code')
    if receive_code.lower() != store_code.lower():
        return ---
    else:
        return ---

def get_code(request):
    # Initialize canvas, initialize brush
    mode = "RGB"
    size = (200, 100)
    red = get_color()
    green = get_color()
    blue = get_color()
    color_bg = (red, green, blue)
    image = Image.new(mode=mode, size=size, color=color_bg)
    imagedraw = ImageDraw(image, mode=mode)
    imagefont = ImageFont.truetype(settings.FONT_PATH, 100)
    verify_code = generate_code()
    request.session['verify_code'] = verify_code
    for i in range(4):
        fill = (get_color(), get_color(), get_color())
        imagedraw.text(xy=(50*i, 0), text=verify_code[i], font=imagefont, fill=fill)
    for i in range(5000):
        fill = (get_color(), get_color(), get_color())
        xy = (random.randrange(201), random.randrange(100))
        imagedraw.point(xy=(), fill=fill)
    fp = BytesIO()
    image.save(fp, "png")
    return HttpResponse(fp.getvalue(), content_type="image/png")

def get_color():
    return random.randrange(256)

def generate_code():
    source = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890"
    for i in range(4):
        code += random.choice(source)
    return code

Rich text

  • django plug-in

    • pip install django-tinymce
  • Use:

    • Used in background management
    • Used in pages, usually for blogs
  • Used in the background

    • Configure settings Py file

      • INSTALLED_ Add tinymce app to apps
    • Add default configuration

      TINYMCE_DEFAULT_COUNFIG = {
          'theme': 'advanced',
          'width': 800,
          'height': 600,
      }
      
    • Create model class:

      from tinymce.models import HTMLField
      class Blog(models.Model):
          sBlog = HTMLField()
      
    • Configure site

      admin.site.register
      

Keywords: Python Django

Added by GoSharks on Mon, 07 Mar 2022 15:58:46 +0200