-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.py
78 lines (62 loc) · 2.3 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
from piccolo.engine import engine_finder
from piccolo_admin.endpoints import create_admin
from secure import SecureHeaders
from starlette.applications import Starlette
from starlette.middleware.authentication import AuthenticationMiddleware
from starlette.middleware.sessions import SessionMiddleware
from starlette.routing import Route
from starlette.staticfiles import StaticFiles
from accounts.routes import accounts_routes
from accounts.tables import UserAuthentication
from ads.routes import ads_routes
from ads.tables import Ad, Image, Notification, Rent, Review
from home.endpoints import HomeEndpoint
from settings import SECRET_KEY, templates
# Security Headers are HTTP response headers that, when set,
# can enhance the security of your web application
# by enabling browser security policies.
# more on https://secure.readthedocs.io/en/latest/headers.html
secure_headers = SecureHeaders()
routes = [
Route("/", HomeEndpoint, name="index"),
]
app = Starlette(debug=True, routes=routes)
app.mount(
"/admin/",
create_admin(tables=[Ad, Review, Image, Rent, Notification]),
)
app.mount("/static", StaticFiles(directory="static"), name="static")
app.mount("/accounts", accounts_routes)
app.mount("/ads", ads_routes)
app.add_middleware(AuthenticationMiddleware, backend=UserAuthentication())
app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY)
# middleware for secure headers
@app.middleware("http")
async def set_secure_headers(request, call_next):
response = await call_next(request)
secure_headers.starlette(response)
return response
@app.exception_handler(404)
async def not_found(request, exc):
"""
Return an HTTP 404 page.
"""
template = "404.html"
context = {"request": request}
return templates.TemplateResponse(template, context, status_code=404)
@app.exception_handler(500)
async def server_error(request, exc):
"""
Return an HTTP 500 page.
"""
template = "500.html"
context = {"request": request}
return templates.TemplateResponse(template, context, status_code=500)
@app.on_event("startup")
async def open_database_connection_pool():
engine = engine_finder()
await engine.start_connnection_pool()
@app.on_event("shutdown")
async def close_database_connection_pool():
engine = engine_finder()
await engine.close_connnection_pool()