文档章节

Python 常用工具类

猿神出窍
 猿神出窍
发布于 2017/05/24 17:47
字数 1040
阅读 108
收藏 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
博文 172
码字总数 60705
作品 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
一个 Pythoner的 Awesome List

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

无与童比
2016/12/10
0
0
Python 的单元测试之 unittest

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

koala bear
2014/07/06
0
0
新手该如何学python怎么学好python?

转自:http://hi.baidu.com/zenseeblog/blog/item/4db0dc2012d4c34aad34dee6.html 根据本人的学习经验,我总结了以下十点和大家分享: 1)学好python的第一步,就是马上到www.python.org网站...

flynewton
2010/09/29
0
10

没有更多内容

加载失败,请刷新页面

加载更多

下一页

shell-日志脚本小实验

1.查找日志2018-8-15,求得那一分钟访问量最大。 #/bin/bash#from cc#2018-8-15#2018-08-15.log 哪一分钟 访问量 最大for d in `ls /data/nginx/logs/`doif [ -a 2018-08-15...

chencheng-linux
昨天
0
0
Android中的设计模式之状态模式

参考 《设计模式:可复用面向对象软件的基础 》5.8 State 状态 对象行为型模式 《Android源码设计模式解析与实战》第7章 随遇而安--状态模式 意图 允许一个对象在其内部状态改变时改变它的行...

newtrek
昨天
0
0
xshell端 vim没有颜色

说明 使用xshell连接服务器的时候,使用vim打开文档没有颜色 解决方法: 1.在更目录home或者etc下找到vim的配置文件vimrc 2.vim打开它找个坑,添加下面这个东西 set t_Co=256 3.保存退出,就...

杉下
昨天
0
0
spring 资料

spring boot http://www.ityouknow.com/springboot/2016/01/06/spring-boot-quick-start.html

zaolonglei
昨天
2
0
TypeScript基础入门 - 函数 - 简介

转载 TypeScript基础入门 - 函数 - 简介 项目实践仓库 https://github.com/durban89/typescript_demo.gittag: 1.1.6 为了保证后面的学习演示需要安装下ts-node,这样后面的每个操作都能直接...

durban
昨天
0
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部