__init__.py 2.04 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

7
import cachecontrol
8 9
import flask
import jinja2
10 11 12
import requests
import tableschema

13
import opendataschema
14

15
from . import config
16

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

19

20 21 22
def generate_schema_from_url_func(session):
    """Generates a function that encloses session"""

23 24 25 26 27
    def tableschema_from_url(url):
        response = session.get(url)
        response.raise_for_status()
        descriptor = response.json()
        return tableschema.Schema(descriptor)
28

29 30 31 32 33
    return tableschema_from_url


caching_session = cachecontrol.CacheControl(requests.Session())
tableschema_from_url = generate_schema_from_url_func(caching_session)
34 35


36
# And load schema catalogs which URLs are found in homepage_config.json
37
schema_catalog_map = {}
38
if config.HOMEPAGE_CONFIG:
Christophe Benz's avatar
Christophe Benz committed
39
    log.info("Initializing homepage sections...")
40
    for section in config.HOMEPAGE_CONFIG['sections']:
Christophe Benz's avatar
Christophe Benz committed
41 42
        name = section['name']
        log.info('Initializing homepage section "{}"...'.format(name))
43 44 45
        catalog = section.get('catalog')
        if catalog and isinstance(catalog, str) and catalog.startswith('http'):
            schema_catalog_map[name] = opendataschema.SchemaCatalog(catalog, session=caching_session)
46
    log.info("...done")
47 48

# Flask things
49
app = flask.Flask(__name__)
50 51
app.secret_key = config.SECRET_KEY

Christophe Benz's avatar
Christophe Benz committed
52 53 54 55 56
matomo = None
if config.MATOMO_AUTH_TOKEN and config.MATOMO_BASE_URL and config.MATOMO_SITE_ID:
    from flask_matomo import Matomo
    matomo = Matomo(app, matomo_url=config.MATOMO_BASE_URL,
                    id_site=config.MATOMO_SITE_ID, token_auth=config.MATOMO_AUTH_TOKEN)
57

58 59 60 61
# 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__)

62

63 64 65 66 67 68
@jinja2.contextfilter
@blueprint.app_template_filter()
def urlencode(context, value):
    return quote_plus(value)


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