__init__.py 1.38 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 7
import flask
import jinja2
8 9 10 11
import requests
import tableschema
from cachetools.func import ttl_cache

12
import opendataschema
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 29
# And load schema catalogs which urls are found in config.json
schema_catalog_map = {}
30 31 32 33 34 35
if config.HOMEPAGE_CONFIG:
    for section in config.HOMEPAGE_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)
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