Beispiel #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'
def dotenv():
    from thun.env import Env

    # same as thun:main
    dotenv_file = os.path.join(os.getcwd(), '.env')
    Env.load_dotenv_vars(dotenv_file)

    return
Beispiel #3
0
    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)
def main(argv=None, quiet=False):
    """Runs original pserve with .env support."""
    # NOTE:
    # `pserve` (PServeCommand) needs `hupper`, it has dependency to **fcntl**.
    # In some environment (e.g. app engine), fcntl is not found :'(
    # So, that's why this import is in method.
    from pyramid.scripts.pserve import PServeCommand

    if not argv:
        argv = sys.argv

    Env.load_dotenv_vars()

    command = PServeCommand(argv, quiet=quiet)
    return command.run()
Beispiel #5
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
    def __init__(self, *args, **kwargs):
        env_dict = (args[0] or {})

        # self.environ is request env.
        # the `env` is os's environ handler (wrapper)

        env = Env()
        if env.is_production:
            env_dict = self._force_ssl(env_dict)
            env_dict = self.__class__.trim_port(env_dict)

        new_args = (env_dict, args[1:])
        if sys.version_info[0] > 3:
            # pylint: disable=missing-super-argument
            super().__init__(*new_args, **kwargs)
        else:
            super(CustomRequest, self).__init__(*new_args, **kwargs)
Beispiel #7
0
def includeme(config):
    env = Env()
    cache_max_age = 3600 if env.is_production else 0

    # routes
    # static files at /*
    filenames = [f for f in ('robots.txt', 'humans.txt', 'favicon.ico')
                 if path.isfile((STATIC_DIR + '/{}').format(f))]
    if filenames:
        config.add_asset_views(
            STATIC_DIR, filenames=filenames, http_cache=cache_max_age)

    # static files at /assets/*
    config.add_static_view(
        name='assets', path=STATIC_DIR, cache_max_age=cache_max_age)

    config.add_route('index', '/')  # overview
    config.add_route('pricing', '/pricing')
Beispiel #8
0
def usage(argv):
    cmd = os.path.basename(argv[0])
    print('usage: %s <config_uri> [var=value]\n'
          '(example: "%s {staging|production}.ini")' % (cmd, cmd))
    sys.exit(1)


def main(argv, _quiet=False):
    if len(argv) < 2:
        usage(argv)

    config_uri = argv[1] if 1 in argv else 'config/production.ini'
    wsgi_app = get_app(config_uri, 'thun')
    setup_logging(config_uri)

    return wsgi_app


if __name__ == '__main__':
    # pylint: disable=relative-import
    from paste.script.cherrypy_server import cpwsgi_server
    from thun.env import Env

    Env.load_dotenv_vars()
    env = Env()  # pylint: disable=invalid-name
    cpwsgi_server(main(sys.argv),
                  host=env.host,
                  port=env.port,
                  numthreads=10,
                  request_queue_size=100)
def env(dotenv):
    from thun.env import Env
    return Env()
Beispiel #10
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