summaryrefslogtreecommitdiff
path: root/megapixels/app/server/create.py
blob: a1ce56df8202b35478ff3c74a25ac5a6eea56208 (plain)
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
import logging
import logging.handlers

logger = logging.getLogger("")
logger.setLevel(logging.DEBUG)
handler = logging.handlers.RotatingFileHandler("flask.log",
    maxBytes=3000000, backupCount=2)
formatter = logging.Formatter(
    '[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logging.getLogger().addHandler(logging.StreamHandler())

logging.debug("starting app")

from flask import Flask, Blueprint, jsonify, send_from_directory
from flask_sqlalchemy import SQLAlchemy
from app.models.sql_factory import connection_url, load_sql_datasets

from app.settings import app_cfg as cfg
from app.server.api import api
from app.server.api_task import api_task

db = SQLAlchemy()

def create_app(script_info=None):
  """
  functional pattern for creating the flask app
  """
  app = Flask(__name__, static_folder='static', static_url_path='')
  app.config['SQLALCHEMY_DATABASE_URI'] = connection_url
  app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
  app.config['CELERY_BROKER_URL'] = cfg.CELERY_BROKER_URL
  app.config['CELERY_RESULT_BACKEND'] = cfg.CELERY_RESULT_BACKEND

  db.init_app(app)
  datasets = load_sql_datasets(replace=False, base_model=db.Model)

  app.register_blueprint(api, url_prefix='/api')
  app.register_blueprint(api_task, url_prefix='/task')
  app.add_url_rule('/<path:file_relative_path_to_root>', 'serve_page', serve_page, methods=['GET'])

  @app.route('/', methods=['GET'])
  def index():
    return app.send_static_file('index.html')

  @app.shell_context_processor
  def shell_context():
    return { 'app': app, 'db': db }

  @app.route("/site-map")
  def site_map():
    links = []
    for rule in app.url_map.iter_rules():
      # url = url_for(rule.endpoint, **(rule.defaults or {}))
      # print(url)
      links.append((rule.endpoint))
    return(jsonify(links))

  return app

def serve_page(file_relative_path_to_root):
  """
  trying to get this to serve /path/ with /path/index.html,
  ...but it doesnt actually matter for production...
  """
  if file_relative_path_to_root[-1] == '/':
    file_relative_path_to_root += 'index.html'
  return send_from_directory("static", file_relative_path_to_root)