def testSetControllerFromRouter(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) self.assertEqual(app.controllers, {}) router = Router([Resource(TestController, root=True)]) app.setControllerFromRouter(router) self.assertNotEqual(app.controllers, {})
def testJsoniFy(self): d = dict(a=23, b=42, c=[1, 2, 3]) ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) #hum def returnKwargs(): return shimehari.jsonify(**d) def returnDict(): return shimehari.jsonify(d) app.router = shimehari.Router([ Rule('/kw', endpoint='returnKwargs', methods=['GET']), Rule('/dict', endpoint='returnDict', methods=['GET']) ]) app.controllers['returnKwargs'] = returnKwargs app.controllers['returnDict'] = returnDict c = app.testClient() for url in '/kw', '/dict': rv = c.get(url) print rv.mimetype self.assertEqual(rv.mimetype, 'application/json') self.assertEqual(shimehari.json.loads(rv.data), d)
def testStaticFile(self): ConfigManager.removeConfig('development') ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) app.setStaticFolder('static') with app.testRequestContext(): rv = app.sendStaticFile('index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assertEqual(cc.max_age, 12 * 60 * 60) rv = shimehari.sendFile(os.path.join(app.rootPath, 'static/index.html')) cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assertEqual(cc.max_age, 12 * 60 * 60) app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600 with app.testRequestContext(): rv = app.sendStaticFile('index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assertEqual(cc.max_age, 3600) rv = shimehari.sendFile(os.path.join(app.rootPath, 'static/index.html')) cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assertEqual(cc.max_age, 3600) class StaticFileApp(shimehari.Shimehari): def getSendFileMaxAge(self, filename): return 10 app = StaticFileApp(__name__) app.setStaticFolder('static') with app.testRequestContext(): rv = app.sendStaticFile('index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assertEqual(cc.max_age, 10) rv = shimehari.sendFile(os.path.join(app.rootPath, 'static/index.html')) cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assertEqual(cc.max_age, 10)
def testTemplateEscaping(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) app.setupTemplater() render = shimehari.renderTempalteString with app.testRequestContext(): rv = render('{{"</script>"|tojson|safe }}') self.assertEqual(rv, '"</script>"') rv = render('{{"<\0/script>"|tojson|safe }}') self.assertEqual(rv, '"<\\u0000/script>"')
def testTemplateEscaping(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) app.setupTemplater() render = shimehari.renderTemplateString with app.testRequestContext(): rv = render('{{"</script>"|tojson|safe }}') self.assertEqual(rv, '"</script>"') rv = render('{{"<\0/script>"|tojson|safe }}') self.assertEqual(rv, '"<\\u0000/script>"')
def testGenerateURL(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) def index(*args, **kwargs): return 'index' app.router = shimehari.Router([Rule('/', endpoint='index', methods=['GET'])]) with app.appContext(): rv = shimehari.urlFor('index') self.assertEqual(rv, 'https://localhost/')
def testJSONBadRequests(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) def returnJSON(*args, **kwargs): return unicode(shimehari.request.json) app.router = shimehari.Router([Rule('/json', endpoint='returnJSON', methods=['POST'])]) app.controllers['returnJSON'] = returnJSON c = app.testClient() rv = c.post('/json', data='malformed', content_type='application/json') self.assertEqual(rv.status_code, 400)
def testGotFirstRequest(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) self.assertEqual(app.gotFirstRequest, False) def returnHello(*args, **kwargs): return 'Hello' app.router = shimehari.Router([Rule('/hell', endpoint='returnHello', methods=['POST'])]) app.controllers['returnHello'] = returnHello c = app.testClient() c.get('/hell', content_type='text/planetext') self.assert_(app.gotFirstRequest)
def testGenerateURL(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) def index(*args, **kwargs): return "index" app.router = shimehari.Router([Rule("/", endpoint="index", methods=["GET"])]) with app.appContext(): rv = shimehari.urlFor("index") self.assertEqual(rv, "https://localhost/")
def testJSONAttr(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) def returnJSON(*args, **kwargs): return unicode(shimehari.request.json['a'] + shimehari.request.json['b']) app.router = shimehari.Router([Rule('/add', endpoint='returnJSON', methods=['POST'])]) app.controllers['returnJSON'] = returnJSON c = app.testClient() rv = c.post('/add', data=shimehari.json.dumps({'a': 1, 'b': 2}), content_type='application/json') self.assertEqual(rv.data, '3')
def testJSONBadRequests(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) def returnJSON(*args, **kwargs): return unicode(shimehari.request.json) app.router = shimehari.Router( [Rule('/json', endpoint='returnJSON', methods=['POST'])]) app.controllers['returnJSON'] = returnJSON c = app.testClient() rv = c.post('/json', data='malformed', content_type='application/json') self.assertEqual(rv.status_code, 400)
def testAddRoute(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) self.assertEqual(app.controllers, {}) self.assertEqual(app.router._rules, []) def index(*args, **kwargs): return 'Sake nomitai.' app.addRoute('/', index) c = app.testClient() rv = c.get('/', content_type='text/html') self.assertEqual(rv.status_code, 200) self.assert_('Sake nomitai.' in rv.data)
def testSetup(self): # ConfigManager.addConfig(testConfig) ConfigManager.removeConfig('development') ConfigManager.addConfig(Config('development', {'AUTO_SETUP': False, 'SERVER_NAME': 'localhost', 'PREFERRED_URL_SCHEME': 'https'})) app = shimehari.Shimehari(__name__) app.appPath = os.path.join(app.rootPath, 'testApp') app.appFolder = 'shimehari.testsuite.testApp' app.setupTemplater() app.setupBindController() app.setupBindRouter() self.assertNotEqual(app.controllers, {}) self.assertNotEqual(app.router._rules, {}) pass
def testGenerateURL(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) def index(*args, **kwargs): return 'index' app.router = shimehari.Router( [Rule('/', endpoint='index', methods=['GET'])]) with app.appContext(): rv = shimehari.urlFor('index') self.assertEqual(rv, 'https://localhost/')
def jsonBodyEncoding(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) app.testing = True def returnJSON(*args, **kwargs): return shimehari.request.json app.router = shimehari.Router([Rule('/json', endpoint='returnJSON', methods=['GET'])]) app.controllers['returnJSON'] = returnJSON c = app.testClient() resp = c.get('/', data=u"はひ".encode('iso-8859-15'), content_type='application/json; charset=iso-8859-15') self.assertEqual(resp.data, u'はひ'.encode('utf-8'))
def getConfig(self): u"""現在アプリケーションに適用されているコンフィグを返します。""" configs = ConfigManager.getConfigs() try: # from .config import config configs = ConfigManager.getConfigs() except ImportError: pass if not configs: cfg = Config(self.currentEnv, self.defaultConfig) ConfigManager.addConfig(cfg) return cfg else: return configs[self.currentEnv]
def testJSONBadRequestsContentType(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) @csrfExempt def returnJSON(*args, **kwargs): return unicode(shimehari.request.json) app.router = shimehari.Router([Rule('/json', endpoint='returnJSON', methods=['POST'])]) app.controllers['returnJSON'] = returnJSON c = app.testClient() rv = c.post('/json', data='malformed', content_type='application/json') self.assertEqual(rv.status_code, 400) self.assertEqual(rv.mimetype, 'application/json') self.assert_('description' in shimehari.json.loads(rv.data)) self.assert_('<p>' not in shimehari.json.loads(rv.data)['description'])
class Command(AbstractCommand): name = 'routes' summary = "Show Application routing" usage = "Usage: %prog [OPTIONS]" def __init__(self): super(Command, self).__init__() def handle(self, *args, **options): try: importFromString('config') except ImportError: sys.path.append(os.getcwd()) try: importFromString('config') except ImportError, e: t = sys.exc_info()[2] raise CommandError(u'コンフィグファイルが見当たりません:: %s' % e), None, traceback.print_tb(t) config = ConfigManager.getConfig(getEnviron()) appPath = os.path.join(os.getcwd(), config['APP_DIRECTORY']) if not os.path.isdir(appPath): t = sys.exc_info()[2] raise CommandError( u'アプリケーションが見当たりません::'), None, traceback.print_tb(t) try: router = importFromString(config['APP_DIRECTORY'] + '.' + 'router') except Exception, e: t = sys.exc_info()[2] raise CommandError(u'ルーターがみつかりません。\n %s' % e), None, traceback.print_tb(t)
def csrfProtect(self, requestToken=None): if shared._csrfExempt: return if not request.method in ['POST', 'PUT', 'PATCH', 'DELETE']: return sessionToken = session.get('_csrfToken', None) if not sessionToken: # CSRF token missing abort(403) config = ConfigManager.getConfig() secretKey = config['SECRET_KEY'] hmacCompare = hmac.new(secretKey, str(sessionToken).encode('utf-8'), digestmod=sha1) token = requestToken if requestToken is not None else request.form.get('_csrfToken') if hmacCompare.hexdigest() != token: # invalid CSRF token if self.csrfHandler: self.csrfHandler(*self.app.matchRequest()) else: abort(403) if not self.checkCSRFExpire(token): # CSRF token expired abort(403)
def __init__(self, importName, appFolder='app', controllerFolder='controllers', viewFolder=None): self.importName = importName self.currentEnv = getEnviron() self.rootPath = getRootPath(self.importName) from shimehari.configuration import ConfigManager config = ConfigManager.getConfig(self.currentEnv) if config and self.rootPath == os.getcwd( ) + '/' + config['APP_DIRECTORY']: self.rootPath = os.getcwd() self.appFolder = config['APP_DIRECTORY'] if config and config[ 'APP_DIRECTORY'] else appFolder self.controllerFolder = config['CONTROLLER_DIRECTORY'] if config and \ config['CONTROLLER_DIRECTORY'] else controllerFolder self.viewFolder = config['VIEW_DIRECTORY'] if config and config[ 'VIEW_DIRECTORY'] else viewFolder self._staticFolder = config['ASSETS_DIRECTORY'] if config and config[ 'ASSETS_DIRECTORY'] else None self._staticURL = None
def handle(self, moduleType, name, *args, **options): if not moduleType == 'controller': raise CommandError('ない') path = options.get('path') if path is None: currentPath = os.getcwd() try: importFromString('config') except: sys.path.append(os.getcwd()) try: importFromString('config') except ImportError: raise CommandError('config file is not found...') config = ConfigManager.getConfig(getEnviron()) path = os.path.join(currentPath, config['APP_DIRECTORY'], config['CONTROLLER_DIRECTORY']) if not os.path.isdir(path): raise CommandError('Given path is invalid') ctrlTemplate = os.path.join(shimehari.__path__[0], 'core', 'conf', 'controller_template.org.py') name, filename = self.filenameValidation(path, name) newPath = os.path.join(path, filename) self.readAndCreateFileWithRename(ctrlTemplate, newPath, name)
def run(self, *args, **options): import config # try: # #humu- # import config # except ImportError, e: # sys.path.append(os.getcwd()) # try: # import config # except ImportError, e: # t = sys.exc_info()[2] # raise DrinkError(u'ちょっと頑張ったけどやっぱりコンフィグが見当たりません。\n%s' % e), None, traceback.print_exc(t) try: currentEnv = options.get('SHIMEHARI_ENV') currentConfig = ConfigManager.getConfig(currentEnv or 'development') app = importFromString( currentConfig['MAIN_SCRIPT'] + '.' + currentConfig['APP_INSTANCE_NAME']) if options.get('browser'): timer = threading.Timer(0.5, self.openBrowser, args=[self.host, self.port]) timer.start() app.run(host=self.host, port=int(self.port), debug=True) except: raise
def get(self, sid): if not self.is_valid_key(sid): return self.new() config = ConfigManager.getConfig() secretKey = config['SECRET_KEY'] if secretKey is not None: return self.session_class.load_cookie(request, key=self.key, secret_key=secretKey, sid=sid)
def jsonBodyEncoding(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) app.testing = True def returnJSON(*args, **kwargs): return shimehari.request.json app.router = shimehari.Router( [Rule('/json', endpoint='returnJSON', methods=['GET'])]) app.controllers['returnJSON'] = returnJSON c = app.testClient() resp = c.get('/', data=u"はひ".encode('iso-8859-15'), content_type='application/json; charset=iso-8859-15') self.assertEqual(resp.data, u'はひ'.encode('utf-8'))
def __init__(self, storetype=None): config = ConfigManager.getConfig(getEnviron()) if config['CACHE_STORE'] is not None: store = config['CACHE_STORE'] else: store = storetype self.store = self._importCacheStore(store)
def _importCacheStore(self, storetype): if storetype == 'simple': return SimpleCacheStore() if storetype == 'memcache': return MemcachedCacheStore() if storetype == 'file': config = ConfigManager.getConfig(getEnviron()) return FileSystemCacheStore(cacheDir=config['CACHE_DIR']) if storetype == 'redis': return RedisCacheStore() return NullCacheStore()
def testJSONAttr(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) def returnJSON(*args, **kwargs): return unicode(shimehari.request.json['a'] + shimehari.request.json['b']) app.router = shimehari.Router( [Rule('/add', endpoint='returnJSON', methods=['POST'])]) app.controllers['returnJSON'] = returnJSON c = app.testClient() rv = c.post('/add', data=shimehari.json.dumps({ 'a': 1, 'b': 2 }), content_type='application/json') self.assertEqual(rv.data, '3')
def generateCSRFToken(): if not '_csrfToken' in session: session['_csrfToken'] = genereateToken() now = datetime.datetime.now() + datetime.timedelta() session['_csrfTokenAdded'] = time.mktime(now.timetuple()) config = ConfigManager.getConfig() secretKey = config['SECRET_KEY'] hmacCsrf = hmac.new(secretKey, str(session['_csrfToken']).encode('utf-8'), digestmod=sha1) return hmacCsrf.hexdigest()
def testHasChild(self): ConfigManager.removeConfig("development") ConfigManager.addConfig(testConfig) def index(*args, **kwargs): return "index" def show(*args, **kwargs): return "show" router = RESTfulRouter( [Resource(IndexController, [Resource(ChildController)]), RESTfulRule("test", index, show)] ) app = shimehari.Shimehari(__name__) app.setupTemplater() app.router = router app.setControllerFromRouter(router) c = app.testClient() rv = c.get("/index/1", content_type="text/planetext") self.assertEqual(rv.data, "response show")
def testTryTriggerBeforeFirstRequest(self): ConfigManager.removeConfig('development') ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) app.testCnt = 0 @app.beforeFirstRequest def doFirst(): app.testCnt = app.testCnt + 1 return app.testCnt def returnHello(*args, **kwargs): return 'Hello' app.router = shimehari.Router([Rule('/hell', endpoint='returnHello', methods=['POST'])]) app.controllers['returnHello'] = returnHello c = app.testClient() self.assertEqual(app.testCnt, 0) c.get('/hell', content_type='text/planetext') self.assertEqual(app.testCnt, 1) c.get('/hell', content_type='text/planetext') self.assertEqual(app.testCnt, 1)
def testHasChild(self): ConfigManager.removeConfig('development') ConfigManager.addConfig(testConfig) def index(*args, **kwargs): return 'index' def show(*args, **kwargs): return 'show' router = RESTfulRouter([ Resource(IndexController, [Resource(ChildController)]), RESTfulRule('test', index, show), ]) app = shimehari.Shimehari(__name__) app.setupTemplater() app.router = router app.setControllerFromRouter(router) c = app.testClient() rv = c.get('/index/1', content_type='text/planetext') self.assertEqual(rv.data, "response show")
def testStaticFile(self): ConfigManager.removeConfig('development') ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) app.staticFolder = 'static' with app.testRequestContext(): print app.appFolder print app.staticFolder rv = app.sendStaticFile('index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assertEqual(cc.max_age, 12 * 60 * 60) rv = shimehari.sendFile( os.path.join(app.rootPath, 'static/index.html')) cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assertEqual(cc.max_age, 12 * 60 * 60) app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 3600 with app.testRequestContext(): rv = app.sendStaticFile('index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assertEqual(cc.max_age, 3600) rv = shimehari.sendFile( os.path.join(app.rootPath, 'static/index.html')) cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assertEqual(cc.max_age, 3600) class StaticFileApp(shimehari.Shimehari): def getSendFileMaxAge(self, filename): return 10 app = StaticFileApp(__name__) app.staticFolder = 'static' with app.testRequestContext(): rv = app.sendStaticFile('index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assertEqual(cc.max_age, 10) rv = shimehari.sendFile( os.path.join(app.rootPath, 'static/index.html')) cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assertEqual(cc.max_age, 10)
def handle(self, *args, **options): try: importFromString('config') except ImportError: sys.path.append(os.getcwd()) try: importFromString('config') except ImportError: raise CommandError(u'コンフィグファイルが見当たりません') env = options.get('env') if env is None: env = 'development' sys.stdout.write('\nYour Shimehari App Current Config.\n\n') sys.stdout.write('-------------------------------------------------\n') sys.stdout.write(ConfigManager.getConfig(env).dump()) sys.stdout.write('\n')
def __init__(self, importName, appFolder='app', controllerFolder='controllers', viewFolder=None): self.importName = importName self.currentEnv = getEnviron() self.rootPath = getRootPath(self.importName) from shimehari.configuration import ConfigManager config = ConfigManager.getConfig(self.currentEnv) if config and self.rootPath == os.getcwd() + '/' + config['APP_DIRECTORY']: self.rootPath = os.getcwd() self.appFolder = config['APP_DIRECTORY'] if config and config['APP_DIRECTORY'] else appFolder self.controllerFolder = config['CONTROLLER_DIRECTORY'] if config and \ config['CONTROLLER_DIRECTORY'] else controllerFolder self.viewFolder = config['VIEW_DIRECTORY'] if config and config['VIEW_DIRECTORY'] else viewFolder self._staticFolders = {} if config and config['ASSETS_DIRECTORY']: assetsDir = config['ASSETS_DIRECTORY'] if type(assetsDir) is list: [self._staticFolders.setdefault(x, x) for x in assetsDir] else: self._staticFolders = {assetsDir: assetsDir} if config and config['STATIC_DIRECTORY']: staticDir = config['STATIC_DIRECTORY'] if isinstance(staticDir, (list, tuple)): [self._staticFolders.setdefault(x, x) for x in staticDir] elif isinstance(staticDir, dict): self._staticFolders.update(staticDir) else: self._staticFolders.setdefault(staticDir, staticDir) self._staticURLDict = {} def _assetsURL(self): if config['ASSETS_DIRECTORY'] in self._staticFolders: return self.getStaticURL(config['ASSETS_DIRECTORY']) else: return None self.assetsURL = property(_assetsURL) del _assetsURL
def __init__(self, importName, appFolder='app', controllerFolder='controllers', viewFolder=None): self.importName = importName self.currentEnv = getEnviron() self.rootPath = getRootPath(self.importName) from shimehari.configuration import ConfigManager config = ConfigManager.getConfig(self.currentEnv) if config and self.rootPath == os.getcwd() + '/' + config['APP_DIRECTORY']: self.rootPath = os.getcwd() self.appFolder = config['APP_DIRECTORY'] if config and config['APP_DIRECTORY'] else appFolder self.controllerFolder = config['CONTROLLER_DIRECTORY'] if config and \ config['CONTROLLER_DIRECTORY'] else controllerFolder self.viewFolder = config['VIEW_DIRECTORY'] if config and config['VIEW_DIRECTORY'] else viewFolder self._staticFolder = config['ASSETS_DIRECTORY'] if config and config['ASSETS_DIRECTORY'] else None self._staticURL = None
def createLogger(loggerName='shimehariLoagger'): Logger = getLoggerClass() class DebugLogger(Logger): def getEffectiveLevel(x): if x.level == 0 and config['DEBUG']: return DEBUG return Logger.getEffectiveLevel(x) class DebugHandler(StreamHandler): def emit(x, record): StreamHandler.emit(x, record) if config['DEBUG'] else None config = ConfigManager.getConfig(getEnviron()) if config['LOG_FILE_OUTPUT']: fn = os.path.join(config['LOG_FILE_DIRECTORY'], getEnviron()) + '.log' if config['LOG_FILE_ROTATE']: from logging import RotateFileHandler handler = RotateFileHandler(fn, 'a', config['LOG_ROTATE_MAX_BITE'], config['LOG_ROTATE_COUNT']) else: from logging import FileHandler handler = FileHandler(fn, 'a') handler.setFormatter(Formatter(config['LOG_OUTPUT_FORMAT'])) logger = getLogger() else: handler = DebugHandler() handler.setFormatter(Formatter(config['LOG_DEBUG_FORMAT'])) logger = getLogger(loggerName) logger.setLevel(DEBUG) del logger.handlers[:] logger.__class__ = DebugLogger logger.addHandler(handler) return logger
def _exec_log(self): __import__('config') config = ConfigManager.getConfig() logDir = os.path.join(os.getcwd(), config['LOG_FILE_DIRECTORY']) self._removeFiles(logDir, r'\.log$')
ConfigManager.addConfigs([ Config( 'development', { 'DEBUG': False, 'TEST': False, #アプリのディレクトリ名 'APP_DIRECTORY': '%s', 'MAIN_SCRIPT': 'main', #アプリケーションinstanceの名前 'APP_INSTANCE_NAME': 'app', 'CONTROLLER_DIRECTORY': 'controllers', 'VIEW_DIRECTORY': 'views', 'ASSESTS_DIRECTORY': 'assets', #for daiginjou 'MODEL_DIRECTORY': 'models', 'PREFERRED_URL_SCHEME': 'http', 'AUTO_SETUP': True, 'CONTROLLER_AUTO_NAMESPACE': True, 'TEMPLATE_ENGINE': 'jinja2', 'SECRET_KEY': '_secret_shimehari', 'SERVER_NAME': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'PERMANENT_SESSION_LIFETIME': timedelta(days=31), #キャッシュ 'CACHE_STORE': None, 'CACHE_DEFAULT_TIMEOUT': 300, 'CACHE_THRESHOLD': 500, 'CACHE_KEY_PREFIX': None, 'CACHE_DIR': None, 'CACHE_OPTIONS': None, 'CACHE_ARGS': [], 'LOG_FILE_OUTPUT': False, 'LOG_FILE_ROTATE': False, 'LOG_ROTATE_MAX_BITE': (5 * 1024 * 1024), 'LOG_ROTATE_COUNT': 5, 'LOG_FILE_DIRECTORY': '%s/log', 'LOG_DEBUG_FORMAT': '%s', 'LOG_OUTPUT_FORMAT': '%s' }) ])
ConfigManager.addConfigs([ Config( 'development', { 'DEBUG': False, 'TEST': False, #アプリのディレクトリ名 'APP_DIRECTORY': 'app', 'MAIN_SCRIPT': 'main', #アプリケーションinstanceの名前 'APP_INSTANCE_NAME': 'app', 'CONTROLLER_DIRECTORY': 'controllers', 'VIEW_DIRECTORY': 'views', 'ASSESTS_DIRECTORY': 'assets', #for daiginjou 'MODEL_DIRECTORY': 'models', 'PREFERRED_URL_SCHEME': 'http', 'AUTO_SETUP': True, 'CONTROLLER_AUTO_NAMESPACE': True, 'TEMPLATE_ENGINE': 'jinja2', 'SECRET_KEY': '_hagedown', 'SERVER_NAME': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'PERMANENT_SESSION_LIFETIME': timedelta(days=31), 'SESSION_COOKIE_NAME': 'session', 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, #キャッシュ 'CACHE_STORE': None, 'CACHE_DEFAULT_TIMEOUT': 300, 'CACHE_THRESHOLD': 500, 'CACHE_KEY_PREFIX': None, 'CACHE_DIR': None, 'CACHE_OPTIONS': None, 'CACHE_ARGS': [], 'LOG_FILE_OUTPUT': False, 'LOG_FILE_ROTATE': False, 'LOG_ROTATE_MAX_BITE': (5 * 1024 * 1024), 'LOG_ROTATE_COUNT': 5, 'LOG_FILE_DIRECTORY': 'app/log', 'LOG_DEBUG_FORMAT': '--------------------------------------------------------------------------------\n%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n%(message)s\n--------------------------------------------------------------------------------', 'LOG_OUTPUT_FORMAT': '%(asctime)s %(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n%(message)s\n--------------------------------------------------------------------------------', ###application config### 'PER_PAGE': 5 }) ])
#!/usr/bin/env python # -*- coding: utf-8 -*- from shimehari import ApplicationController from shimehari.configuration import ConfigManager from app.models.articles import ArticleModel from app.models.sites import SystemInfoModel from app.models.tags import TagModel from app.helpers.paginator import Pagination PER_PAGE = ConfigManager.getConfig()['PER_PAGE'] class TagsController(ApplicationController): def __init__(self, name): ApplicationController.__init__(self, name) def index(self, *args, **kwargs): tags = SystemInfoModel.getAllTagList() tagList = [] for tag in tags: if tag['count'] > 12: tag['size'] = 12 else: tag['size'] = tag['count'] tagList.append(tag) return self.renderTemplate('tags/index.html', tagList=tagList) def tagIndex(self, *args, **kwargs): name = kwargs['tagname']
def __init__(self, controller=None, children=[], name=None, only=[], excepts=[], root=False, subdomain=None, buildOnly=False, strict_slashes=None, redirectTo=None, alias=False, host=None, defaults=None, namespace=None): Map.__init__(self, rules=[], default_subdomain='', charset='utf-8', strict_slashes=True, redirect_defaults=True, converters=None, sort_parameters=False, sort_key=None, encoding_errors='replace', host_matching=False) if only != [] and excepts != []: raise ValueError('allow or deny!!!!') self._rules = [] self.children = children self.only = only self.excepts = excepts self.root = root self.subdomain = self.default_subdomain = subdomain self.buildOnly = buildOnly self.strict_slashes = strict_slashes self.redirectTo = redirectTo self.alias = alias self.host = host self.defaults = defaults self.name = name self.getName = self.getNameFromRESTAction self.namespace = namespace if self.namespace: if self.namespace.startswith('/'): self.namespace = self.namespace[1:] if self.namespace.endswith('/'): self.namespace = self.namespace[:len(self.namespace) - 1] #ディレクトリが深かった時自動で elif controller is not None: config = ConfigManager.getConfig() if config['CONTROLLER_AUTO_NAMESPACE'] and type(controller) is not int: pkgs = controller.__module__.split('.') appFolder = config['APP_DIRECTORY'] controllerFolder = config['CONTROLLER_DIRECTORY'] if appFolder in pkgs: pkgs.remove(appFolder) if controllerFolder in pkgs: pkgs.remove(controllerFolder) self.orgName = pkgs[len(pkgs) - 1] pkgs = pkgs[:len(pkgs) - 1] self.namespace = "/".join(pkgs) if self.namespace is not '': self._inSubDir = True if controller: controller = self._checkControllerType(controller) if not name: if hasattr(controller, 'baseName'): self.baseName = self.orgName = controller.baseName elif isinstance(controller, Rule): self.baseName = self.orgName = str(controller.endpoint) self.add(controller) #uuuumu if self.root: self.baseName = '/' if self.parent: self.baseName = self.parent.baseName + '/' + self.baseName if isinstance(self.children, list) and len(self.children) > 0: for child in self.children: if not isinstance(child, (Resource, RESTfulRule, Rule)): raise TypeError('children is invalid') if isinstance(child, Rule): child.rule = self.baseName + '/' + child.rule else: child.parent = self child.refresh() if isinstance(child, Resource): self._rules = self._rules + child._rules
try: #humu- import config except ImportError, e: import sys sys.path.append(os.getcwd()) try: import config except ImportError, e: t = sys.exc_info()[2] raise DrinkError(u'ちょっと頑張ったけどやっぱりコンフィグが見当たりません。\n%s' % e), None, traceback.print_exc(t) try: currentEnv = options.get('SHIMEHARI_ENV') currentConfig = ConfigManager.getConfig(currentEnv or 'development') app = importFromString(currentConfig['APP_DIRECTORY'] + '.' + currentConfig['MAIN_SCRIPT'] + '.' + currentConfig['APP_INSTANCE_NAME']) if not self.debug and currentConfig['DEBUG']: self.debug = True def openBrowser(host, port): url = 'http://' if not host: url += '127.0.0.1' else: url += host if not port: url += ':5959/'
def testAppContextProvidesCurrentApp(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) with app.appContext(): self.assertEqual(shimehari.currentApp._get_current_object(), app) self.assertEqual(shimehari._appContextStack.top, None)
def testLogger(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) self.assert_(type(app.logger))
def testGetConfig(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) self.assertEqual(app.getConfig(), testConfig)
def testAddController(self): ConfigManager.addConfig(testConfig) app = shimehari.Shimehari(__name__) self.assertEqual(app.controllers, {}) app.addController(TestController) self.assertNotEqual(app.controllers, {})
import shimehari import unittest from StringIO import StringIO from logging import StreamHandler from shimehari.testsuite import ShimehariTestCase from werkzeug.routing import Rule from shimehari.configuration import ConfigManager, Config testConfig = Config( 'development', { 'AUTO_SETUP': False, 'SERVER_NAME': 'localhost', 'PREFERRED_URL_SCHEME': 'https' }) ConfigManager.addConfig(testConfig) class ShimehariSubclassingTestCase(ShimehariTestCase): def testSuperessedExceptionLogging(self): class SupressedShimehari(shimehari.Shimehari): def logException(self, exc_info): pass out = StringIO() app = SupressedShimehari(__name__) app.loggerName = 'shimehariTests/test' app.logger.addHandler(StreamHandler(out)) def index(): 1 / 0
#!/usr/bin/env python # -*- coding: utf-8 -*- u""" =============================== [[Shimehari Config]] config ~~~~~~ =============================== """ from shimehari.configuration import Config, ConfigManager from werkzeug.utils import import_string from shimehari.helpers import getEnviron currentEnv = getEnviron() obj = import_string('config.%s' % currentEnv) config = {} for key in dir(obj): if key.isupper(): config[key] = getattr(obj, key) ConfigManager.addConfig(Config(currentEnv, config))
ConfigManager.addConfigs([ Config('development', { 'DEBUG': False, 'TEST': False, #アプリのディレクトリ名 'APP_DIRECTORY': 'app', 'MAIN_SCRIPT': 'main', #アプリケーションinstanceの名前 'APP_INSTANCE_NAME': 'app', 'CONTROLLER_DIRECTORY': 'controllers', 'VIEW_DIRECTORY': 'views', 'ASSETS_DIRECTORY':'assets', 'STATIC_DIRECTORY':[], #for daiginjou 'MODEL_DIRECTORY': 'models', 'PREFERRED_URL_SCHEME': 'http', 'AUTO_SETUP': True, 'CONTROLLER_AUTO_NAMESPACE': True, 'TEMPLATE_ENGINE': 'jinja2', 'SECRET_KEY': '_secret_shimehari', 'SERVER_NAME': None, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'PERMANENT_SESSION_LIFETIME': timedelta(days=31), 'SESSION_COOKIE_NAME': '_app_session', 'SESSION_COOKIE_HTTPONLY': True, 'SESSION_COOKIE_SECURE': False, #キャッシュ 'CACHE_STORE': None, 'CACHE_DEFAULT_TIMEOUT': 300, 'CACHE_THRESHOLD': 500, 'CACHE_KEY_PREFIX': None, 'CACHE_DIR': None, 'CACHE_OPTIONS': None, 'CACHE_ARGS': [], 'LOG_FILE_OUTPUT': False, 'LOG_FILE_ROTATE': False, 'LOG_ROTATE_MAX_BITE': (5 * 1024 * 1024), 'LOG_ROTATE_COUNT': 5, 'LOG_FILE_DIRECTORY': 'log', 'LOG_DEBUG_FORMAT': '--------------------------------------------------------------------------------\n%(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n%(message)s\n--------------------------------------------------------------------------------', 'LOG_OUTPUT_FORMAT': '%(asctime)s %(levelname)s in %(module)s [%(pathname)s:%(lineno)d]:\n%(message)s\n--------------------------------------------------------------------------------' }) ])
ConfigManager.addConfigs([ Config( 'development', { 'DEBUG': False, 'TEST': False, 'APP_ROOT': None, #アプリのディレクトリ名 'APP_DIRECTORY': 'testApp', 'MAIN_SCRIPT': 'main', #アプリケーションinstanceの名前 'APP_INSTANCE_NAME': 'app', 'CONTROLLER_DIRECTORY': 'controllers', 'VIEW_DIRECTORY': 'views', #for daiginjou 'MODEL_DIRECTORY': 'models', 'PREFERRED_URL_SCHEME': 'http', 'AUTO_SETUP': True, 'TEMPLATE_ENGINE': 'jinja2', 'USE_X_SENDFILE': False, 'SECRET_KEY': '_secret_shimehari', 'SERVER_NAME': None, 'TRAP_HTTP_EXCEPTIONS': False, 'TRAP_BAD_REQUEST_ERRORS': False, 'PRESERVE_CONTEXT_ON_EXCEPTION': None, 'PERMANENT_SESSION_LIFETIME': timedelta(days=31) }) ])