Ai
1 Star 0 Fork 0

anydev/nicegui

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
prometheus.py 1.58 KB
一键复制 编辑 原始数据 按行查看 历史
Falko Schindler 提交于 2023-10-23 16:24 +08:00 . remove log module from public API
import inspect
import logging
import uuid
from fastapi import FastAPI, Request, Response
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
EXCLUDED_USER_AGENTS = {'bot', 'spider', 'crawler', 'monitor', 'curl',
'wget', 'python-requests', 'kuma', 'health check'}
def start_monitor(app: FastAPI) -> None:
try:
import prometheus_client
except ModuleNotFoundError:
logging.info('Prometheus not installed, skipping monitoring')
return
visits = prometheus_client.Counter('nicegui_page_visits', 'Number of real page visits',
['path', 'session', 'origin'])
class PrometheusMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
if 'id' not in request.session:
request.session['id'] = str(uuid.uuid4())
response = await call_next(request)
if response.headers.get('x-nicegui-content') == 'page':
agent = request.headers.get('user-agent', 'unknown').lower()
# ignore monitoring, web crawlers and the like
if not any(s in agent for s in EXCLUDED_USER_AGENTS):
origin_url = request.headers.get('referer', 'unknown')
visits.labels(request.get('path'), request.session['id'], origin_url).inc()
return response
if inspect.stack()[-2].filename.endswith('spawn.py'):
prometheus_client.start_http_server(9062)
app.add_middleware(PrometheusMiddleware)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/anydev/nicegui.git
git@gitee.com:anydev/nicegui.git
anydev
nicegui
nicegui
main

搜索帮助