文档章节

Python 常用工具类

猿神出窍
 猿神出窍
发布于 2017/05/24 17:47
字数 1040
阅读 113
收藏 0
def _create_secret(length=10):
    """
    获取由10位随机大小写字母、数字组成的值
    :param length:
    :return:
    """
    key = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    len_chars = len(chars) - 1
    for i in xrange(length):
        # 每次从chars中随机取一位
        key += chars[random.randint(0, len_chars)]
    return key


def _create_percent():
    """
    创建赢家百分比
    :return:
    """
    return random.uniform(1, 100)


def _get(url, params=None, timeout=5, headers=_get_headers()):
    """
    Get请求
    :param url:
    :param params:
    :param timeout:
    :param headers:
    :return:
    """
    try:
        response = requests.get(url=url, params=params, timeout=timeout, headers=headers)
        response.raise_for_status()
        result = response.json()
    except BaseException as e:
        logger.info(e.message)
        client.captureException()
        result = None
    return result


def _post(url, params=None, json=None, timeout=5, headers=_get_headers()):
    """
    Post请求
    :param url:
    :param params:
    :param json:
    :param timeout:
    :param headers:
    :return:
    """
    try:
        response = requests.post(url=url, data=params, json=json, headers=headers, timeout=timeout)
        response.raise_for_status()
        result = response.json()
    except BaseException as e:
        logger.info(e.message)
        client.captureException()
        result = {'status': False, 'message': ''}
    return result

def valid_signature(params, timeout=settings.SIGNATURE_TIMEOUT):
    """
    验签
    :param params: 
    :param timeout: 
    :return: 
    """
    if not params or not isinstance(params, dict):
        return False

    signature = params.pop('signature', '')
    app_id = params.get('app_id', '')
    if not signature or not app_id:
        return False

    timestamp = params.get('timestamp', '')
    current_timestamp = int(time.time())
    if current_timestamp - int(timestamp) > timeout:
        return False

    website = Website.obj.get_by_appid(app_id)
    if not website:
        return False

    sign = generate_signature(website.secret_key, params)
    if sign != signature:
        return False

    return True


def generate_signature(secret_key, params):
    """
    生成签名
    :param secret_key: 
    :param params: 
    :return: 
    """
    params['secret_key'] = secret_key
    keys = sorted(params.keys())
    tmp_str = ''
    for key in keys:
        tmp_str = '{tmp_str}{key}={value}'.format(tmp_str=tmp_str, key=key, value=unicode(params.get(key)))
    md5_str = _md5(tmp_str.encode('utf-8'))
    params.pop('secret_key')
    return md5_str


def _md5(str):
    """
    加密
    :param str:
    :return:
    """
    try:
        my_md5 = hashlib.md5()
        my_md5.update(str)
        md5_str = my_md5.hexdigest()
    except BaseException as e:
        return None
    return md5_str.upper()


def createVocabList(dataSet):
    """
    将二维数组转换为一维数组
    :param dataSet:
    :return:
    """
    vocabSet = set([])
    for document in dataSet:
        vocabSet = vocabSet | set(document)
    return list(vocabSet)

def get_user_ticket(room_id, bet_id, bet_amount):
    """
    计算中奖票号
    :param room_id:
    :param bet_id:
    :param bet_amount:
    :return:
    """
    bet_amount = float(bet_amount)
    user_list = RouletteStake.objects.filter(room_id=room_id, bet_id=bet_id).order_by('created')
    amount = 0
    for user in user_list:
        amount += float(user.amount)

    if amount == 0:
        tickets = [1, int(bet_amount * 100)]
    else:
        tickets = [int(amount * 100) + 1, int(amount * 100 + bet_amount * 100)]

    return tickets


