奇怪的知识又增加了
Lex_lht
????
展开
-
python根据主机名获取主机的IP地址
比如我的hosts名字[root@controller ~]# cat /etc/hosts127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4::1 localhost localhost.localdomain localhost6 localhost6.localdomain699.0.85.37 controller99.0.85.38 compute199.0.85原创 2021-03-12 16:17:13 · 404 阅读 · 0 评论 -
实现一个函数出错重试的装饰器
装饰器import functoolsdef retry_if_error(f): @functools.wraps(f) def inner(*args, **kwargs): remain_times = 3 while remain_times > 0: try: return f(*args, **kwargs) except Exception原创 2021-02-24 17:00:47 · 198 阅读 · 0 评论 -
利用python实现事件回调
一、简介在代码开发的过程中,为了降低各模块之间的耦合度,除了可以采用rpc的方式外,也可以采用事件订阅的方式进行。昨天在和小伙伴讨论这个模块的作用时,我突然想到这个事件回调可以用在智能家居中。。。二、实现主要利用了python中collections的defaultdict模块为了方便区分callback,因此实现一个函数来获取该callback的IDdef get_callback_id(callback): """return a unique identifier for the原创 2021-02-07 15:06:50 · 1028 阅读 · 4 评论 -
with的一种用法(利用with清理资源与回退)
需求场景在执行完对资源的操作后再执行一些动作,若此动作执行失败,需要对之前对资源的操作进行回退。示例在执行完do_something_to_db 函数后,需要执行after_do_db 函数,但是当after_do_db 函数执行错误,需要对do_something_to_db 函数之前所做的操作进行清理、回退这时使用with语句可以比较方便的进行回退操作,相对于不加with的语句显得优雅许多不用每次调用after_do_db时都加try...except...回退清理代码代码class Bas原创 2020-12-29 18:01:21 · 285 阅读 · 2 评论 -
Postman的Binary方式传送数据,requests实现
问题来源及背景最近在学习ES,在批量上传数据的时候卡住了,requests上传文件的时候一般用的是url = 'http://127.0.0.1:9200/_bulk'files = { "field" : open(filename, mode='rb') }requests.post(url, data=files, headers={'Content-Type':'binary'})但是上传的过程中ES一直报错,信息如下{"error":{"root_cau原创 2020-10-08 16:17:44 · 9332 阅读 · 1 评论 -
记两种使用property的方法
使用property可以限定类属性的读写使用property()函数函数声明:property(fget=None, fset=None, fdel=None, doc=None)优点:按照一般的写set和get的思路,不用加装饰器,只需在get和set函数后加上property函数即可示例:class Student(object): def __init__(self, name): self._name = name self._sex = Non原创 2020-08-10 14:01:20 · 1036 阅读 · 0 评论 -
Python偏函数(partial)的一些应用
在看Flask源码时发现的偏函数,现整理一下一些可能的应用例子示例1from functools import partialdef lookup_req_object(name): top = instance_stack.pop() return getattr(top, name, None)class Person: def __init__(self, name, age): self.name = name self.原创 2020-07-29 15:53:02 · 274 阅读 · 1 评论 -
将IP地址转换成整型--python实现
def int2ip(num): s = [] for i in range(4): s.append(str(num %256)) num //= 256 return '.'.join(s[::-1])def ip2int(ip): res = 0 for j, i in enumerate(ip.split('.')[::-1]): res += 256**j*int(i) return res"""原创 2020-06-24 14:25:04 · 772 阅读 · 0 评论 -
10进制转62进制
def __10to62(num): """ 10进制转62进制 """ base_scale = 62 chars = [ '3', 'a', '7', 'n', '2', 'b', 'H', 'm', 'E', '4', 's', 'M', 'f', 'Z', 'I', 'Y', 'K', 'x', 'q', 'U', 'o', 'l', 'L', 'D', '5', 'd', 'Q', 'h', 'i', 'y'.原创 2020-06-09 14:21:02 · 470 阅读 · 0 评论 -
关于jpg图片的小知识
.jpg文件的开头以字节FF D8开始如图原创 2020-05-25 20:40:21 · 522 阅读 · 0 评论