Switch to Django with visitor tracking and server info footnote
All checks were successful
ci/woodpecker/manual/woodpecker Pipeline was successful
All checks were successful
ci/woodpecker/manual/woodpecker Pipeline was successful
This commit is contained in:
61
core/views.py
Normal file
61
core/views.py
Normal file
@@ -0,0 +1,61 @@
|
||||
from datetime import timedelta
|
||||
from django.utils import timezone
|
||||
from django.shortcuts import render
|
||||
from .models import Visit
|
||||
|
||||
|
||||
def _get_server_info():
|
||||
try:
|
||||
with open('/proc/uptime') as f:
|
||||
total_seconds = int(float(f.read().split()[0]))
|
||||
days, rem = divmod(total_seconds, 86400)
|
||||
hours, mins = divmod(rem, 3600)
|
||||
uptime = f"{days}d {hours}h {mins // 60}m"
|
||||
except Exception:
|
||||
uptime = 'N/A'
|
||||
|
||||
try:
|
||||
with open('/proc/loadavg') as f:
|
||||
parts = f.read().split()
|
||||
load = f"{parts[0]} {parts[1]} {parts[2]}"
|
||||
except Exception:
|
||||
load = 'N/A'
|
||||
|
||||
try:
|
||||
meminfo = {}
|
||||
with open('/proc/meminfo') as f:
|
||||
for line in f:
|
||||
key, val = line.split(':')
|
||||
meminfo[key.strip()] = int(val.split()[0])
|
||||
mem_total = meminfo['MemTotal'] // 1024
|
||||
mem_free = meminfo['MemAvailable'] // 1024
|
||||
mem_used = mem_total - mem_free
|
||||
except Exception:
|
||||
mem_total = mem_free = mem_used = 0
|
||||
|
||||
return {
|
||||
'uptime': uptime,
|
||||
'load': load,
|
||||
'mem_total': mem_total,
|
||||
'mem_free': mem_free,
|
||||
'mem_used': mem_used,
|
||||
}
|
||||
|
||||
|
||||
def index(request):
|
||||
forwarded = request.META.get('HTTP_X_FORWARDED_FOR', '')
|
||||
ip = forwarded.split(',')[0].strip() if forwarded else request.META.get('REMOTE_ADDR', 'unknown')
|
||||
|
||||
Visit.objects.create(ip=ip)
|
||||
|
||||
now = timezone.now()
|
||||
start_of_day = now.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
|
||||
context = {
|
||||
'visitor_ip': ip,
|
||||
'visits_today': Visit.objects.filter(timestamp__gte=start_of_day).count(),
|
||||
'visits_week': Visit.objects.filter(timestamp__gte=now - timedelta(days=7)).count(),
|
||||
'visits_month': Visit.objects.filter(timestamp__gte=now - timedelta(days=30)).count(),
|
||||
**_get_server_info(),
|
||||
}
|
||||
return render(request, 'core/index.html', context)
|
||||
Reference in New Issue
Block a user