def _draw_algor(user_list, percentage, room_id, bet_id):
    """
    抽奖算法
    :param user_list:
    :param percentage:
    :return:
    """
    result = dict()
    amount = 0
    for user in user_list:
        amount += float(user.get('amount'))

    user_ratio = dict()
    for user in user_list:
        user_ratio[user.get('id')] = float(decimal_div(user.get('amount'), amount, 4) * 100)

    # 中奖票号
    ticket = int(math.floor((float(amount) * 100 - 0.0000000001) * (percentage / 100)))

    # 找出中奖者 组装票
    process_list = RouletteStake.objects.filter(room_id=room_id, bet_id=bet_id).values('account_id', 'tickets',
                                                                                       'account__ucenter_id')
    for stake in process_list:
        if stake.get('tickets')[0] <= ticket <= stake.get('tickets')[1]:
            result['win_id'] = stake.get('account_id')
            result['ucenter_id'] = stake.get('account__ucenter_id')
            break
    result['win_ticket'] = ticket
    result['amount'] = amount
    result['user_ratio'] = user_ratio
    return result

# -*- coding:utf-8 -*-
from pyDes import *
from binascii import b2a_hex, a2b_hex

KEY = "_KEY"  # 密钥
IV = "__IV"  # 偏转向量


def encrypt_des(data, key=KEY, iv=IV):
    """
    对称加密
    :param data:
    :param key:
    :param iv:
    :return:
    """
    k = des(key, CBC, iv, pad=None, padmode=PAD_PKCS5)
    d = k.encrypt(data)
    return b2a_hex(d)


def decrypt_des(code, key=KEY, iv=IV):
    """
    解密
    :param code:
    :param key:
    :param iv:
    :return:
    """
    k = des(key, CBC, iv, pad=None, padmode=PAD_PKCS5)
    code = a2b_hex(code)
    return k.decrypt(code)

得到IP:
 

# coding=utf-8
import urllib2
import random
import time
import requests


def dl():
    a1={
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64)'}
    o_g=['114.239.3.149:808','61.232.254.39:3128','218.18.232.29:8080']
    a=0
    for a in range(0,3):
        proxies_l = {'http': o_g[a],

             }
        print(proxies_l['http'])

        try:
            req=requests.get('http://httpbin.org/ip',headers=a1,proxies=proxies_l)
            print('finish')
            print (req.text)
        except:
            print('no proxies')
        sleep_time=random.randint(1,3)
        time.sleep(sleep_time)
        print('Wait%ds'%sleep_time)

dl()

django批量操作:

# -*- coding:utf-8 -*-
from __future__ import unicode_literals


def insert_many(objects, using="default"):
    """
    Insert list of Django objects in one SQL query.
    Objects must be of the same Django model.
    Note that save is not called and signals on the model are not raised.
    Mostly from: http://people.iola.dk/olau/python/bulkops.py
    """
    if not objects:
        return

    import django.db.models
    from django.db import connections
    from django.db import transaction
    con = connections[using]

    model = objects[0].__class__
    fields = [f for f in model._meta.fields
              if not isinstance(f, django.db.models.AutoField)]
    parameters = []
    for o in objects:
        params = tuple(f.get_db_prep_save(f.pre_save(o, True), connection=con)
                       for f in fields)
        parameters.append(params)

    table = model._meta.db_table
    column_names = ",".join(con.ops.quote_name(f.column) for f in fields)
    placeholders = ",".join(("%s",) * len(fields))
    con.cursor().executemany("insert into %s (%s) values (%s)"
                             % (table, column_names, placeholders), parameters)
    transaction.commit()


def update_many(objects, fields=None, using="default"):
    """Update list of Django objects in one SQL query, optionally only
    overwrite the given fields (as names, e.g. fields=["foo"]).
    Objects must be of the same Django model. Note that save is not
    called and signals on the model are not raised.

    Mostly from: http://people.iola.dk/olau/python/bulkops.py
    """
    if not objects:
        return

    import django.db.models
    from django.db import connections
    from django.db import transaction
    con = connections[using]

    if fields is None:
        fields = []
    names = fields
    meta = objects[0]._meta

    fields = [f for f in meta.fields
              if not isinstance(f, django.db.models.AutoField)
              and (not names or f.name in names)
              and (not (hasattr(f, 'auto_now_add') and f.auto_now_add))]

    if not fields:
        raise ValueError("No fields to update, field names are %s." % names)

    fields_with_pk = fields + [meta.pk]
    parameters = []
    for o in objects:
        parameters.append(tuple(f.get_db_prep_save(f.pre_save(o, True),
                                                   connection=con) for f in fields_with_pk))

    table = meta.db_table
    assignments = ",".join(("%s=%%s" % con.ops.quote_name(f.column))
                           for f in fields)

    con.cursor().executemany("update %s set %s where %s=%%s"
                             % (table, assignments,
                                con.ops.quote_name(meta.pk.column)),
                             parameters)

    transaction.commit()

