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

Commit

Permalink
Divide environs (#63)
Browse files Browse the repository at this point in the history
Split environs
  • Loading branch information
c-bata committed Jan 1, 2017
1 parent 85f0e6d commit 2f14476
Show file tree
Hide file tree
Showing 15 changed files with 471 additions and 472 deletions.
9 changes: 5 additions & 4 deletions kobin/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
from .app import (
Kobin, Config,
Kobin, load_config,
load_config_from_module, load_config_from_pyfile
)
from .environs import (
request, BaseResponse, Response,
TemplateResponse, JSONResponse, RedirectResponse, HTTPError
from .requests import request
from .responses import (
BaseResponse, Response, TemplateResponse,
JSONResponse, RedirectResponse, HTTPError
)
68 changes: 38 additions & 30 deletions kobin/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ def index() -> Response:
import traceback

from .routes import Router
from .environs import request, HTTPError
from .requests import request
from .responses import HTTPError


class Kobin:
Expand All @@ -32,7 +33,7 @@ class Kobin:
"""
def __init__(self, config=None):
self.router = Router()
self.config = config if config else Config()
self.config = config if config else load_config()
self.before_request_callback = None
self.after_request_callback = None

Expand Down Expand Up @@ -96,42 +97,49 @@ def _handle_unexpected_exception(e, debug):
return response


class Config(dict):
"""This class manages your application configs.
"""
def __init__(self, **kwargs):
init_kw = {
'BASE_DIR': os.path.abspath('.'),
'TEMPLATE_DIRS': [os.path.join(os.path.abspath('.'), 'templates')],
'DEBUG': False,
}
init_kw.update(kwargs)
super().__init__(**init_kw)
self._template_env = None

@property
def template_env(self):
if self._template_env is None:
from jinja2 import Environment, FileSystemLoader
self._template_env = Environment(loader=FileSystemLoader(self['TEMPLATE_DIRS']))
return self._template_env
# 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
return Environment(loader=FileSystemLoader(template_dirs), **envoptions)
except ImportError:
pass


def load_config(config=None):
default_config = {
'BASE_DIR': os.path.abspath('.'),
'TEMPLATE_DIRS': [os.path.join(os.path.abspath('.'), 'templates')],
'DEBUG': False,
}
if config is None:
return default_config

default_config.update(config)

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


def load_config_from_module(module):
return Config(**{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):
module = SourceFileLoader('config', filepath).load_module()
return load_config_from_module(module)


def current_app():
"""Get your Kobin class object."""
return request['kobin.app']


def current_config():
def current_config(key, default=None):
"""Get the configurations of your Kobin's application."""
return current_app().config
return request['kobin.app'].config.get(key, default)
20 changes: 7 additions & 13 deletions kobin/app.pyi
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
from typing import Callable, Dict, List, Tuple, Iterable, TypeVar, Any
from types import ModuleType
from jinja2 import Environment # type: ignore

from .routes import Router
from .environs import BaseResponse, Response
from .responses import BaseResponse, Response


WSGIEnvironValue = TypeVar('WSGIEnvironValue')
Expand All @@ -16,11 +15,11 @@ WSGIResponse = Iterable[bytes]

class Kobin:
router: Router
config: Config
config: Dict[str, Any]
before_request_callback: Callable[[], None]
after_request_callback: Callable[[BaseResponse], BaseResponse]

def __init__(self, config: Config = ...) -> None: ...
def __init__(self, config: Dict[str, Any] = ...) -> None: ...
def route(self, rule: str = ..., method: str = ..., name: str = ...,
callback: ViewFunction = ...) -> ViewFunction: ...
def before_request(self, callback: Callable[[], None]) -> Callable[[], None]: ...
Expand All @@ -33,13 +32,8 @@ class Kobin:
def _get_traceback_message(e: BaseException) -> str: ...
def _handle_unexpected_exception(e: BaseException, debug: bool) -> Response: ...

class Config(dict):
_template_env: Environment

def __init__(self, **kwargs: Dict[str, Any]) -> None: ...
def template_env(self) -> Environment: ...

def load_config_from_pyfile(filepath: str) -> Config: ...
def load_config_from_module(module: ModuleType) -> Config: ...
def load_config(config: Dict[str, Any] = ...) -> Dict[str, Any]: ...
def load_config_from_pyfile(filepath: str) -> Dict[str, Any]: ...
def load_config_from_module(module: ModuleType) -> Dict[str, Any]: ...
def current_app() -> Kobin: ...
def current_config() -> Config: ...
def current_config(key: str) -> Any: ...
131 changes: 0 additions & 131 deletions kobin/environs.pyi

This file was deleted.

0 comments on commit 2f14476

Please sign in to comment.