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

Pierre Dittgen's avatar
Pierre Dittgen committed
7
import cachecontrol
8 9
import flask
import jinja2
10 11 12 13
import requests
import tableschema
from cachetools.func import ttl_cache

14
import opendataschema
15

16
from . import config
17

Christophe Benz's avatar
Christophe Benz committed
18 19
log = logging.getLogger(__name__)

20

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


Pierre Dittgen's avatar
Pierre Dittgen committed
26 27
# And load schema catalogs which urls are found in config.json
schema_catalog_map = {}
28
if config.HOMEPAGE_CONFIG:
Christophe Benz's avatar
Christophe Benz committed
29
    log.info("Initializing homepage sections...")
Pierre Dittgen's avatar
Pierre Dittgen committed
30
    caching_session = cachecontrol.CacheControl(requests.Session())
31 32 33 34
    for section in config.HOMEPAGE_CONFIG['sections']:
        if isinstance(section['catalog'], str) and section['catalog'].startswith('http'):
            code = section['code']
            url = section['catalog']
Pierre Dittgen's avatar
Pierre Dittgen committed
35
            schema_catalog_map[code] = opendataschema.SchemaCatalog(url, session=caching_session)
36 37

# Flask things
38
app = flask.Flask(__name__)
39 40
app.secret_key = config.SECRET_KEY

41

42 43 44 45
# 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__)

46

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


53
# Keep this import after app initialisation (to avoid cyclic imports)
54
from . import views  # noqa isort:skip