-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
60 lines (43 loc) · 1.39 KB
/
main.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
import random
import settings
from slugify import slugify
from starlette.applications import Starlette
from starlette.responses import Response
from starlette.routing import Route, Mount
from starlette.staticfiles import StaticFiles
from starlette.templating import Jinja2Templates
from questions import questions
templates = Jinja2Templates(directory="templates")
def get_context_data(request, question, perm=False):
permalink = app.url_path_for("permalink", question=slugify(question))
return {
"question": question,
"permalink": permalink,
"perm": perm,
"request": request,
}
valid_routes = {}
for question in questions:
slug = slugify(question)
valid_routes[slug] = question
def permalink(request):
slug = request.path_params["question"]
try:
question = valid_routes[slug]
except KeyError:
return Response("Not found", status_code=404)
else:
return templates.TemplateResponse(
"question.html", get_context_data(request, question, perm=True),
)
def home(request):
question = random.choice(questions)
return templates.TemplateResponse(
"question.html", get_context_data(request, question)
)
routes = [
Route("/", home),
Route("/{question}", permalink),
Mount("/static", StaticFiles(directory="static")),
]
app = Starlette(debug=settings.DEBUG, routes=routes)