这篇文章主要是在纪录 python decorator 的学习过程,
有错或是更好的写法的话,欢迎留言讨论!!
装饰器可以帮助我们更加精简我们的程序码,举凡 Flask、FastAPI 等 module 都有使用
更加详细的介绍可以参考 这个网址
def demo_decorator(callback):
def add():
print("测试装饰器")
# 测试用内容,会印出累加
tmp = 0
for i in range(10):
tmp += i
print(tmp)
# 呼叫 callback 也就是带有装饰器的函式本身
callback()
# 规定要回传装饰器内的函式
return add
@demo_decorator
def demo_main_function():
print("测试函式")
if __name__ == '__main__':
demo_main_function()
在网路爬虫当中,我们常常会遇到需要重试请求的情况,碰到这种情况,我们可以利用 decorator 进行重试
import requests
def retry_decorator(callback):
def retry(url, retry_time):
recoder = 0
while recoder < retry_time:
try:
return callback(url)
except requests.exceptions.RequestException:
print("请求错误")
recoder += 1
return retry
@retry_decorator
def demo_main_function(url):
res = requests.get(url)
print(res.status_code)
if __name__ == '__main__':
# correct url
demo_main_function("https://google.com.tw", 3)
print("-------------------")
# wrong url
demo_main_function("https://test.test.test", 3)
C:\Users\nick\Desktop\deacorator_testt\venv\Scripts\python.exe C:/Users/nick/Desktop/deacorator_testt/main.py
200
-------------------
请求错误
请求错误
请求错误
Process finished with exit code 0
<<: 为了转生而点技能-JavaScript,day8(浅笔记-物件之浅层复制与深层复制
今天尝试将 2D RPG 角色移动模组根据规格画出 Flowchart 和 State Diagra...
如标题,这篇想教大家如何自己手动分割硬碟 Windows有C槽、D槽、E槽……等,但linux没有w...
身为一个普大的普通大学生, 实战经验少得可怜, 除了学过资工基本学科,就只会用 Python 写 L...
在 KLineViewController 开出的 volumeDataSet 会在 parent ...
前言 今天是铁人赛的第十五天,终於要把前两天的爬虫程序整合到LineBot了 再次说明:这里不是手把...