Django統(tǒng)計(jì)前臺站點(diǎn)訪問數(shù)量
后端
Django框架自帶sqlite3數(shù)據(jù)庫驹碍,通過models.py文件內(nèi)定義數(shù)據(jù)庫類用來存儲訪問信息
from django.db import models
import time
# 網(wǎng)站總訪問次數(shù)
class VisitNumber(models.Model):
date = models.IntegerField(verbose_name='網(wǎng)站訪問時間', default=int(time.time()))
class Meta:
verbose_name = '網(wǎng)站訪問時間'
verbose_name_plural = verbose_name
def __str__(self):
return str(self.count)
新增接口准给,用以向數(shù)據(jù)庫中新增一條數(shù)據(jù),前臺頁面渲染過程中調(diào)用一次該接口
def set_visit_count(request):
cur_time = int(time.time())
count_nums = VisitNumber()
count_nums.date = cur_time
count_nums.save()
return JsonResponse({"status": True, "data": cur_time})
新增接口虐译,用以從數(shù)據(jù)庫獲取訪問信息
conn = sqlite3.connect("/root/Django/db.sqlite3")
cursor = conn.cursor()
data = cursor.execute(f"select * from DeployProductRepair_visitnumber where date > {start_time} and date < {end_time};")
conn.commit()
cur_time_visit = len(data.fetchall())
cursor.close()
conn.close()
return cur_time_visit
因?yàn)閙odels.py文件發(fā)生改變腾务,所以需要在環(huán)境上重新生成數(shù)據(jù)庫表裙椭,執(zhí)行以下兩行命令岳链,之后啟動python服務(wù)
python3 /root/Django/manage.py makemigrations
python3 /root/Django/manage.py migrate
nohup python3 /root/Django/manage.py runserver 10.243.22.192:8080
前端
src/api/index.ts文件中增加一個請求
const setVisitCount = (params) => {
return request.get("/setVisitCount/", params) as Promise<{
status: boolean;
data: Array<any>;
}>;
}
在總?cè)肟谖募pp.tsx中增加調(diào)用請求
import { setVisitCount } from "./api/index.ts";
//并不需要對返回值做處理花竞,因此可以不必使用await同步
const visitCount = setVisitCount(null);
在需要顯示數(shù)據(jù)的頁面調(diào)用獲取請求并渲染即可
const { data, count } = await getUseData({ type: this.state.type });
this.setState({
visitCount: count,
});