简介
之前一直是使用busuanzi
https://github.com/soxft/busuanzi
但是为了降本增效,所以想直接使用umami上的数据算了,但是umami如果统计所有时间的数据会很慢,肯定不如busuanzi这样直接从redis拿数据库快,所以需要有一个定时任务的接口去定时获取数据然后缓存下来,这样每次用户请求博客的时候拿到的数据就是之前获取过的数据
操作
首先要有一个接口脚本,我这个脚本要把站点共享出来,然后在共享出来的页面中获取数据
import httpx
import time
import uvicorn
from fastapi import FastAPI
from fastapi_utilities import repeat_every
from fastapi.middleware.cors import CORSMiddleware
async def get_data():
async with httpx.AsyncClient() as session:
website_id = "xxxxxxxxxxx"# 站点id
url = "https://umami.xxxxx.com"# umami地址
share_id = "xxxxx"
login_url = f"{url}/api/share/{share_id}"
try:
token_response = await session.get(login_url, timeout=100)
token_response.raise_for_status()
token = token_response.json()["token"]
headers = {"x-umami-share-token": token}
timestamp_ms = int(time.time() * 1000)
today_website = f"{url}/api/websites/{website_id}/stats?startAt=1&endAt={timestamp_ms}"
today_res = await session.get(today_website, headers=headers, timeout=100)
today_res.raise_for_status()
today_data = today_res.json()
pageviews = today_data["pageviews"]["value"]
visitors = today_data["visitors"]["value"]
print(pageviews, visitors)
return {
"pageviews": pageviews,
"visitors": visitors
}
except httpx.HTTPStatusError as e:
print(f"HTTP error occurred: {e}")
except Exception as e:
print(f"An error occurred: {e}")
return {
"pageviews": 0,
"visitors": 0
}
data_store = {
"pageviews": 0,
"visitors": 0
}
@repeat_every(seconds=600)
async def job():
global data_store
data_store = await get_data()
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 允许所有源
allow_credentials=True,
allow_methods=["*"], # 允许所有方法
allow_headers=["*"], # 允许所有头
)
app.add_event_handler("startup", job)
@app.get("/")
async def root():
return data_store
if __name__ == '__main__':
uvicorn.run(app, host="0.0.0.0", port=8000)
之后修改博客页面,添加一些js
fetch('https://xxxx.xxxxx.com/')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(umami_data => {
// 将获取到的数据显示在前端
document.getElementById('pageviews').textContent = umami_data.pageviews;
document.getElementById('visitors').textContent = umami_data.visitors;
})
.catch(error => {
console.error('There was a problem with the fetch operation:', error);
document.getElementById('pageviews').textContent = 'Error';
document.getElementById('visitors').textContent = 'Error';
});
添加页面
<div id="umami_data">
<tr align="center">
<td> <i class="fa fa-regular fa-eye " style="color: #ff8e2d;"></i> 本站总访问量 <span id="pageviews"></span> 次
</td>
<td> <i class="fa fa-regular fa-user " style="color: #ff8e2d;"></i> 本站总访客数 <span id="visitors"></span> 人
</td>
</tr>
</div>
欢迎关注我的博客www.bboy.app
Have Fun