Redis *** 作:
#连接: 11111111
#端口: 3306#密码: 11111111&*
# 服务器连接命令: redis-cli -a password -h ip -p 6379# redis-cli -a password -h 118.24.3.40 -p 6379import 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)#解包List1r.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 xlwtbook = xlwt.Workbook()xlwt.Workbook()sheet = book.add_sheet("sheet1")for i in range(65535): sheet.write(i,0,i)book.save("a.xlsx")
import xlrdfrom xlutils import copybook = 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的excelbook = 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 urlopenfrom urllib.parse import urlencode,urljoin,quote_plus,unquote_plus,quote,unquotehost = "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/@R_502_6852@/@R_502_6852@_upload"# data = {"@R_502_6852@":open("a.xls",'rb')}# req = requests.post(url,@R_502_6852@s=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 tracebackl = [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" #qqsmtp = 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 requestsurl = "https://oAPI.dingtalk.com/robot/send"import timeimport hmacimport hashlibimport base64import urllib.parsedef 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,signdef 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 Redis *** 作、excel *** 作、网络请求、异常处理、发送邮件、发送钉钉消息等所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)