def default_500_body(self, tb): t = string.Template("<h2>$title</h2>$explanation<br />$detail<br /><pre>$traceback</pre>$comment") args = dict( explanation=self.explanation or "", detail=self.detail or "", comment=self.comment or "", title=self.title, traceback=tb, ) return t.substitute(args) DEFAULT_ERRORS[500] = InternalServerError Configuration.setDefaults(errorHandlers=DEFAULT_ERRORS, errorPage=None, notFoundPage=None, showTraceback=True) def get_http_exception(status, *args, **kwargs): handlerclass = Configuration.errorHandlers[status] handler = handlerclass(*args, **kwargs) return handler def handle_error(status, environ, start_response, *args, **kwargs): handler = get_http_exception(status, *args, **kwargs) return handler(environ, start_response) __all__ = ["DEFAULT_ERRORS", "get_http_exception"]
from skunk.web.fileserver import * from skunk.web.context import * from skunk.web.controller import * from skunk.web.routing import * from skunk.web.buffet import * from skunk import __version__ from skunk.config import Configuration from skunk.web.routing import _redirect Configuration.setDefaults( serverIdentification='Skunkweb %s' % __version__, defaultCharset='utf-8', defaultContentType='text/html', # this overrides variable set in skunk.stml redirectFunc=_redirect ) del Configuration, __version__, _redirect from skunk.web.bootstrapper import *
""" Description goes here. """ from skunk.components.objects import * from skunk.components.compileCache import * from skunk.components.context import * from skunk.components.exceptions import * from skunk.components.handlers import * from skunk.components.api import * from skunk.config import Configuration Configuration.setDefaults( useCompileMemoryCache=True, compileCachePath=None, componentRoot='/', componentCache=':memory:', componentCacheDebugMemcached=False, componentExtraGlobals=None, componentFileSuffixMap=DEFAULT_FILE_COMPONENT_SUFFIX_MAP, componentHandlers=defaultComponentHandlers) del Configuration
def setUp(self): self.tmpdir=tempfile.mkdtemp() Cfg.setDefaults(compileCacheRoot=self.tmpdir) self.comp1=Component(code=someCode, name='testcomponent')
import logging from skunk.config import Configuration Configuration.setDefaults(userLogger='USER') def getUserLogger(): """returns the logger used for user logging in STML""" return logging.getLogger(Configuration.userLogger) def debug(msg, *args, **kwargs): getUserLogger().debug(msg, *args, **kwargs) def info(msg, *args, **kwargs): getUserLogger().info(msg, *args, **kwargs) def warn(msg, *args, **kwargs): getUserLogger().warn(msg, *args, **kwargs) def error(msg, *args, **kwargs): getUserLogger().error(msg, *args, **kwargs) def exception(msg, *args, **kwargs): getUserLogger().exception(msg, *args, **kwargs) __all__=['debug', 'info', 'warn', 'error', 'exception']
from UserDict import DictMixin import cPickle from hashlib import sha256 import random import time from uuid import uuid4 from skunk.config import Configuration from skunk.web.context import Context Configuration.setDefaults( sessionTimeout=18000, # in seconds (30 minutes) sessionTouchInterval=20, # seconds sessionCookieMaxSize=3900, # bytes sessionCookieName="skunksession", sessionCookieNonce="", sessionEnabled=True, sessionServerStore=None, sessionStaleAction=None, ) DIGESTSIZE = 64 SALTSIZE = 4 class Session(object, DictMixin): def __init__(self): self.dirty = False self._data = None self._session_id = None self._mtime = 0
# """ A library for the memoization of functions and other callables. """ from skunk.cache.exceptions import * from skunk.cache.base import * from skunk.cache.policy import * from skunk.cache.memoryCache import * from skunk.cache.diskCache import * from skunk.cache.decorator import * from skunk.cache.log import * from skunk.config import Configuration as _c _c.setDefaults(defaultCacheExpiration='30s', defaultCachePolicy=YES, defaultCacheOndefer=None) del _c
"\.(comp|pydcmp|pyinc|pycomp|inc)$", # skunk components "~$", # backup file "\.conf$", # configuration files ] DEFAULT_INDEX_DOCUMENTS = ["index.html", "index.stml", "index.xml", "index.py"] DEFAULT_FILE_DISPATCHERS = [(".*\.(stml|html|py)$", "skunk.web.fileserver:serve_stml")] Configuration.setDefaults( hiddenFilePatterns=DEFAULT_HIDDEN_FILE_PATTERNS, indexDocuments=DEFAULT_INDEX_DOCUMENTS, # options for serving static files with x-sendfile staticFileUseXSendFile=False, staticFileXSendFileHeader="X-Sendfile", staticFileXSendFileHeaderPathTranslated=True, staticFileAddEtag=False, # whether to guess the character encoding of static text files # with chardet, if available staticFileUseChardet=True, # for dispatching server, a list of (pattern, handler) pairs fileDispatchers=DEFAULT_FILE_DISPATCHERS, ) class FileServerBase(object): def get_request(self, environ): try: return Context.request except AttributeError: return webob.Request(environ)
'filename' : None, 'stream' : None, 'level' : logging.WARN, 'format' : '%(name)s %(asctime)s %(levelname)s %(message)s' 'datefmt' : None}]} the same logger can have multiple handlers. Each handler has a level (can be inherited), a formatter. """ import logging from skunk.config import Configuration Configuration.setDefaults(logConfig={'' : dict( level=logging.WARN, format='%(name)s %(asctime)s %(levelname)s %(message)s', datefmt=None)}) def get_level(lvl): if isinstance(lvl, str): try: lvl=logging._levelNames[lvl.upper()] except KeyError: raise ConfigurationError("unknown log level: %s" % lvl) return lvl def _setup_logging(logconfig): if not logconfig: return if all(isinstance(d, (list, tuple, dict)) for d in logconfig.itervalues()): for logname, configs in logconfig.iteritems():
import sha import time import uuid from skunk.config import Configuration from skunk.web.context import Context, InitContextHook, CleanupContextHook from skunk.util.importutil import import_from_string log=logging.getLogger(__name__) # set configuration variables Configuration.setDefaults( sessionEnabled=False, sessionCookieName='skunksession', sessionCookiePath='/', sessionCookieExtras=None, sessionTimeout=18000, # in seconds: 30 minutes sessionStaleAction=None, ) # hook to enable sessions and put them in the context def _init_session_hook(ctxt, env): if Configuration.sessionEnabled: ctxt.session=Session() def _session_cleanup_hook(ctxt, env): if Configuration.sessionEnabled: Context.session.save() def enable():
doing this manually in a module. """ import logging from skunk.config import Configuration from skunk.util.importutil import import_from_string from skunk.web.logconfig import _setup_logging from skunk.web.runner import run log=logging.getLogger(__name__) Configuration.setDefaults(services=[], wsgiPipeline=( 'skunk.web.context:ContextMiddleware', 'skunk.web.routing:RoutingMiddleware', 'skunk.web.controller:ControllerServer', 'skunk.web.fileserver:DispatchingFileServer' ) ) def load_services(): for service in Configuration.services: try: log.info("loading service '%s'", service) s=import_from_string(service) if callable(s): log.debug("service is callable, calling") s() else: initmethod=getattr(s, 'init_service', None)
from cherrypy.wsgiserver import CherryPyWSGIServer as httpserver except ImportError: httpserver=None from skunk.config import Configuration Configuration.setDefaults( # for scgi and fcgi; currently the only http alternatives # are threaded useThreads=False, serverProtocol='http', maxThreads=None, maxSpare=None, minSpare=None, maxChildren=None, maxRequests=None, pidfile=None, daemonize=False, umask=None, user=None, group=None, bindAddress='TCP:127.0.0.1:7777', serverName=None, sslCertificate=None, sslPrivateKey=None) log=logging.getLogger(__name__) class _BindAddress(object):
tagVocabulary=None): STMLComponentMixin.__init__(self, tagVocabulary) StringOutputFileComponent.__init__(self, filename, namespace=namespace) def _precall(self, namespace): namespace=STMLComponentMixin._precall(self, namespace) return StringOutputFileComponent._precall(self, namespace) DEFAULT_STML_FILE_COMPONENT_SUFFIX_MAP={ '.comp' : ('string', STMLFileComponent), '.inc' : ('include', STMLFileComponent), '.stml' : ('string', STMLFileComponent), '.html' : ('string', STMLFileComponent), } DEFAULT_STML_FILE_COMPONENT_SUFFIX_MAP.update(DEFAULT_FILE_COMPONENT_SUFFIX_MAP) Configuration.setDefaults( componentFileSuffixMap=DEFAULT_STML_FILE_COMPONENT_SUFFIX_MAP) __all__=['STMLComponentMixin', 'STMLComponent', 'STMLFileComponent', 'DEFAULT_STML_FILE_COMPONENT_SUFFIX_MAP']
import logging from pkg_resources import iter_entry_points from skunk.config import Configuration from skunk.util.decorators import rewrap log=logging.getLogger(__name__) Configuration.setDefaults(defaultTemplatingEngine='stml', templateEngineOptions={}, defaultControllerTemplate=None) def template(template=None, **template_opts): """ a decorator which indicates that the function should use a template. """ def wrapper(func): def newfunc(*args, **kwargs): data=func(*args, **kwargs) if not isinstance(data, dict): # you decided not to use a template, bye-bye return data tmpl=(template or Configuration.defaultControllerTemplate or Configuration.defaultTemplate) if not tmpl: raise ValueError('no template specified or found in configuration')
import base64 import logging import os from skunk.config import Configuration from skunk.util.armor import armor, dearmor from skunk.util.authenticator import FileAuthenticator from skunk.web.buffet import template from skunk.web.context import Context from skunk.web.exceptions import get_http_exception log=logging.getLogger(__name__) Configuration.setDefaults(authorizer=None, defaultUser=None, authFile=None, users={}, authCookieName='skunkauth', authCookieAttributes={}) def enable(): """ install the auth service. """ from skunk.web.context import InitContextHook if not _auth_hook in InitContextHook: InitContextHook.append(_auth_hook) init_service=enable def _auth_hook(*args, **kwargs): authorizer=Configuration.authorizer
""" support code for using routes middleware. """ import httplib from routes import request_config import routes.middleware from skunk.config import Configuration from skunk.web.context import Context, InitContextHook from skunk.web.exceptions import get_http_exception Configuration.setDefaults(MvcOn=True, routes=[], controllers={}) def _redirect(url, status=httplib.MOVED_PERMANENTLY): raise get_http_exception(status, location=url) def initMapper(context, environ): if not Configuration.MvcOn: return map=routes.Mapper() for r in Configuration.routes: if isinstance(r, dict): map.connect(**r) elif isinstance(r, (list, tuple)): if (len(r)==2 and isinstance(r[0], (list, tuple)) and isinstance(r[1], dict)): map.connect(*r[0], **r[1])
import webob.exc from skunk.config import Configuration from skunk.stml.exceptions import STMLSyntaxError from skunk.stml.parser import Expr, Node from skunk.stml.signature import Signature from skunk.stml.valformat import ValFormatRegistry from skunk.stml.log import debug from skunk.stml.tagutils import get_temp_name def _redirect_func(location, status): raise webob.exc.status_map(status, location=location)() Configuration.setDefaults(redirectFunc=_redirect_func) class BlockTag(Node): """ Base class for block tags, that need to be closed with a second tag. """ isBlock=True localTagDict={} _top=False class EmptyTag(Node): _top=False class CommentTag(BlockTag): """ a tag that emits no code. """