python Redis操作excel操作网络请求异常处理发送邮件发送钉钉消息等

Posted python测开搬砖人

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Redis操作excel操作网络请求异常处理发送邮件发送钉钉消息等相关的知识,希望对你有一定的参考价值。

Redis操作:

#连接: 11111111
#端口: 3306 #密码: 11111111&*
# 服务器连接命令: redis-cli -a password -h ip -p 6379 # redis-cli -a password -h 118.24.3.40 -p 6379 import redis # db=4 数据库4,decode_responses=True 拿到结果自动转字符串 r = redis.Redis(host="11111111",password="11111111&*",port=6379,db=4,decode_responses=True)
# 字符串操作------------------------------------------ # key不能重复,重复就会覆盖 # 60:失效秒数,不传保存永久 # r.set("key_ljq","lllllll",60) # # r.set("key_ljq","lllllll") # print(r.get("key_ljq")) # # r.delete("key_ljq") #删除key # 基本操作---------------------------------------------- # 查看key失效时间, ttl是 -1 的话永久生效 # print(r.ttl("key_ljq")) # # 获取数据库所有的key # print(r.keys("key_ljq")) # # 获取数据库的key,加条件 _ 匹配 # print(r.keys("*_*")) # # 返回0代表不存在,返回1 代表存在 # print(r.exists("key_ljq")) # # 查看key的类型 # print(r.type("key_ljq")) # # 设置key的失效时间 # r.expire("key_ljq",60) #hash类型 大字典 ---------------------------------------------- r.hset=("students","xiaohei",\'{"id":1,"score":99}\') d = {"aa":1,"bb":2} r.hmget("students",d)#字典批量写入 # print(r.hget("students","xiaohei"))#获取指定的小key # r.hgetall("students")#获取大key所有的数据 # r.hdel("students","xiaohei")#删除指定小key # r.delete("students")#删除大key所有的数据 # r.hexists("students","xiaohei")#判断里面的小key是否存在 # xb_info = r.hget("students","xiaohei")#获取指定的小key # print(xb_info.decode())#转字典 # ret = {b\'xiaohei\': b\'{"id":1,"score":99}\', b\'xiaobai\': b\'{"id":5,"score":99}\', b\'xiaohei1\': b\'{"id":1,"souce":99}\', b\'xiaobai1\': b\'{"id":1,"souce":99}\', b\'lxp2\': b\'{"id":2,"score":80}\', b\'xiaobao\': b\'{"id":5,"score":99}\', b\'lixuesong\': b\'{"id":1,"class":4}\'} #转字典 # ret = r.hgetall("students")#获取大key所有的数据 # new_ret = {} # for k,v in ret.items(): # k = k.ddecode() # v = v.ddecode() # new_ret[k] = v # print(new_ret) #list-------------------------------------------- list1 = [1,23,3] r.lpush("ljq",*list1)#解包list1 r.lpush("ljq","111","222")#左边添加 从前往后加 key:"ljq", values:"111","222" r.rpush("ljq","111")#右边添加,---从后往前加 print(r.lrange("ljq",0,1))#取值,下标取值,顾头顾尾 r.lpop("ljq")#从左边删除 r.rpop("ljq")#从右边删除 r.lset("ljq",0,"2222")#指定位置 下标0 修改值 print(r.llen("ljq"))#取list长度 print(r.ltrim("ljq",0,1))#除去你指定的范围 下标0到1,其他都删除 print(r.lrem("ljq",2,"2222"))#删除指定的元素, 2 :指定删除2次 # 清空数据库 # r.flushdb()#清空当前数据库 # r.flushall()#清空所有数据库
import redis
# select 11  查询数据库11
# fflushdb  清除数据库 11 的数据
# db=4 数据库4,decode_responses=True 拿到结果自动转字符串
r = redis.Redis(host="1111111",password="111111",port=6379,db=4,decode_responses=True)
r2 = redis.Redis(host="1111111",password="111111&*",port=6379,db=11,decode_responses=True)
for k in r.keys(): k_type = r.type(k) if k_type == "string": value = r.get(k) r2.set(k,value) elif k_type == "hash": dic = r.hgetall(k) r2.hmset(k,dic) elif k_type == "list": l_len = r.llen(k) result = r.lrange(k,0,l_len) r2.rpush(k,*result) # for k in r.keys(): # k_type = r.type(k) # if k_type == "string": # value = r.get(k) # r2.set(k,value) # elif k_type == "hash": # dic = r.hgetall(k) # r2.hmset(k,dic) # elif k_type == "list": # l_len = r.llen(k) # result = r.lrange(k,0,l_len) # r2.rpush(k,*result)

 

excel操作:

import xlrd

# book = xlrd.open_workbook("test.xls")
# # sheet = book.sheet_by_name("sheet1")
# sheet = book.sheet_by_index(0)
# # book.sheets()#获取所有sheet页
# print(sheet.cell(0,0).value)#获取某个单元格的内容
# print(sheet.row_values(0))#获取整行的内容
# print(sheet.col_values(0))#获取整列的内容
# print(sheet.nrows)#总共多少行
# print(sheet.ncols)#总共多少列


import xlwt
book = xlwt.Workbook()
xlwt.Workbook()
sheet = book.add_sheet("sheet1")
for i in range(65535):
    sheet.write(i,0,i)
book.save("a.xlsx")
import xlrd
from xlutils import copy

book = xlrd.open_workbook("test.xls")
new_book = copy.copy(book)

sheet = new_book.get_sheet(0)
# print(dir(sheet))#查看所有函数
sheet.write(0,0,"编号")

new_book.save("test.xls")
import openpyxl
# openpyxl   文件必须是xlsx的excel
book = openpyxl.load_workbook("test.xlsx")

sheet = book["sheet1"]
print(book.sheetnames)#所有sheet页

#取出每行数据
# for row in sheet.rows:
#     print(row)
#     for col in row:
#         print(col.value)
#取出每行数据放list里
# for row in sheet.rows:
#     row_data = [col.value for col in row]
#     print(row_data)

print(sheet.rows)#所有行
print(sheet.max_row)#多少行
print(sheet.max_column)#多少列
print(sheet.cell(1,1).value)#获取 从1开始
sheet.cell(1,1).value = "id"#获取第一行第一列  表格数据改为 id
# print(dir(sheet))
# 修改-------------------------------------------------------------
print(sheet["A1"].value)
sheet["A1"] = "id"
book.save("test.xlsx")

 

网络请求:

from urllib.request import urlopen
from urllib.parse import urlencode,urljoin,quote_plus,unquote_plus,quote,unquote

host = "https://gitee.com/"
url = urljoin(host,"li-jiaqiang1")#拼接链接
data = {"id":1}

# print(urlencode(data))#把字典转  键等于值
# req = urlopen(url,urlencode(data).encode())#post请求
req = urlopen(url+"?"+urlencode(data))#get请求
print(req.read().decode())

# quote_plus,quote:编码      unquote_plus,unquote:解码
host = "https://gitee.com/?stu=\'系哦啊黑\'"
print(quote_plus(host))#编码

host = "http://api.nnzhp.cn/api/user/stu_info?stu_name=%E5%B0%8F%E9%BB%91"
print(unquote_plus(host))#解码
import requests
#get请求
# url = "http://api.nnzhp.cn/api/user/stu_info"
# data = {"stu_name":"小"}
# req = requests.get(url,data)
# ----------------------------------------------------------------
#post请求
# url = "http://api.nnzhp.cn/api/user/login"
# data = {"username":"niuhanyang","passwd":"aA123456"}
# data2 = {"version":1}
# # req = requests.post(url,data)
#
# # params 参数放在URL里
# # data   参数放在body里
# req = requests.post(url,params = data2,data = data)
# print(req.url)#查看请求发出去的URL
# ----------------------------------------------------------------
# url = "http://api.nnzhp.cn/api/user/add_stu"
# data = {
#       "grade": "飞马座",
#       "phone": "22345678992",
#     "name":"哈哈哈哈"
# }
# req = requests.post(url,json=data)

# ----------------------------------------------------------------
# url = "https://qun.qq.com/cgi-bin/qun_mgr/search_group_members"
# data = {
# "gc": 180208520,
# "st": "21",
# "end": "41",
# "sort": 0,
# "bkn": "1391997515"
# }
# cookie = {\'RK\': \'XYYhgDpPfy\', \'ptcz\': \'a5b23b4f93bc2f304119957286b77b21be95814358d482ef0a2bf216733e57ba\', \'pgv_pvid\': \'5931324545\', \'uin\': \'o0511402865\', \'skey\': \'@HHempil2m\', \'p_uin\': \'o0511402865\', \'pt4_token\': \'tkeLBl-znMjpBJxIv1Chj*kLx7p0dsh4BkZfF39cpDk_\', \'p_skey\': \'OS7gS9Zw8*r*aIpqd5-S5BUo65EJMNWRkLLMO1Vpu5o_\', \'traceid\': \'5b35fe5632\'}
# req = requests.post(url,data,cookies=cookie)
# ----------------------------------------------------------------
# url = "https://qun.qq.com/cgi-bin/qun_mgr/search_group_members"
# data = {
# "gc": 180208520,
# "st": "21",
# "end": "41",
# "sort": 0,
# "bkn": "1391997515"
# }
# header = {\'cookie\': \'RK=XYYhgDpPfy; ptcz=a5b23b4f93bc2f304119957286b77b21be95814358d482ef0a2bf216733e57ba; pgv_pvid=5931324545; uin=o0511402865; skey=@HHempil2m; p_uin=o0511402865; pt4_token=tkeLBl-znMjpBJxIv1Chj*kLx7p0dsh4BkZfF39cpDk_; p_skey=OS7gS9Zw8*r*aIpqd5-S5BUo65EJMNWRkLLMO1Vpu5o_; traceid=5b35fe5632\'}
# req = requests.post(url,data,headers=header)

# 上传文件----------------------------------------------------------------
# # 接口文档: https://www.showdoc.com.cn/1333080850263964?page_id=6626741024413881
# url = "http://api.nnzhp.cn/api/file/file_upload"
# data = {"file":open("a.xls",\'rb\')}
# req = requests.post(url,files=data)

# 下载文件----------------------------------------------------------------
url = "http://aliimg.changba.com/cache/photo/941190975_200_200.jpg"
req = requests.get(url,verify=False)
with open("a.jpg","wb") as fw:
    fw.write(req.content)
# print(req.json())#返回字典,如果接口返回的不是json会报错
# print(req.text)#返回字符串
# print(req.content)#返回bytes
# print(req.cookies)#返回状态吗
# print(req.headers)#返回headers
import requests,xlwt,random
# 抓取所有的qq好友信息,每一个分组的好友写到一个sheet页里面
url = "https://qun.qq.com/cgi-bin/qun_mgr/get_friend_list"
data = {"bkn": "777503858"}
header = {"cookie":"_qpsvr_localtk=0.9495471953715655; uin=o0260303838; skey=@5il0ji5ch; RK=8YqtXKQ+R8; ptcz=74f5842468a029b8831974abf25c8e5ef46df2fa6a9a1ab325414634d44b5e28; p_uin=o0260303838; pt4_token=jHZFIlAC7pGSQrxBuz4po4WghX5g5TEgZGwO3p*nWlE_; p_skey=uHGnQA7535*L0hDHRSekFdPgLtSOOTlq-p9-P7rAFF8_; traceid=80d1189f41"}
req = requests.post(url,data,headers=header)
print(req.json())
result = req.json().get("result")
book = xlwt.Workbook()


for index,g_info in result.items():
    g_mems = g_info.get("mems") #list
    g_name = g_info.get("gname") if g_info.get("gname") else "默认分组"
    print("当前取的分组是===================",g_name)
    try:
        sheet = book.add_sheet(g_name)
    except Exception as e:
        sheet_name = "好友分组_%s" % random.randint(1, 1000)
        print("sheet页名字不合法,重新命名 : %s" % sheet_name)
        sheet = book.add_sheet(sheet_name)
    for col, mem in enumerate(g_mems):
        nick = mem.get("name")
        qq = mem.get("uin")
        sheet.write(col, 0, nick)
        sheet.write(col, 1, qq)
        # print("%s => %s" % (nick,qq))

book.save("qq.xls")

 

异常处理:

import traceback
l = [1,3,4]
# print(l[4])
d = {"name":1}
try:
    name = d["name"]
    l[4]
# except KeyError as e:
#     print(e)
#     print("出现异常了")
# except IndexError as e:
#     print(e)
#     print("出现下标异常了")
except Exception as e:
    # traceback.print_exc()
    print("出异常了")
    msg = traceback.format_exc()
    print(msg)

else:
    print("没有异常")
finally:
    print("finally:不管出不出异常都往下走")

#判断小数
def is_float(s):
    try:
        float(s)
    except:
        return False
    return True


"""
BaseException    # 所有异常的基类
SystemExit      # 解释器请求退出
KeyboardInterrupt    # 用户中断执行(通常是输入^C)
Exception    # 常规错误的基类
StopIteration    # 迭代器没有更多的值
GeneratorExit    #生成器(generator)发生异常来通知退出
StandardError    # 所有的内建标准异常的基类
ArithmeticError    # 所有数值计算错误的基类
FloatingPointError    # 浮点计算错误
OverflowError    #数值运算超出最大限制
ZeroDivisionError   # 除(或取模)零 (所有数据类型)
AssertionError    #断言语句失败
AttributeError    # 对象没有这个属性
EOFError    #没有内建输入,到达EOF 标记
EnvironmentError    # 操作系统错误的基类
IOError    #输入/输出操作失败
OSError    #操作系统错误
WindowsError    #系统调用失败
ImportError    # 导入模块/对象失败
LookupError    #无效数据查询的基类
IndexError    # 序列中没有此索引(index)
KeyError    #映射中没有这个键
MemoryError    # 内存溢出错误(对于Python 解释器不是致命的)
NameError    # 未声明/初始化对象 (没有属性)
UnboundLocalError    # 访问未初始化的本地变量
ReferenceError    # 弱引用(Weak reference)试图访问已经垃圾回收了的对象
RuntimeError    # 一般的运行时错误
NotImplementedError    # 尚未实现的方法
SyntaxError    # Python 语法错误
IndentationError    # 缩进错误
TabError    # Tab 和空格混用
SystemError   #  一般的解释器系统错误
TypeError    #对类型无效的操作
ValueError   #  传入无效的参数
UnicodeError    # Unicode 相关的错误
UnicodeDecodeError    #Unicode 解码时的错误
UnicodeEncodeError    #Unicode 编码时错误
UnicodeTranslateError    #Unicode 转换时错误
Warning    #警告的基类
DeprecationWarning    #关于被弃用的特征的警告
FutureWarning    # 关于构造将来语义会有改变的警告
OverflowWarning    # 旧的关于自动提升为长整型(long)的警告
PendingDeprecationWarning    #关于特性将会被废弃的警告
RuntimeWarning    #可疑的运行时行为(runtime behavior)的警告
SyntaxWarning    # 可疑的语法的警告
UserWarning    #用户代码生成的警告
"""

 

发送邮件:

import yamail
# # import yagmail #附件是中文名,显示乱码
# # 授权码 : hcapwu
#
# username = "511465@qq.com"
# password = "hcaphhcia"
# host = "smtp.qq.com"
# # host = "smtp.163.com"
# # host = "smtp.126.com"
# smtp = yamail.SMTP(host=host,user=username,password=password)
# # smtp.send(to="260303838@qq.com")
# smtp.send(to=["260303838@qq.com","126120511@qq.com"],
#           cc=["26030388@qq.com","12612511@qq.com"],
#           subject="课后好好学习",
#           contents="haoahochifan",
#           attachments=["reg.py","tools.py"])

username = "5165@qq.com"
password = "hcahcaia"
host = "smtp.qq.com" #qq
# host = "smtp.163.com" #163
# host = "smtp.126.com" #qq

smtp = yamail.SMTP(host=host,user=username,password=password)
# smtp.send(to="1018934314@qq.com")
smtp.send(
    to=["260303838@qq.com","1054114694@qq.com"],
    cc=["1490768397@qq.com","1164019076@qq.com"],
    subject="课后好好学习",
    contents="下课之后先吃饭,吃完饭明天好好学习。",
    attachments=["reg.py","tools.py"]
)

 

发送钉钉消息:

# import requests
# url = "https://oapi.dingtalk.com/robot/send?access_token=1111111111111111111"
## 密钥:  11111111111111111111
# data = {
#     "msgtype": "text",
#     "text": {
#         "content": "fmz,xiakele"
#     },
#     "at":{
#         "atMobiles":["13951813583"],
#         "isAtAll":"True"  #@ True:@所有人     False:@一个人
#     }
# }
# r = requests.post(url,json=data)
# print(r.json())

