Skip to content

Instantly share code, notes, and snippets.

@morsoli
Last active September 22, 2020 01:39
Show Gist options
  • Select an option

  • Save morsoli/d80ee78c121317a02f6cc34d50e9174a to your computer and use it in GitHub Desktop.

Select an option

Save morsoli/d80ee78c121317a02f6cc34d50e9174a to your computer and use it in GitHub Desktop.
常用的代码总结
  1. limit log file size to 5MB in python
import logging
from logging.handlers import RotatingFileHandler
log_formatter = logging.Formatter('%(asctime)s %(levelname)s %(funcName)s(%(lineno)d) %(message)s')
logFile = 'C:\\Temp\\log'
my_handler = RotatingFileHandler(logFile, mode='a', maxBytes=5*1024*1024, 
                                    backupCount=2, encoding=None, delay=0)
my_handler.setFormatter(log_formatter)
my_handler.setLevel(logging.INFO)
app_log = logging.getLogger('root')
app_log.setLevel(logging.INFO)
app_log.addHandler(my_handler)
while True:
     app_log.info("data")
  1. 安装pip
$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py   # 下载安装脚本
$ sudo python get-pip.py    # 运行安装脚本
  1. Django序列化输出重写原有字段
class DemoSerializer:
    def to_representation(self, obj):
        data = super(DemoSerializer, self).to_representation(obj)
        name = data['name']
        new_name = 'demo_name'
        data['name'] = new_name
  1. Django序列化输出时添加字段
ip_count = serializers.SerializerMethodField()
...
def get_ip_count(self, obj):
    ...
    return ip_count
  1. ip计数
from ipaddress import ip_address
def count_ip(ip_pool):
    start,end=ip_pool.split('-')
    start = ip_address(start)
    end = ip_address(end)
    count=0
    while start <= end:
        count+=1
        start += 1
    return count
  1. ipv4与ipv6检查
import socket
def is_ipv4(ip):
    try:
        socket.inet_pton(socket.AF_INET, ip)
    except AttributeError:  # no inet_pton here, sorry
        try:
            socket.inet_aton(ip)
        except socket.error:
            return False
        return ip.count('.') == 3
    except socket.error:  # not a valid ip
        return False
    return True

def is_ipv6(ip):
    try:
        socket.inet_pton(socket.AF_INET6, ip)
    except socket.error:  # not a valid ip
        return False
    return True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment