文档章节

Python 常用工具类

猿神出窍
 猿神出窍
发布于 2017/05/24 17:47
字数 1040
阅读 103
收藏 0
点赞 0
评论 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)

 

© 著作权归作者所有

共有 人打赏支持
猿神出窍
粉丝 15
博文 161
码字总数 57015
作品 0
沙坪坝
项目经理
Python学习小白必备书籍以及源码下载、代码求助三大网站

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

柯西带你学编程 ⋅ 05/30 ⋅ 0

python学习-python-nmap实现高效的端口扫描器

python的第三方模块,python-nmap实现高效的端口扫描。 一、准备工作 yum -y install nmap #安装nmap工具pip install python-nmap==0.4.0 #python2.7环境使用pip安装0.4.0版本的第三方模块 ...

羊草 ⋅ 05/03 ⋅ 0

Linux环境下的Anaconda安装及使用

Anaconda对于python就相当于Ubuntu对于Linux,即Anaconda是python的一个发行版,将python和许多常用的package打包,方便pythoners直接使用。像virtualenv、pyenv等工具管理虚拟环境,起到的作...

戴千岩 ⋅ 2017/09/24 ⋅ 0

Python 3 的环境下如何正确地使用 Fabric

注:标题中「Fabric」指的是 Fabric( http://www.fabfile.org ),一个 Python 社区常用的远程/本地自动化执行工具。 讲 Fabric 之前,先讲讲我的 Python 开发环境。 很久以前,那会还在用 ...

I'm TualatriX ⋅ 05/21 ⋅ 0

机器学习的最佳学习路线原来只有四步

AI这个词相信大家都非常熟悉,近几年来人工智能圈子格外热闹,光是AlphoGo就让大家对它刮目相看。今天小天就来跟大家唠一唠如何进军人工智能的第一步——机器学习。 在机器学习领域,Python已...

ufv59to8 ⋅ 05/12 ⋅ 0

pycharm中使用anaconda

source activate python34 # for Linux & Mac# 激活后,会发现terminal输入的地方多了python34的字样,实际上,此时系统做的事情就是把默认2.7环境从PATH中去除,再把3.4对应的命令加入PATH#...

h8b6pk7m7r8 ⋅ 01/07 ⋅ 0

5本必读Python入门书籍,你都看过吗?(附福利)

今天技术学派为大家准备了5本Python入门书籍,除了书籍小编还整理了3个常用的资源网站分享给大家。 1.Python基础教程 《Python基础教程》是经典的Python入门教程书籍,本书层次鲜明,结构严谨...

Python燕大侠 ⋅ 06/07 ⋅ 0

Python开发一:PyCharm教程

通过前面的Python学习笔记教程,基本已经算入门Python了,接下来为了巩固Python,此后几篇文章重点在于使用Python开发应用。 所谓好马配好鞍,Python开发已经不同于Python入门,单纯的官方解...

viatorsun ⋅ 05/11 ⋅ 0

Python Scrapy 爬虫(三):部署环境搭建

当我们的爬虫程序开发完成后,应该考虑的事情就是如何将我们的爬虫程序部署到我们的服务器上来运行了。 下面就以 CentOS 作为我们的爬虫程序的部署环境来介绍部署爬虫的第一步:部署环境搭建...

雨林_a1d6 ⋅ 05/29 ⋅ 0

云计算Python自动化:python文件类型讲解

Python的文件类型主要分为3种:源代码(source file)、字节码(byte-code file)、优化的字节码(optimized file)。这些代码都可以直接运行,不需要编译或者连接。这正是Python语言的特性,...

长沙千锋 ⋅ 05/16 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

zblog2.3版本的asp系统是否可以超越卢松松博客的流量[图]

最近访问zblog官网,发现zlbog-asp2.3版本已经进入测试阶段了,虽然正式版还没有发布,想必也不久了。那么作为aps纵横江湖十多年的今天,blog2.2版本应该已经成熟了,为什么还要发布这个2.3...

原创小博客 ⋅ 57分钟前 ⋅ 0

聊聊spring cloud的HystrixCircuitBreakerConfiguration

序 本文主要研究一下spring cloud的HystrixCircuitBreakerConfiguration HystrixCircuitBreakerConfiguration spring-cloud-netflix-core-2.0.0.RELEASE-sources.jar!/org/springframework/......

go4it ⋅ 今天 ⋅ 0

二分查找

二分查找,也称折半查找、二分搜索,是一种在有序数组中查找某一特定元素的搜索算法。搜素过程从数组的中间元素开始,如果中间元素正好是要查找的元素,则搜素过程结束;如果某一特定元素大于...

人觉非常君 ⋅ 今天 ⋅ 0

VS中使用X64汇编

需要注意的是,在X86项目中,可以使用__asm{}来嵌入汇编代码,但是在X64项目中,再也不能使用__asm{}来编写嵌入式汇编程序了,必须使用专门的.asm汇编文件来编写相应的汇编代码,然后在其它地...

simpower ⋅ 今天 ⋅ 0

ThreadPoolExecutor

ThreadPoolExecutor public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, ......

4rnold ⋅ 昨天 ⋅ 0

Java正无穷大、负无穷大以及NaN

问题来源:用Java代码写了一个计算公式,包含除法和对数和取反,在页面上出现了-infinity,不知道这是什么问题,网上找答案才明白意思是负的无穷大。 思考:为什么会出现这种情况呢?这是哪里...

young_chen ⋅ 昨天 ⋅ 0

前台对中文编码,后台解码

前台:encodeURI(sbzt) 后台:String param = URLDecoder.decode(sbzt,"UTF-8");

west_coast ⋅ 昨天 ⋅ 0

实验楼—MySQL基础课程-挑战3实验报告

按照文档要求创建数据库 sudo sercice mysql startwget http://labfile.oss.aliyuncs.com/courses/9/createdb2.sqlvim /home/shiyanlou/createdb2.sql#查看下数据库代码 代码创建了grade......

zhangjin7 ⋅ 昨天 ⋅ 0

一起读书《深入浅出nodejs》-node模块机制

node 模块机制 前言 说到node,就不免得提到JavaScript。JavaScript自诞生以来,经历了工具类库、组件库、前端框架、前端应用的变迁。通过无数开发人员的努力,JavaScript不断被类聚和抽象,...

小草先森 ⋅ 昨天 ⋅ 0

Java桌球小游戏

其实算不上一个游戏,就是两张图片,不停的重画,改变ball图片的位置。一个左右直线碰撞的,一个有角度碰撞的。 左右直线碰撞 package com.bjsxt.test;import javax.swing.*;import j...

森林之下 ⋅ 昨天 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部