[django] 常用公共代码,长期更新

227 阅读1分钟

Django 常用公共代码,长期更新

django pathandrename 用于django models 的file字段

import os
from uuid import uuid4

from django.utils.deconstruct import deconstructible


@deconstructible
class PathAndRename(object):

    def __init__(self, sub_path):
        self.path = sub_path

    def __call__(self, instance, filename):
        ext = filename.split('.')[-1]

        # set filename as random string
        filename = '{}.{}'.format(uuid4().hex, ext)

        # return the whole path to the file
        return os.path.join(self.path, filename)

使用方式, 这样就不会有相同的文件出现了

content = models.FileField(upload_to=PathAndRename('/example_path'))

django 获取客户端ip

def get_ip_addr(request):
    ipaddr = request.META.get('HTTP_X_FORWARDED_FOR', None)
    if ipaddr:
        # X_FORWARDED_FOR returns client1, proxy1, proxy2,...
        ipaddr = ipaddr.split(', ')[0]
    else:
        ipaddr = request.META.get('REMOTE_ADDR', '')
    return ipaddr

django 彩色日志配置

需要先安装 colorlog

pip install colorlog
log_level = 'DEBUG'
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': '[%(asctime)s][%(name)s:%(lineno)s][%(levelname)s] %(message)s',
            'datefmt': '%Y/%b/%d %H:%M:%S'
        },
        'colored': {'()': 'colorlog.ColoredFormatter',
                    'format': '[%(log_color)s%(asctime)s%(reset)s][%(name)s:%(lineno)s][%(log_color)s%(levelname)s%(reset)s] %(message)s',
                    'datefmt': '%Y/%b/%d %H:%M:%S',
                    'log_colors': {'DEBUG': 'cyan',
                                   'INFO': 'green',
                                   'WARNING': 'bold_yellow',
                                   'ERROR': 'red',
                                   'CRITICAL': 'red,bg_white'},
                    'secondary_log_colors': {},
                    'style': '%'},
    },
    'handlers': {
        'console': {
            'level': log_level,
            'class': 'logging.StreamHandler',
            'formatter': 'colored'
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'propagate': True,
        },
    }
}

效果如下图:

image.png 这个只是应用了django的日志,如果要应用自己的日志的话,需要加上自己的hanlder,

time model

class TimedModel(models.Model):
    """Abstract Model class.

    Provide created_at field and updated_at field.
    """
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True