读取文件:

def read_file(fpath): 
   BLOCK_SIZE = 1024 
   with open(fpath, 'rb') as f: 
       while True: 
           block = f.read(BLOCK_SIZE) 
           if block: 
               yield block 
           else: 
               return

循环删除 防止索引溢出:

num_list = [1, 2, 3, 4, 5]
print(num_list)
# num_list[:] 拷贝删除
for item in num_list[:]:
    if item == 2:
        num_list.remove(item)
    else:
        print(item)

 

© 著作权归作者所有

共有 人打赏支持
猿神出窍
粉丝 16
博文 175
码字总数 61429
作品 0
沙坪坝
项目经理
Python基础总结成千行代码,让Python入门更简单!

只要学会这千行代码,不管你是零基础还是弱基础或是没有接触过编程,都可以快速入门Python!当时我就不信邪啊,等我看完之后,即使作为一个Python老鸟了,还是领会到了很多教授他的独特见解!...

糖宝lsh
09/10
0
0
Python学习小白必备书籍以及源码下载、代码求助三大网站

Python小白开发入门必备的3本书籍,除了书籍小U还整理了5个程序员们常用的资源网站。 入门书籍一 《Python for data analysis》 这本书涵盖了ipython notebook、Numpy、Scipy和Pandas包的使用...

柯西带你学编程
05/30
0
0
大神整理的python资源大全

Python基本安装: http://www.python.org/ 官方标准Python开发包和支持环境,同时也是Python的官方网站; http://www.activestate.com/ 集成多个有用插件的强大非官方版本,特别是针对Windo...

openthings
2015/12/15
0
0
Python 的单元测试之 unittest

Overview Basic example 随着项目的不断扩大,单元测试在保证开发效率、可维护性和软件质量等方面的地位越发举足轻重,是一本万利的举措。Python 常用 unittest module 编写单元测试,它包含...

koala bear
2014/07/06
0
0
一个 Pythoner的 Awesome List

从大三接触 Python 到现在几乎已经有两年的接触经验了,除去中间有一年左右接私活写写 Android 和 Lamp 之外,有 Python 实际项目开发经验也算是 9 个多月,也稍微算得上是一个入门级别的 Py...

无与童比
2016/12/10
0
0

没有更多内容

加载失败,请刷新页面

加载更多

一个可能的NEO链上安全随机数解决方案

0x00 困境 链上安全随机数生成应该算是一个比较蛋疼的问题,哪怕你的系统再牛逼,合约程序困在小小的虚拟机里,哪怕天大的本事也施展不开。 更悲催的是,交易执行的时候,是在每一个节点都执...

暖冰
今天
1
0
【大福利】极客时间专栏返现二维码大汇总

我已经购买了如下专栏,大家通过我的二维码你可以获得一定额度的返现! 然后,再给大家来个福利,只要你通过我的二维码购买,并且关注了【飞鱼说编程】公众号,可以加我微信或者私聊我,我再...

飞鱼说编程
今天
4
0
Spring5对比Spring3.2源码之容器的基本实现

最近看了《Spring源码深度解析》,该书是基于Spring3.2版本的,其中关于第二章容器的基本实现部分,目前spring5的实现方式已有较大改变。 Spring3.2的实现: public void testSimpleLoad(){...

Ilike_Java
今天
1
0
【王阳明心学语录】-001

1.“破山中贼易,破心中贼难。” 2.“夫万事万物之理不外于吾心。” 3.“心即理也。”“心外无理,心外无物,心外无事。” 4.“人心之得其正者即道心;道心之失其正者即人心。” 5.“无...

卯金刀GG
今天
2
0
OSChina 周三乱弹 —— 我们无法成为野兽

Osc乱弹歌单(2018)请戳(这里) 【今日歌曲】 @ _刚刚好: 霸王洗发水这波很骚 手机党少年们想听歌,请使劲儿戳(这里) hahahahahahh @嘻酱:居然忘了喝水。 让你喝可乐的话, 你准忘不了...

小小编辑
今天
17
2

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部