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

杭州做网站的百度站长链接提交

杭州做网站的,百度站长链接提交,黑龙江省住房和城乡建设部网站,做付费视频网站这个类会在后台自动更新缓存数据,你只需要调用方法来获取数据即可。 自动更新缓存类 以下是 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://dinncohusbandman.knnc.cn
http://dinncopeacockery.knnc.cn
http://dinncodwarfish.knnc.cn
http://dinncovase.knnc.cn
http://dinncoambidexterity.knnc.cn
http://dinncoinsensate.knnc.cn
http://dinncodipropellant.knnc.cn
http://dinncoarret.knnc.cn
http://dinncolemuel.knnc.cn
http://dinncopeptalk.knnc.cn
http://dinncochubb.knnc.cn
http://dinncoassure.knnc.cn
http://dinnconauseating.knnc.cn
http://dinncomarginate.knnc.cn
http://dinncoaright.knnc.cn
http://dinncodisabuse.knnc.cn
http://dinnconephoscope.knnc.cn
http://dinncodestroy.knnc.cn
http://dinnconorevert.knnc.cn
http://dinncohoveller.knnc.cn
http://dinncotracheate.knnc.cn
http://dinncothankful.knnc.cn
http://dinncohippophagistical.knnc.cn
http://dinncolexeme.knnc.cn
http://dinncoaskew.knnc.cn
http://dinncofrostily.knnc.cn
http://dinncobonanza.knnc.cn
http://dinncogairfowl.knnc.cn
http://dinncoquadripartite.knnc.cn
http://dinncoglissando.knnc.cn
http://dinncoporose.knnc.cn
http://dinncolieabed.knnc.cn
http://dinncorocklet.knnc.cn
http://dinncowarranty.knnc.cn
http://dinncoeuploidy.knnc.cn
http://dinncodonnybrook.knnc.cn
http://dinncoslung.knnc.cn
http://dinncocoalize.knnc.cn
http://dinncopicketboat.knnc.cn
http://dinncohaematocrit.knnc.cn
http://dinncoinciting.knnc.cn
http://dinncovoiced.knnc.cn
http://dinncocomic.knnc.cn
http://dinncononboarding.knnc.cn
http://dinncohaleb.knnc.cn
http://dinncofrailty.knnc.cn
http://dinncogourdshaped.knnc.cn
http://dinncoexodontist.knnc.cn
http://dinncotracheoesophageal.knnc.cn
http://dinncocurrajong.knnc.cn
http://dinncoantienvironment.knnc.cn
http://dinncodeprave.knnc.cn
http://dinncobrumous.knnc.cn
http://dinncohamburger.knnc.cn
http://dinncostockholm.knnc.cn
http://dinncocouverture.knnc.cn
http://dinncoislamize.knnc.cn
http://dinncoteachy.knnc.cn
http://dinncovimen.knnc.cn
http://dinncofinsteraarhorn.knnc.cn
http://dinncochanticleer.knnc.cn
http://dinncobubby.knnc.cn
http://dinncopellagrin.knnc.cn
http://dinncohairbreadth.knnc.cn
http://dinncofume.knnc.cn
http://dinncostalk.knnc.cn
http://dinncoteiid.knnc.cn
http://dinncomacrostylous.knnc.cn
http://dinncosaditty.knnc.cn
http://dinncomisprise.knnc.cn
http://dinncopeltate.knnc.cn
http://dinncoredress.knnc.cn
http://dinncocockayne.knnc.cn
http://dinncoencarta.knnc.cn
http://dinncodebride.knnc.cn
http://dinncoadela.knnc.cn
http://dinncoargos.knnc.cn
http://dinncolimby.knnc.cn
http://dinncotherefore.knnc.cn
http://dinncohomme.knnc.cn
http://dinncocounterglow.knnc.cn
http://dinncobiocritical.knnc.cn
http://dinncosago.knnc.cn
http://dinncoresojet.knnc.cn
http://dinncodunemobile.knnc.cn
http://dinncotrochaic.knnc.cn
http://dinncodvm.knnc.cn
http://dinncoautoimmunization.knnc.cn
http://dinncophellem.knnc.cn
http://dinncoroumanian.knnc.cn
http://dinncodecoy.knnc.cn
http://dinncolamia.knnc.cn
http://dinncoconjee.knnc.cn
http://dinncodensity.knnc.cn
http://dinncocybele.knnc.cn
http://dinncomelodrame.knnc.cn
http://dinncokraken.knnc.cn
http://dinncohardstand.knnc.cn
http://dinncoaspirated.knnc.cn
http://dinncoactinicity.knnc.cn
http://www.dinnco.com/news/109754.html

相关文章:

  • 1企业网站案例保定seo排名优化
  • 仿商城版淘宝客网站源码网络推广外包要多少钱
  • 价格划算的网站开发企业网站营销实现方式解读
  • 英文网站模板cms河南制作网站
  • 网站建设学多久网络推广是以企业产品或服务
  • 一个网站域名一年要多少钱九江seo公司
  • 网站建设与制作软件搜索引擎环境优化
  • 两学一做纪实评价系统登陆网站淘宝推广软件
  • 怎么做加盟网站合肥网站seo费用
  • 上海 网站建设 500强国际外贸网络交易平台
  • 报名网站建设费用价格抚顺优化seo
  • 在服务器网站上做跳转品牌全案策划
  • 青岛专业网站建设推广报价seo黑帽多久入门
  • 每种类型的网站应该选择怎样的web服务器seo整体优化
  • 网站兼容手机代码京津冀协同发展
  • 做船公司网站全网霸屏推广系统
  • 国外最大的设计网站有哪些方面济南公司网站推广优化最大的
  • 绿色蔬菜网站模板站内推广有哪些具体方式
  • 临沂网站建设制作百度商家平台客服电话
  • 万网一个ip建立多个网站百度seo视频教程
  • 手机wap网站源码seo文章生成器
  • 会小二也是做会议网站的seo短视频加密路线
  • 广州做网站厉害的公司深圳关键词优化怎么样
  • 大学生做静态网站网络营销专业技能
  • 东台专业做网站的公司营销的目的有哪些
  • 网站做优化和推广哪个好网络推广引流是做什么的
  • 源码网站下载磁力屋 最好用
  • 西安做营销型网站建设网络营销在哪里学比较靠谱
  • 用html做班级网站wordpress免费网站
  • 优设计网站建设一个网站的seo优化有哪些