Exemple #1
0
def add_cache_control(evt):
    req = evt.request
    res = req.response

    env = Env()
    if env.get('ENV', 'production') != 'production':
        res.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
Exemple #2
0
def resolve_env_vars(settings):
    env = Env()
    s = settings.copy()
    for k, v in Env.settings_mappings().items():
        # ignores missing key or it has a already value in config
        if k not in s or s[k]:
            continue
        new_v = env.get(v, None)
        if not isinstance(new_v, str):
            continue
        # ignores empty string
        if ',' in new_v:
            s[k] = [nv for nv in new_v.split(',') if nv != '']
        elif new_v:
            s[k] = new_v
    return s
Exemple #3
0
class TemplateUtility(object):
    # pylint: disable=no-self-use

    def __init__(self, ctx, req, **kwargs):
        self.context, self.req = ctx, req

        self.env = Env()

        if getattr(req, 'util', None) is None:
            req.util = self
        self.__dict__.update(kwargs)

    @reify
    def manifest_json(self):  # type: () -> dict
        manifest_file = path.join(self.project_root, 'static', 'manifest.json')
        data = {}
        if path.isfile(manifest_file):
            with open(manifest_file) as data_file:
                data = json.load(data_file)

        return data

    @reify
    def project_root(self):  # type: () -> None
        return path.join(path.dirname(__file__), '..')

    @reify
    def var(self):  # type: () -> dict
        """Returns a dict has variables."""
        return {  # external services
            'gitlab_url': self.env.get('GITLAB_URL', '/'),
            'tinyletter_url': self.env.get('TINYLETTER_URL', '/'),
            'twitter_url': self.env.get('TWITTER_URL', '/'),
            'typekit_id': self.env.get('TYPEKIT_ID', ''),
            'userlike_script': self.env.get('USERLIKE_SCRIPT', '/'),
        }

    def is_matched(self, matchdict):  # type: (dict) -> bool
        return self.req.matchdict == matchdict

    def static_url(self, filepath):  # type: (str) -> str
        from thun.route import STATIC_DIR

        def get_bucket_info(name):
            part = self.req.settings.get('bucket.{0:s}'.format(name))
            if not part:
                # returns invalid path
                return ''
            return re.sub(UNSLASH_PATTERN, '', part)

        if self.env.is_production:
            h, n, p = [get_bucket_info(x) for x in ('host', 'name', 'path')]
            return 'https://{0:s}/{1:s}/{2:s}/{3:s}'.format(h, n, p, filepath)
        return self.req.static_url(STATIC_DIR + '/' + filepath)

    def static_path(self, filepath):  # type: (str) -> str
        from thun.route import STATIC_DIR
        return self.req.static_path(STATIC_DIR + '/' + filepath)

    def hashed_asset_url(self, filepath):  # type: (str) -> str
        hashed_filepath = self.manifest_json.get(filepath, filepath)
        return self.static_url(hashed_filepath)

    def allow_svg(self, size):  # type: (str) -> 'function'
        """Returns actual allow_svg as function allowing given size."""
        def _allow_svg(tag, name, value):  # type: (str, str, str) -> bool
            """Returns True if tag is svg and it has allowed attrtibutes."""
            if tag == 'svg' and name in ('width', 'height', 'class'):
                return True
            else:
                if name == 'viewBox':
                    return value == size
            return False

        return _allow_svg