python笔记:随机数,md5,en/decoder

2019-11-21 21:22:38 浏览数 (1)

uuid 生成随机识别号

代码语言:javascript复制
import uuid

for i in range(0,10):
    print "uuid is :"  str(uuid.uuid4())

另一种实现

代码语言:javascript复制
import os
import base64

def GetRndStr():    
    rndByte = os.urandom(6)
    b64Str = base64.urlsafe_b64encode(rndByte)
    return b64Str

生成不重复随机序列

代码语言:javascript复制
import random

def get_rnd(max_size, counts):
    basearr = [x for x in range(max_size)]
    result = []

    max_position = max_size - 1
    while counts and max_position:
        rnd_position = random.randint(0, max_position)
        result.append(basearr[rnd_position])
        basearr[rnd_position] = basearr[max_position]
        max_position -= 1
        counts -= 1
    return result

for i in range(10):
    print(get_rnd(1000, 50))

生成snowflake流水号

代码语言:javascript复制
import datetime
import math
import threading
import time
import uuid

from random import SystemRandom

cryptogen = SystemRandom()


# 0位 时间 机器码 random 流水号
# 0 - 0 * 41 - 0 * 10 - 0 * 8 - 0 * 4

class SnowFlake(object):
    def __init__(self):
        self._INIT_TIME = 1420041600000  # 2015-01-01
        self._last_timestamp = 0
        self._WORKER_ID_LEN = 10
        self._RAM_LEN = 8
        self._FLOW_LEN = 22 - self._WORKER_ID_LEN - self._RAM_LEN
        self._flow = 0
        self._FLOW_MAX = int(math.pow(2, self._FLOW_LEN))
        self._lock = threading.Lock()
        self._worker_id = None
        self._ram = None

    def _get_worker_id(self):
        if not self._worker_id:
            self._worker_id = uuid.getnode() % 
                              int(math.pow(2, self._WORKER_ID_LEN))
        return self._worker_id

    def _generate_ram(self):
        self._ram = (self._ram   1) % 
                    int(math.pow(2, self._WORKER_ID_LEN))

    def _get_ram(self):
        if not self._ram:
            self._ram = cryptogen.randrange(0, 100000) % 
                        int(math.pow(2, self._RAM_LEN))
        return self._ram

    def generate(self):
        self._lock.acquire(1)
        tp = int(time.time() * 1000)
        tp = tp - self._INIT_TIME

        if tp < self._last_timestamp:
            # 处理时间回拔,重新生成ram
            self._generate_ram()

        if tp == self._last_timestamp:
            self._flow  = 1
            if self._flow > self._FLOW_MAX:
                raise Exception("flow no overflowed!")
        else:
            self._last_timestamp = tp
            self._flow = 1

        ret = 0

        ret  = tp << (self._WORKER_ID_LEN   self._RAM_LEN   self._FLOW_LEN)
        ret  = self._get_worker_id() << (self._RAM_LEN   self._FLOW_LEN)
        ret  = self._get_ram() << self._FLOW_LEN
        ret  = self._flow

        self._lock.release()
        return ret

    def get_time(self, flow_no):
        flow_tp = flow_no >> (self._WORKER_ID_LEN   self._RAM_LEN   self._FLOW_LEN)
        utc_tp = flow_tp   self._INIT_TIME

        dt = datetime.datetime.fromtimestamp(utc_tp / 1000)
        return dt

    def get_worker_id(self, flow_no):
        worker_id = flow_no >> self._FLOW_LEN   self._RAM_LEN
        worker_id = worker_id & ((1 << self._WORKER_ID_LEN) - 1)
        return worker_id

    def get_ram(self, flow_no):
        ram = flow_no >> self._FLOW_LEN
        ram = ram & ((1 << self._RAM_LEN) - 1)
        return ram

if __name__ == '__main__':
    snowflake = SnowFlake()
    for i in range(10):
        flow_no = snowflake.generate()
        bit_flow_no = '{:064b}'.format(flow_no)
        dt = snowflake.get_time(flow_no)
        worker_id = snowflake.get_worker_id(flow_no)
        ram = snowflake.get_ram(flow_no)
        # print(flow_no)
        print("{} n{} n{} "
              "n{} n{}".format(flow_no, bit_flow_no, dt, worker_id, ram))

加权随机数

代码语言:javascript复制
import random

# 加权随机数
def rnd_power(power_ranks: [int]) -> int:
    """
    传入权重,随机返回该权重的index
    :param power_ranks: [10,20,30,40]
    :return: index of power_rank
    """
    sum_ranks = sum(power_ranks)
    rnd = random.randint(0, sum_ranks - 1)
    all_rank = 0
    for i, rank in enumerate(power_ranks):
        all_rank  = rank
        if rnd < all_rank:
            return i

if __name__ == '__main__':
    result = [0, 0, 0, 0]
    for i in range(10000):
        index = rnd_power([10, 20, 30, 40])
        result[index]  = 1
    print(result) # [1000, 2025, 2973, 4002]

2 md5加密

代码语言:javascript复制
import hashlib

md5obj = hashlib.md5()
md5obj.update("hello")
md5obj.update("world")

print md5obj.hexdigest()

#md5文件
def CalcMD5(filepath):
    with open(filepath,'rb') as f:
        md5obj = hashlib.md5()
        md5obj.update(f.read())
        hash = md5obj.hexdigest()
        return hash

3 url的编码和解码

代码语言:javascript复制
import urllib
import urlparse

data = {
    'name':'尹子豪',
    'id':'346093'
    }
#返回的是string类型的url
data = urllib.urlencode(data) #比较坑,有urlencode没有urldecode。。
print data

data = urlparse.urlparse("www.yinzihao.com.cn/index?" data) #凑个网址,使用parse拆分
print data

params=urlparse.parse_qs(data.query,True) #拆分url参数,自动urldecode了,大家不用担心。
print params
myname = params['name'][0] #此时可以打印名称了
print myname.decode('utf-8').encode('gbk') #输出的时候使用系统的gbk编码,否则乱码。

py3可以这样

代码语言:javascript复制
from urllib import parse

test = "大猪"
test = parse.quote(test)
print(test)
test = parse.unquote(test)
print(test)

4 htmlencoder和decoder

代码语言:javascript复制
import HTMLParser
import cgi

def decodeHtml(input):
    h = HTMLParser.HTMLParser()
    s = h.unescape(input)
    return s

def encodeHtml(input):
    s = cgi.escape(input)
    return s

py3

代码语言:javascript复制
from html import escape, unescape

strs = "<span>&#62;</span>"
strs = escape(strs)
print(strs)
strs = unescape(strs)
print(strs)

0 人点赞