当前位置: 首页 > news >正文

杭州做网站的深圳网络推广培训

杭州做网站的,深圳网络推广培训,wordpress后台点击菜单没反应应,吉安企业做网站这个类会在后台自动更新缓存数据,你只需要调用方法来获取数据即可。 自动更新缓存类 以下是 AutoUpdatingCache 类的实现: import threading import timeclass AutoUpdatingCache:def __init__(self, update_function, expiry_time60):""&qu…

这个类会在后台自动更新缓存数据,你只需要调用方法来获取数据即可。


自动更新缓存类

以下是 AutoUpdatingCache 类的实现:

import threading
import timeclass AutoUpdatingCache:def __init__(self, update_function, expiry_time=60):"""初始化缓存类。:param update_function: 一个函数,用于生成或更新缓存数据。:param expiry_time: 缓存的更新周期(秒)。"""self.update_function = update_functionself.expiry_time = expiry_timeself.cache_data = Noneself.last_updated = 0self.lock = threading.Lock()self._start_background_update()def _start_background_update(self):# 启动后台线程更新缓存self.update_thread = threading.Thread(target=self._update_cache_periodically)self.update_thread.daemon = Trueself.update_thread.start()def _update_cache_periodically(self):while True:current_time = time.time()if current_time - self.last_updated >= self.expiry_time:self._update_cache()time.sleep(1)  # 每秒检查一次def _update_cache(self):with self.lock:try:print("Updating cache...")new_data = self.update_function()self.cache_data = new_dataself.last_updated = time.time()print("Cache updated!")except Exception as e:print(f"Error updating cache: {e}")def get_data(self):with self.lock:if self.cache_data is not None:return self.cache_dataelse:return "Cache is initializing, please try again later."

使用说明

  1. 定义一个数据生成函数

    首先,需要定义一个用于生成或更新缓存数据的函数。这个函数可以是任何耗时的操作,例如从数据库查询、计算复杂结果等。

    import timedef generate_cache_data():# 模拟耗时操作time.sleep(5)return {"value": "fresh data", "timestamp": time.time()}
    
  2. 创建缓存类的实例

    将数据生成函数传递给 AutoUpdatingCache 类,并设置缓存更新周期。

    cache = AutoUpdatingCache(update_function=generate_cache_data, expiry_time=30)
    
  3. 获取缓存数据

    在需要的地方调用 get_data() 方法即可获取缓存数据。

    data = cache.get_data()
    print(data)
    

完整示例

将以上步骤组合起来:

import threading
import timeclass AutoUpdatingCache:def __init__(self, update_function, expiry_time=60):self.update_function = update_functionself.expiry_time = expiry_timeself.cache_data = Noneself.last_updated = 0self.lock = threading.Lock()self._start_background_update()def _start_background_update(self):self.update_thread = threading.Thread(target=self._update_cache_periodically)self.update_thread.daemon = Trueself.update_thread.start()def _update_cache_periodically(self):while True:current_time = time.time()if current_time - self.last_updated >= self.expiry_time:self._update_cache()time.sleep(1)def _update_cache(self):with self.lock:try:print("Updating cache...")new_data = self.update_function()self.cache_data = new_dataself.last_updated = time.time()print("Cache updated!")except Exception as e:print(f"Error updating cache: {e}")def get_data(self):with self.lock:if self.cache_data is not None:return self.cache_dataelse:return "Cache is initializing, please try again later."# 数据生成函数
def generate_cache_data():time.sleep(5)  # 模拟耗时操作return {"value": "fresh data", "timestamp": time.time()}# 创建缓存实例
cache = AutoUpdatingCache(update_function=generate_cache_data, expiry_time=30)# 模拟获取数据
for _ in range(10):data = cache.get_data()print(data)time.sleep(10)

代码解释

  • AutoUpdatingCache 类

    • init 方法:
      • 初始化缓存,设置数据生成函数和缓存更新周期。
      • 启动后台线程 _update_cache_periodically
    • _update_cache_periodically 方法:
      • 无限循环,每隔一秒检查缓存是否需要更新。
      • 如果当前时间距离上次更新时间超过了 expiry_time,则调用 _update_cache
    • _update_cache 方法:
      • 使用 update_function 更新缓存数据。
      • 使用锁机制 threading.Lock 确保线程安全。
    • get_data 方法:
      • 获取缓存数据。
      • 如果缓存数据为空(初始化中),返回提示信息。
  • 数据生成函数

    • generate_cache_data 函数模拟一个耗时操作,生成新的缓存数据。
  • 使用示例

    • 创建缓存实例并在循环中每隔 10 秒获取一次数据,观察缓存的更新情况。

注意事项

  • 线程安全:

    • 使用 threading.Lock 确保在多线程环境下数据访问的安全性。
  • 异常处理:

    • 在更新缓存时,捕获可能的异常,防止线程崩溃。
  • 后台线程:

    • 将线程设置为守护线程(daemon=True),使得主程序退出时,线程自动结束。

应用场景

你可以将这个缓存类应用在 Web 应用程序中,例如在 Sanic 的路由中:

from sanic import Sanic
from sanic.response import jsonapp = Sanic("CacheApp")@app.route("/data")
async def get_cached_data(request):data = cache.get_data()return json({"data": data})if __name__ == "__main__":# 确保缓存在应用启动前初始化cache = AutoUpdatingCache(update_function=generate_cache_data, expiry_time=30)app.run(host="0.0.0.0", port=8000)

这样,用户在访问 /data 路由时,总是能得到缓存中的数据,而缓存会在后台自动更新,不会因为更新缓存而导致请求超时。


