__init__.py 1.44 KB
Newer Older
Pierre Dittgen's avatar
Pierre Dittgen committed
1
import json
2
import os
3
from pathlib import Path
4
from urllib.parse import quote_plus
5

6
import opendataschema
7 8
import flask
import jinja2
9 10 11 12
import requests
import tableschema
from cachetools.func import ttl_cache

13

14 15
# Let this import after app initialisation
from . import config
16

17

18
@ttl_cache(maxsize=50, ttl=5*60)
19 20 21 22
def download_with_cache(url):
    return requests.get(url)


23
@ttl_cache(maxsize=24, ttl=5*60)
24 25 26 27
def schema_from_url(url):
    return tableschema.Schema(url)


28
# load config.json
Pierre Dittgen's avatar
Pierre Dittgen committed
29
ui_config = json.load(config.UI_CONFIG_FILE.open('rt', encoding='utf-8')) if config.UI_CONFIG_FILE else []
30

31 32 33 34 35 36 37
# And load schema catalogs which urls are found in config.json
schema_catalog_map = {}
for section in ui_config['sections']:
    if isinstance(section['catalog'], str) and section['catalog'].startswith('http'):
        code = section['code']
        url = section['catalog']
        schema_catalog_map[code] = opendataschema.SchemaCatalog(url, download_func=download_with_cache)
38 39

# Flask things
40
app = flask.Flask(__name__)
41 42
app.secret_key = config.SECRET_KEY

43

44 45 46 47
# Jinja2 url_quote_plus custom filter
# https://stackoverflow.com/questions/12288454/how-to-import-custom-jinja2-filters-from-another-file-and-using-flask
blueprint = flask.Blueprint('filters', __name__)

48

49 50 51 52 53 54
@jinja2.contextfilter
@blueprint.app_template_filter()
def urlencode(context, value):
    return quote_plus(value)


55 56
# Keep this import after app initialisation (to avoid cyclic imports)
from . import views  # isort:skip