-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
69 lines (55 loc) · 2.11 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
61
62
63
64
65
66
67
68
69
#!/usr/bin/env python
import os, sys
from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse, HTMLResponse
from jinja2 import Environment, PackageLoader, select_autoescape
from jinja2.ext import i18n
DJAOAPP_SUBDOMAIN = "livedemo"
DJAOAPP_API_BASE_URL = os.getenv('DJAOAPP_API_BASE_URL')
if not DJAOAPP_API_BASE_URL:
sys.stderr.write("warning: cannot find DJAOAPP_API_BASE_URL"\
" in the environment. Please define DJAOAPP_API_BASE_URL before running"\
" the server on your development machine. For example:"\
" `export DJAOAPP_API_BASE_URL=\"https://livedemo.djaoapp.com/api\"`.")
app = FastAPI()
env = Environment(
loader=PackageLoader(DJAOAPP_SUBDOMAIN),
autoescape=select_autoescape(),
extensions=[i18n]
)
env.install_null_translations()
def prefix_filter(path):
if not path or path.startswith('/assets'):
return "https://www.djaoapp.com%s" % path
return path
env.filters['asset'] = prefix_filter
env.filters['site_url'] = prefix_filter
# Serves the homepage, i.e. http://127.0.0.1:8000/
@app.get("/", response_class=HTMLResponse)
def read_root():
return read_page('index')
# Serves the favicon
@app.get("/favicon.ico")
def read_favicon():
return read_asset('favicon.ico', prefix=None)
# Serves public assets such as .css and .js files.
@app.get("/assets/{asset_path:path}")
def read_asset_assets(asset_path):
return read_asset(asset_path, prefix='assets')
# Serves public static assets such as .css and .js files.
@app.get("/static/{asset_path:path}")
def read_asset(asset_path, prefix='static'):
if prefix:
pathname = os.path.join(DJAOAPP_SUBDOMAIN, 'public', prefix, asset_path)
else:
pathname = os.path.join(DJAOAPP_SUBDOMAIN, 'public', asset_path)
if not os.path.exists(pathname):
raise HTTPException(status_code=404)
return FileResponse(pathname)
# Serves HTML pages, i.e. http://127.0.0.1:8000/{page}/
@app.get("/{page:path}/", response_class=HTMLResponse)
def read_page(page):
template = env.get_template("%s.html" % page)
return template.render(request="", urls={
'api_base': DJAOAPP_API_BASE_URL
})