import requests

url = "https://oapi.dingtalk.com/robot/send"

import time
import hmac
import hashlib
import base64
import urllib.parse

def get_dd_sign():
    timestamp = str(round(time.time() * 1000))
    secret = \'11111111111111111111111111111\'
    secret_enc = secret.encode(\'utf-8\')
    string_to_sign = \'{}\\n{}\'.format(timestamp, secret)
    string_to_sign_enc = string_to_sign.encode(\'utf-8\')
    hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
    return timestamp,sign

def send_dd_msg(msg,at=None,at_all=False):

    data = {
        "msgtype": "text",
        "text": {
            "content": msg
        },
        "at": {
            "atMobiles": at,
            "isAtAll": at_all
        }
    }
    timestamp,sign = get_dd_sign()
    params = {
        "access_token":"access_token11111111111111111111",
        "timestamp":timestamp,
        "sign":sign
    }
    try:
        r = requests.post(url,json=data,params=params)
    except:
        print("滴滴消息没有发送成功")
    else:
        if r.json().get("errcode")==0:
            return True

 

l = [1,3,4]# print(l[4])d = {"name":1}try:    name = d["name"]    l[4]# except KeyError as e:#     print(e)#     print("出现异常了")# except IndexError as e:#     print(e)#     print("出现下标异常了")except Exception as e:    # traceback.print_exc()    print("出异常了")    msg = traceback.format_exc()    print(msg)
else:    print("没有异常")finally:    print("finally:不管出不出异常都往下走")
#判断小数def is_float(s):    try:        float(s)    except:        return False    return True

"""BaseException    # 所有异常的基类SystemExit      # 解释器请求退出KeyboardInterrupt    # 用户中断执行(通常是输入^C)Exception    # 常规错误的基类StopIteration    # 迭代器没有更多的值GeneratorExit    #生成器(generator)发生异常来通知退出StandardError    # 所有的内建标准异常的基类ArithmeticError    # 所有数值计算错误的基类FloatingPointError    # 浮点计算错误OverflowError    #数值运算超出最大限制ZeroDivisionError   # 除(或取模)零 (所有数据类型)AssertionError    #断言语句失败AttributeError    # 对象没有这个属性EOFError    #没有内建输入,到达EOF 标记EnvironmentError    # 操作系统错误的基类IOError    #输入/输出操作失败OSError    #操作系统错误WindowsError    #系统调用失败ImportError    # 导入模块/对象失败LookupError    #无效数据查询的基类IndexError    # 序列中没有此索引(index)KeyError    #映射中没有这个键MemoryError    # 内存溢出错误(对于Python 解释器不是致命的)NameError    # 未声明/初始化对象 (没有属性)UnboundLocalError    # 访问未初始化的本地变量ReferenceError    # 弱引用(Weak reference)试图访问已经垃圾回收了的对象RuntimeError    # 一般的运行时错误NotImplementedError    # 尚未实现的方法SyntaxError    # Python 语法错误IndentationError    # 缩进错误TabError    # Tab 和空格混用SystemError   #  一般的解释器系统错误TypeError    #对类型无效的操作ValueError   #  传入无效的参数UnicodeError    # Unicode 相关的错误UnicodeDecodeError    #Unicode 解码时的错误UnicodeEncodeError    #Unicode 编码时错误UnicodeTranslateError    #Unicode 转换时错误Warning    #警告的基类DeprecationWarning    #关于被弃用的特征的警告FutureWarning    # 关于构造将来语义会有改变的警告OverflowWarning    # 旧的关于自动提升为长整型(long)的警告PendingDeprecationWarning    #关于特性将会被废弃的警告RuntimeWarning    #可疑的运行时行为(runtime behavior)的警告SyntaxWarning    # 可疑的语法的警告UserWarning    #用户代码生成的警告"""

以上是关于python Redis操作excel操作网络请求异常处理发送邮件发送钉钉消息等的主要内容,如果未能解决你的问题,请参考以下文章

python excel操作及网络编程

lua 操作redis

八python操作excel及网络编程和异常处理

Python Redis pipeline 操作

Python之操作Excel异常处理网络编程

Nosql和Redis介绍,Redis五大数据类型及操作,跳跃表