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 __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
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 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 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, 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 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 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 getCookieExpire(self, session): if session.permanent: return datetime.utcnow() + ConfigManager.getConfig()['PERMANENT_SESSION_LIFETIME']
def getCookieSecure(self): return ConfigManager.getConfig()['SESSION_COOKIE_SECURE']
def getCookieHttpOnly(self): return ConfigManager.getConfig()['SESSION_COOKIE_HTTPONLY']
def run(self, *args, **options): 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') if len(args): app = importFromString(args[0]) else: app = importFromString(currentConfig['APP_DIRECTORY'] + '.' + currentConfig['MAIN_SCRIPT'] + '.' + currentConfig['APP_INSTANCE_NAME']) if not self.debug and currentConfig['DEBUG']: self.debug = True if options.get('browser'): timer = threading.Timer(0.5, self.openBrowser, args=[self.host, self.port]) timer.start() # key = KeywordListenerThread() # key.register(KeywordCallback(self.openBrowser, [self.host, self.port]), 'b', 'browser')
#!/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 testGetConfig(self): config = Config() ConfigManager.configrations = {} ConfigManager.addConfig(config) self.assertEqual(ConfigManager.getConfig('development'), config)
def new(self): 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)
from sqlalchemy import create_engine from sqlalchemy import * from sqlalchemy.orm import * from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative import declared_attr from sqlalchemy.ext.declarative import DeclarativeMeta from sqlalchemy.orm import sessionmaker, scoped_session from shimehari.configuration import ConfigManager from sqlalchemy import func from formencode import Invalid from inflector import Inflector import copy inflector = Inflector() config = ConfigManager.getConfig() url = config['SQLALCHEMY_DATABASE_URI'] engineOptions = {} engineOptions['encoding'] = 'utf-8' if config.get('DEBUG'): from shimehari_debugtoolbar.helpers.sqlalchemy_debug import ConnectionDebugProxy engineOptions['proxy'] = ConnectionDebugProxy('main') engine = create_engine(url, **engineOptions) session = scoped_session(sessionmaker(autoflush=False, bind=engine)) class Model(object):
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 __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
def _exec_log(self): __import__('config') config = ConfigManager.getConfig() logDir = os.path.join(os.getcwd(), config['LOG_FILE_DIRECTORY']) self._removeFiles(logDir, r'\.log$')
#!/usr/bin/env python # -*- coding: utf-8 -*- from formencode import htmlfill from shimehari import request, ApplicationController, redirect, flash, getFlashedMessage from shimehari.configuration import ConfigManager from app.models.articles import ArticleModel from app.models.sites import SystemInfoModel from app.models.tags import createTags, updateTags from app.helpers.paginator import Pagination PER_PAGE = ConfigManager.getConfig()["PER_PAGE"] class IndexController(ApplicationController): def __init__(self, name): ApplicationController.__init__(self, name) def index(self, *args, **kwargs): u"""メモを一覧で表示します。""" page = kwargs["page"] if "page" in kwargs else 1 count = SystemInfoModel.getArticleCount() articles = ArticleModel.getArticleForPage(page, PER_PAGE) pagination = Pagination(page, PER_PAGE, count) alert = dict(getFlashedMessage(withCategory=True)) return self.renderTemplate( "index/index.html", articles=articles, pagination=pagination, pagePath="/page/", alert=alert )