def testComp14(self): fd, fname=tempfile.mkstemp(suffix=".inc") try: f=os.fdopen(fd, 'w') f.write(""" Hello from me! <:set x `33`:> """) f.close() self.f.write(""" I'm going to call a component now. <:include `compname`:> x is <:val `x`:>. Done. """) self.f.close() suffixes=C.DEFAULT_FILE_COMPONENT_SUFFIX_MAP.copy() suffixes['.comp']=('string', S.STMLFileComponent) suffixes['.inc']=('include', S.STMLFileComponent) Configuration.load_dict(dict(componentFileSuffixMap=suffixes)) res=C.stringcomp(self.fname, compname=fname) print res self.failUnless('Hello from me!\n' in res) self.failUnless("x is 33" in res) finally: os.unlink(fname)
def testCallWithCompileCache(self): Cfg.load_dict(dict(useCompileMemoryCache=True)) comp=self.comp1 d={'a' : 3, 'x' : 2, 'y' : 5} value=comp(d) assert value==(3*(2**5))
def test_stml(): Configuration.load_kw(componentRoot=here) @template('stml:/stmltest.stml') def tester(): return dict(message="my message", mytitle="my title") res=tester() assert "my message" in res assert "my title" in res
def _test(): import sys logging.basicConfig(level=logging.DEBUG) args = sys.argv[1:] if args: Configuration.load_kw(componentRoot=args[0]) from wsgiref.simple_server import make_server from skunk.web.context import ContextMiddleware make_server("localhost", 7777, ContextMiddleware(DispatchingFileServer())).serve_forever()
def _runapp(self, app, environ, start_response): try: return app(environ, start_response) finally: try: try: CleanupContextHook(Context, environ) except: log.exception('error in CleanupContextHook') try: CleanupResourcesHook(Context, environ) except: log.exception('error in CleanupResourcesHook') finally: Context.__dict__.clear() Configuration.trim()
def bootstrap(app=None, *configfiles): """ Steps in bootstrapping: 1. configuration must be read (or it may be initialized already) 2. services must be loaded if they are present. 3. the app must be built if it is not passed in. 4. the server must be started. """ if configfiles: Configuration.load(*configfiles) _setup_logging(Configuration.logConfig) load_services() if not app: app=make_app() run(app)
def test_componentRoot1(): tmpdir=tempfile.mkdtemp() Cfg.load_kw(componentRoot=tmpdir) try: fname=os.path.join(tmpdir, 'index.stml') fp=open(fname, 'w') fp.write('\n'.join([ "<:default kong Chubby:>", "Hello <:val `kong`:>" "<:component /nougat.comp cache=yes:>" ])) fp.close() fp=open(os.path.join(tmpdir, 'nougat.comp'), 'w') fp.write('SERVES YOU RIGHT') fp.close() res=stringcomp('/index.stml', kong='Kong') assert 'Hello Kong' in res finally: Cfg.reset() shutil.rmtree(tmpdir)
def testComp13(self): self.f.write("Hello from me!\n") self.f.close() fd, fname=tempfile.mkstemp(suffix=".comp") try: f=os.fdopen(fd, 'w') f.write(""" I'm going to call a component now. <:component `compname`:> Done. """) f.close() suffixes=C.DEFAULT_FILE_COMPONENT_SUFFIX_MAP.copy() suffixes['.comp']=('string', S.STMLFileComponent) Configuration.load_dict(dict(componentFileSuffixMap=suffixes)) res=C.stringcomp(fname, compname=self.fname) print res self.failUnless('Hello from me!\n' in res) finally: os.unlink(fname)
""" 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
log=logging.getLogger(__name__) sessiondir=tempfile.mkdtemp() def cleanup(): log.info('cleaning up temporary session directory') shutil.rmtree(sessiondir) atexit.register(cleanup) Configuration.load_kw( logConfig={'level' : 'debug'}, sessionEnabled=True, sessionStore=DiskSessionStore(sessiondir), sessionCookieSalt='fudgemeaweatherby', services=['skunk.web.sessions'], controllers=dict(main=__name__), routes=[ (('index', '/'), dict(controller='main', action='dopage')) ]) @expose() def dopage(): session=Context.session number=session.get('number', 0) session['number']=number+1 session.save() return '<em>Your number is %d</em>' % number
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
import os import sys from skunk.config import Configuration from skunk.web import ContextMiddleware, RoutingMiddleware, ControllerServer, expose, bootstrap @expose(content_type='text/plain') def helloworld(): return "Hello World" Configuration.load_kw( logConfig={'level' : 'debug', 'filename' : os.path.abspath('debug.log')}, daemonize=True, useThreads=True, pidfile=os.path.abspath('simplerunner.pid'), controllers=dict(hello=__name__), routes=[(('index', '/'), {'controller' : 'hello', 'action' : 'helloworld'})], bindAddress='TCP:0.0.0.0:7777') app=ContextMiddleware(RoutingMiddleware(ControllerServer())) bootstrap(app)
import os from skunk.config import Configuration, GlobMatcher from skunk.util.pathutil import relpath from skunk.web.auth import CookieFileAuthorizer from skunk.web import ContextMiddleware, DispatchingFileServer, bootstrap Configuration.load_kw(componentRoot=_relpath(__file__, 'files'), services=['skunk.web.auth'], logConfig=dict(level='debug') ) Configuration.addMatcher(GlobMatcher('path', '/protected/*', authorizer=CookieFileAuthorizer( _relpath(__file__, 'auth.conf'), 'nancynonce', '/login.comp'))) app=ContextMiddleware(DispatchingFileServer()) if __name__=='__main__': bootstrap(app)
def setUp(self): self.tmpdir=tempfile.mkdtemp() Cfg.setDefaults(compileCacheRoot=self.tmpdir) self.comp1=Component(code=someCode, name='testcomponent')
""" @expose(content_type="text/plain") def robots(self, color): return "Your robots are about to turn " + color @expose() def wsgi(self): def an_app(environ, start_response): start_response("200 OK", [("Content-Type", "text/plain")]) return ["Hello from a WSGI application"] return an_app comproot = os.path.join(os.path.dirname(__file__), "files") Configuration.load_kw( logConfig=dict(level="debug"), componentRoot=comproot, routes=[ (("robots", "/robots/:color"), {"controller": "simple", "action": "robots"}), (("wsgi", "/wsgi"), {"controller": "simple", "action": "wsgi"}), (("hello", "/hello"), {"controller": "simple"}), ], controllers={"simple": SimpleController()}, ) if __name__ == "__main__": bootstrap()
import os from skunk.config import Configuration from skunk.web import bootstrap, expose, template @expose(content_type='text/plain') def helloworld(name): return 'Hello, World, and furthermore, hi there %s' % name @template('/witch.comp') @expose() def dingdong(): return dict(witch='Brenda', status='dead or missing') Configuration.load_kw( logConfig=dict(level='debug'), componentRoot=os.path.join(os.path.dirname(__file__), 'files'), routes=[ (('hi', 'helloworld/:name'), dict(controller='daone', action='helloworld')), (('ding', 'dingdong'), dict(controller='daone', action='dingdong')), ], controllers={'daone' : __name__}, showTracebacks=True) if __name__=='__main__': bootstrap()
'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():
def tearDown(self): shutil.rmtree(self.componentRoot) Cfg.reset()
def setUp(self): self.componentRoot=tempfile.mkdtemp() Cfg.load_kw(componentRoot=self.componentRoot, useCompileMemoryCache=False)
""" This uses the logconfig service with minimal customization. """ import os from skunk.config import Configuration from skunk.web import expose, bootstrap @expose(content_type='text/plain') def index(): return "A truly pleasant experience\n" Configuration.load_kw( logConfig={'level' : 'debug', 'filename' : 'debug.log'}, routes=[ ((':action',),{'controller' : 'main'}), ], controllers={'main' : __name__}) if __name__=='__main__': bootstrap()
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 *
return dict(message="Edit saved", title=title, body=page.body) routes=[ (('littlewiki', '*title'), dict(controller='littlewiki', action='wikipage')) ] controllers=dict(littlewiki=__name__) comproot=os.path.join(os.path.dirname(__file__), 'files') Configuration.load_kw(routes=routes, componentRoot=comproot, controllers=controllers, logConfig=dict(level='debug'), showTraceback=True) def rollbackConnection(*args, **kwargs): db=pydo.getConnection('littlewiki', False) if db: log.debug("rolling back littlewiki connection") db.rollback() CleanupContextHook.append(rollbackConnection) if __name__=='__main__': bootstrap()
def tearDown(self): shutil.rmtree(self.tmpdir) Cfg.reset()
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():
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"]
# """ 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
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 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']