forked from modmail-dev/logviewer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
83 lines (52 loc) · 1.88 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
__version__ = "1.1"
import os
from motor.motor_asyncio import AsyncIOMotorClient
from sanic import Sanic, response
from sanic.exceptions import abort, NotFound
from jinja2 import Environment, FileSystemLoader
from core.models import LogEntry
if "URL_PREFIX" in os.environ:
print("Using the legacy config var `URL_PREFIX`, rename it to `LOG_URL_PREFIX`")
prefix = os.environ["URL_PREFIX"]
else:
prefix = os.getenv("LOG_URL_PREFIX", "/logs")
if prefix == "NONE":
prefix = ""
app = Sanic(__name__)
app.static("/static", "./static")
jinja_env = Environment(loader=FileSystemLoader("templates"))
def render_template(name, *args, **kwargs):
template = jinja_env.get_template(name + ".html")
return response.html(template.render(*args, **kwargs))
app.ctx.render_template = render_template
@app.listener("before_server_start")
async def init(app, loop):
app.ctx.db = AsyncIOMotorClient(os.getenv("MONGO_URI")).modmail_bot
@app.exception(NotFound)
async def not_found(request, exc):
return render_template("not_found")
@app.get("/")
async def index(request):
return render_template("index")
@app.get(prefix + "/raw/<key>")
async def get_raw_logs_file(request, key):
"""Returns the plain text rendered log entry"""
document = await app.ctx.db.logs.find_one({"key": key})
if document is None:
abort(404)
log_entry = LogEntry(app, document)
return log_entry.render_plain_text()
@app.get(prefix + "/<key>")
async def get_logs_file(request, key):
"""Returns the html rendered log entry"""
document = await app.ctx.db.logs.find_one({"key": key})
if document is None:
abort(404)
log_entry = LogEntry(app, document)
return log_entry.render_html()
if __name__ == "__main__":
app.run(
host=os.getenv("HOST", "0.0.0.0"),
port=os.getenv("PORT", 41999),
debug=bool(os.getenv("DEBUG", False)),
)