Skip to content
This repository has been archived by the owner on May 31, 2019. It is now read-only.

Commit

Permalink
Refactor config handling
Browse files Browse the repository at this point in the history
  • Loading branch information
c-bata committed Jan 1, 2017
1 parent dc13a8e commit d7f1d7b
Show file tree
Hide file tree
Showing 6 changed files with 23 additions and 16 deletions.
19 changes: 14 additions & 5 deletions kobin/app.py
Expand Up @@ -97,6 +97,13 @@ def _handle_unexpected_exception(e, debug):
return response


# Following configurations are optional:
#
# Optional
# * DEBUG
# * SECRET_KEY
# * TEMPLATE_DIRS (default: './templates/') or TEMPLATE_ENVIRONMENT
#
def _load_jinja2_env(template_dirs, **envoptions):
try:
from jinja2 import Environment, FileSystemLoader
Expand All @@ -111,19 +118,21 @@ def load_config(config=None):
'TEMPLATE_DIRS': [os.path.join(os.path.abspath('.'), 'templates')],
'DEBUG': False,
}
if config is None:
return default_config

if config:
default_config.update(config)
default_config.update(config)

if config and 'TEMPLATE_RENDERER' not in config:
if 'TEMPLATE_ENVIRONMENT' not in config:
env = _load_jinja2_env(default_config['TEMPLATE_DIRS'])
if env:
default_config['TEMPLATE_RENDERER'] = env
default_config['TEMPLATE_ENVIRONMENT'] = env
return default_config


def load_config_from_module(module):
return {key: getattr(module, key) for key in dir(module) if key.isupper()}
config = {key: getattr(module, key) for key in dir(module) if key.isupper()}
return load_config(config)


def load_config_from_pyfile(filepath):
Expand Down
6 changes: 2 additions & 4 deletions kobin/requests.pyi
@@ -1,8 +1,6 @@
from typing import Dict, List, Tuple, Any, TypeVar, Callable, Union
from wsgiref.headers import Headers # type: ignore
from typing import Dict, List, Tuple, Any, Callable, Union

WSGIEnvironValue = TypeVar('WSGIEnvironValue')
WSGIEnviron = Dict[str, WSGIEnvironValue]
WSGIEnviron = Dict[str, Any]


class Request:
Expand Down
4 changes: 3 additions & 1 deletion kobin/responses.py
Expand Up @@ -139,7 +139,9 @@ class TemplateResponse(BaseResponse):

def __init__(self, filename, status=200, headers=None, charset='utf-8', **tpl_args):
from .app import current_config
template_env = current_config('TEMPLATE_RENDERER')
template_env = current_config('TEMPLATE_ENVIRONMENT')
if template_env is None:
raise HTTPError('TEMPLATE_ENVIRONMENT is not found in your config.')
template = template_env.get_template(filename)
body = [template.render(**tpl_args).encode(charset)]
super().__init__(body, status=status, headers=headers)
Expand Down
5 changes: 2 additions & 3 deletions kobin/responses.pyi
@@ -1,10 +1,9 @@
from datetime import timedelta, date, datetime
from http.cookies import SimpleCookie
from typing import Dict, List, Tuple, Any, Iterable, TypeVar, Callable, Union
from typing import Dict, List, Tuple, Any, Iterable, Callable, Union
from wsgiref.headers import Headers # type: ignore

WSGIEnvironValue = TypeVar('WSGIEnvironValue')
WSGIEnviron = Dict[str, WSGIEnvironValue]
WSGIEnviron = Dict[str, Any]


HTTP_CODES: Dict[int, str]
Expand Down
3 changes: 1 addition & 2 deletions setup.py
Expand Up @@ -5,7 +5,6 @@

BASE_PATH = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(BASE_PATH, 'README.rst')).read()
CHANGES = open(os.path.join(BASE_PATH, 'CHANGES.rst')).read()

__version__ = '0.1.4'
__author__ = 'Masashi Shibata <contact@c-bata.link>'
Expand Down Expand Up @@ -55,7 +54,7 @@ def run_tests(self):
author_email=__author_email__,
url='https://github.com/kobinpy/kobin',
description='A Minimal WSGI Framework to develop your web application comfortably',
long_description=README + '\n\n' + CHANGES,
long_description=README,
classifiers=__classifiers__,
packages=find_packages(exclude=['test*']),
install_requires=[],
Expand Down
2 changes: 1 addition & 1 deletion tests/test_responses.py
Expand Up @@ -91,7 +91,7 @@ class Jinja2TemplateTests(TestCase):
def test_file(self, mock_config):
""" Templates: Jinja2 file """
config = load_config({'TEMPLATE_DIRS': TEMPLATE_DIRS})
mock_config.return_value = config['TEMPLATE_RENDERER']
mock_config.return_value = config['TEMPLATE_ENVIRONMENT']
response = TemplateResponse('jinja2.html', var='kobin')
actual = response.body
expected = [b"Hello kobin World."]
Expand Down

0 comments on commit d7f1d7b

Please sign in to comment.