__init__.py 1.93 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 8
import flask
import jinja2
9 10 11
import requests
import tableschema

Christophe Benz's avatar
Christophe Benz committed
12
import cachecontrol
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 23 24 25 26 27 28 29
def generate_schema_from_url_func(session):
    """Generates a function that encloses session"""

    def schema_from_url(url):
        req = session.get(url)
        req.raise_for_status()
        schema_dict = req.json()
        return tableschema.Schema(schema_dict)

    return schema_from_url
30 31


32 33
# And load schema catalogs which urls are found in config.json
schema_catalog_map = {}
34
if config.HOMEPAGE_CONFIG:
Christophe Benz's avatar
Christophe Benz committed
35
    log.info("Initializing homepage sections...")
Pierre Dittgen's avatar
Pierre Dittgen committed
36
    caching_session = cachecontrol.CacheControl(requests.Session())
37
    schema_from_url = generate_schema_from_url_func(caching_session)
38 39 40 41
    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
42
            schema_catalog_map[code] = opendataschema.SchemaCatalog(url, session=caching_session)
43 44

# Flask things
45
app = flask.Flask(__name__)
46 47
app.secret_key = config.SECRET_KEY

Christophe Benz's avatar
Christophe Benz committed
48 49 50 51 52
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)
53

54 55 56 57
# 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__)

58

59 60 61 62 63 64
@jinja2.contextfilter
@blueprint.app_template_filter()
def urlencode(context, value):
    return quote_plus(value)


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