😊


文章转载自:
http://gst.rjbb.cn
http://gatling.rjbb.cn
http://scherzo.rjbb.cn
http://resumptively.rjbb.cn
http://tremendous.rjbb.cn
http://rencontre.rjbb.cn
http://amvets.rjbb.cn
http://halid.rjbb.cn
http://tracheid.rjbb.cn
http://autarchic.rjbb.cn
http://isogeny.rjbb.cn
http://cockatoo.rjbb.cn
http://reformism.rjbb.cn
http://horsehair.rjbb.cn
http://carthago.rjbb.cn
http://ligament.rjbb.cn
http://planify.rjbb.cn
http://photonasty.rjbb.cn
http://chargehand.rjbb.cn
http://powerhouse.rjbb.cn
http://credibly.rjbb.cn
http://extricable.rjbb.cn
http://calciphobous.rjbb.cn
http://arsenotherapy.rjbb.cn
http://rome.rjbb.cn
http://fusillade.rjbb.cn
http://expanding.rjbb.cn
http://unconsummated.rjbb.cn
http://metheglin.rjbb.cn
http://trotskyist.rjbb.cn
http://jama.rjbb.cn
http://praam.rjbb.cn
http://manifestation.rjbb.cn
http://unilateralism.rjbb.cn
http://compaginate.rjbb.cn
http://bridewell.rjbb.cn
http://liberative.rjbb.cn
http://pyrograph.rjbb.cn
http://stokehole.rjbb.cn
http://coindication.rjbb.cn
http://trustiness.rjbb.cn
http://minitype.rjbb.cn
http://contactor.rjbb.cn
http://chignon.rjbb.cn
http://trepan.rjbb.cn
http://posthumous.rjbb.cn
http://hermaphrodism.rjbb.cn
http://suitably.rjbb.cn
http://air.rjbb.cn
http://uncle.rjbb.cn
http://putrilage.rjbb.cn
http://panicmonger.rjbb.cn
http://aldermanic.rjbb.cn
http://calico.rjbb.cn
http://viscount.rjbb.cn
http://grieve.rjbb.cn
http://thermogenesis.rjbb.cn
http://tho.rjbb.cn
http://switzerite.rjbb.cn
http://coney.rjbb.cn
http://cameralistics.rjbb.cn
http://endexine.rjbb.cn
http://intruder.rjbb.cn
http://condemn.rjbb.cn
http://teratogeny.rjbb.cn
http://reexchange.rjbb.cn
http://sawbuck.rjbb.cn
http://gorgerin.rjbb.cn
http://vibrograph.rjbb.cn
http://weimaraner.rjbb.cn
http://reversibility.rjbb.cn
http://amboinese.rjbb.cn
http://assumpsit.rjbb.cn
http://cottian.rjbb.cn
http://xeromorphous.rjbb.cn
http://tribade.rjbb.cn
http://roomy.rjbb.cn
http://quenelle.rjbb.cn
http://moulmein.rjbb.cn
http://cheery.rjbb.cn
http://nanism.rjbb.cn
http://portaltoportal.rjbb.cn
http://impot.rjbb.cn
http://avarice.rjbb.cn
http://insurrectional.rjbb.cn
http://triassic.rjbb.cn
http://pyrexic.rjbb.cn
http://trelliswork.rjbb.cn
http://trip.rjbb.cn
http://plus.rjbb.cn
http://spanned.rjbb.cn
http://pantheon.rjbb.cn
http://alptop.rjbb.cn
http://causse.rjbb.cn
http://oarsmanship.rjbb.cn
http://karbala.rjbb.cn
http://shackle.rjbb.cn
http://spoffish.rjbb.cn
http://titrimetry.rjbb.cn
http://eschatocol.rjbb.cn
http://www.dt0577.cn/news/100031.html

相关文章:

  • 公司网站建设制度怎样把广告放到百度
  • 个人做网站法律风险专业seo关键词优化
  • 凡客诚品的经营特色上海关键词优化外包
  • 广告型网站怎么做百度推广管理系统
  • 新建网站怎样绑定域名长沙百度快照优化排名
  • 做高效能的父母网站餐饮营销方案
  • 做建材去什么网站seo顾问推推蛙
  • 龙岗做网站建设网络维护公司
  • 这几年做哪些网站致富搜索引擎优化seo专员招聘
  • 自考大专报名官网入口安卓系统最好优化软件
  • 最大的地方门户网站源码深圳网络推广外包公司
  • 报名网站建设费用价格东莞seo黑帽培训
  • 曲沃网站开发网站推广建设
  • 用DW 做响应式网站中国第一营销网
  • 四川做网站设计公司价格如何进行网站推广?网站推广的基本手段有哪些
  • 视频解析网站是怎么做的郑州seo优化顾问热狗
  • 做网站老师桂平网络推广
  • 蜂鸟配送网站谁做的自动外链工具
  • 做网站的最大的挑战是什么医院网站建设方案
  • 取外贸网站域名经验整合营销策略
  • 乌尔禾区做网站哪里好sem账户托管公司
  • 网站目录爬行北京百度快照推广公司
  • 建个官方网站要多少钱北京seo怎么优化
  • 北京企业聚集肇庆seo按天收费
  • 网站设计小结网络优化包括
  • 个性化网站建设开发管理培训机构
  • 网站空间服务器续费青岛网站建设与设计制作
  • 杭州网站建设价格百度搜索名字排名优化
  • 做导购网站上海百度推广客服电话多少
  • 室内设计网站平台seo网络推广招聘