63 lines
1.8 KiB
Python
63 lines
1.8 KiB
Python
import sys
|
|
import time
|
|
|
|
from flask import current_app, g, render_template, request
|
|
from flask import Flask
|
|
|
|
from scodoc.api import APIError, ScoDocAuthError
|
|
from config import DevConfig
|
|
|
|
|
|
class ReverseProxied:
|
|
"""Adaptateur wsgi qui nous permet d'avoir toutes les URL calculées en https
|
|
sauf quand on est en dev.
|
|
La variable HTTP_X_FORWARDED_PROTO est positionnée par notre config nginx"""
|
|
|
|
def __init__(self, app):
|
|
self.app = app
|
|
|
|
def __call__(self, environ, start_response):
|
|
scheme = environ.get("HTTP_X_FORWARDED_PROTO")
|
|
if scheme:
|
|
environ["wsgi.url_scheme"] = scheme # ou forcer à https ici ?
|
|
return self.app(environ, start_response)
|
|
|
|
# --------- Logging
|
|
def log(msg: str):
|
|
"""log a message.
|
|
If Flask app, use configured logger, else stderr.
|
|
"""
|
|
if current_app and not current_app.config["DEBUG"]:
|
|
current_app.logger.info(msg)
|
|
else:
|
|
sys.stdout.flush()
|
|
sys.stderr.write(
|
|
f"""[{time.strftime("%a %b %d %H:%M:%S %Y")}] scodoc: {msg}\n"""
|
|
)
|
|
sys.stderr.flush()
|
|
|
|
def handle_sco_api_error(exc):
|
|
"page d'erreur avec message"
|
|
log("Error: handle_sco_api_error")
|
|
return render_template("errors/sco_api_error.j2", exc=exc), 404
|
|
|
|
def handle_sco_auth_error(exc):
|
|
"page d'erreur avec message"
|
|
log("Error: handle_sco_auth_error")
|
|
return render_template("errors/sco_auth_error.j2", exc=exc), 404
|
|
|
|
|
|
def create_app(config_class=DevConfig):
|
|
app = Flask(__name__, static_url_path="/AutoSco/static", static_folder="static")
|
|
app.config.from_object(config_class)
|
|
app.wsgi_app = ReverseProxied(app.wsgi_app)
|
|
|
|
from app.views import bp
|
|
|
|
app.register_blueprint(bp)
|
|
|
|
app.register_error_handler(APIError, handle_sco_api_error)
|
|
app.register_error_handler(ScoDocAuthError, handle_sco_auth_error)
|
|
|
|
return app
|