Пример #1
0
def __initConfig():
    import SkunkWeb.Configuration as C
    import os
    C.mergeDefaults(
        webdavDB=os.join(C.SkunkRoot, 'var/run/WEBDAVdb'),
        webdavFS=fs.WebdavFS(),
        )
Пример #2
0
def __initConfig():
    import SkunkWeb.Configuration as C
    import os
    C.mergeDefaults(
        webdavDB=os.join(C.SkunkRoot, 'var/run/WEBDAVdb'),
        webdavFS=fs.WebdavFS(),
    )
Пример #3
0
def __initConfig():
    from SkunkWeb import Configuration
    Configuration.mergeDefaults(
        DocumentTimeout=30,
        PostResponseTimeout=20,
        #                                job=None)
    )
Пример #4
0
def __initConfig():
    from AE import cfg
    from SkunkWeb import Configuration, confvars
    # set our defaults from AE defaults
    Configuration.mergeDefaults(
        documentRoot = confvars.DEFAULT_DOCROOT,
        compileCacheRoot = confvars.DEFAULT_CACHE, 
        componentCacheRoot = confvars.DEFAULT_CACHE,
        failoverComponentCacheRoot = "%s/failoverCache" % Configuration.SkunkRoot,
        mimeTypesFile = confvars.DEFAULT_MIME_TYPES_FILE_NAME,
        componentCommentLevel = 0,
        )
    dd = {}
    for k, v in cfg.Configuration._d.items():
        if k not in ['documentRoot',
                     'compileCacheRoot',
                     'componentCacheRoot',
                     'failoverComponentCacheRoot',
                     'mimeTypesFile',
                     'componentCommentLevel']:
            dd[k]=v
    Configuration.mergeDefaults(dd)
            
    # set AE's config object to ours
    cfg.Configuration = Configuration
    __checkScopes(Configuration.scopeMatchers())
Пример #5
0
def __initConfig():
    from AE import cfg
    from SkunkWeb import Configuration
    # set our defaults from AE defaults
    Configuration.mergeDefaults(
        documentRoot="%s/docroot" % Configuration.SkunkRoot,
        compileCacheRoot="%s/cache" % Configuration.SkunkRoot,
        componentCacheRoot="%s/cache" % Configuration.SkunkRoot,
        failoverComponentCacheRoot="%s/failoverCache" %
        Configuration.SkunkRoot,
        mimeTypesFile="%s/etc/mime.types" % Configuration.SkunkRoot,
        componentCommentLevel=0,
    )
    dd = {}
    for k, v in cfg.Configuration._d.items():
        if k not in [
                'documentRoot', 'compileCacheRoot', 'componentCacheRoot',
                'failoverComponentCacheRoot', 'mimeTypesFile',
                'componentCommentLevel'
        ]:
            dd[k] = v
    Configuration.mergeDefaults(dd)

    # set AE's config object to ours
    cfg.Configuration = Configuration
    __checkScopes(Configuration.matchers)
Пример #6
0
def __initConfig():
    from AE import cfg
    from SkunkWeb import Configuration, confvars
    # set our defaults from AE defaults
    Configuration.mergeDefaults(
        documentRoot=confvars.DEFAULT_DOCROOT,
        compileCacheRoot=confvars.DEFAULT_CACHE,
        componentCacheRoot=confvars.DEFAULT_CACHE,
        failoverComponentCacheRoot="%s/failoverCache" %
        Configuration.SkunkRoot,
        mimeTypesFile=confvars.DEFAULT_MIME_TYPES_FILE_NAME,
        componentCommentLevel=0,
    )
    dd = {}
    for k, v in cfg.Configuration._d.items():
        if k not in [
                'documentRoot', 'compileCacheRoot', 'componentCacheRoot',
                'failoverComponentCacheRoot', 'mimeTypesFile',
                'componentCommentLevel'
        ]:
            dd[k] = v
    Configuration.mergeDefaults(dd)

    # set AE's config object to ours
    cfg.Configuration = Configuration
    __checkScopes(Configuration.scopeMatchers())
Пример #7
0
def __initConfig():
    from SkunkWeb import Configuration
    Configuration.mergeDefaults(
        # session timeout, in seconds. 
        SessionTimeout = 30*60,
        
        # the key under which the session is kept
        SessionIDKey='sessionID',
        
        # the host, user, password, and database (for MySQLSessionStoreImpl)
        SessionHandler_MySQLHost='localhost',
        SessionHandler_MySQLUser='******',
        SessionHandler_MySQLPass='******',
        SessionHandler_MySQLDB='sessionStore',
        
        # table, id column, session value column, and timestamp column
        # (for MySQLSessionStoreImpl)
        SessionHandler_MySQLTable='Sessions',
        SessionHandler_MySQLIDColumn='id',
        SessionHandler_MySQLPickleColumn='pickle',
        SessionHandler_MySQLTimestampColumn='accessTime',

        # the same, for PostgreSQLSessionStoreImpl
        SessionHandler_PGHost='localhost',
        SessionHandler_PGUser='******',
        SessionHandler_PGPass='******',
        SessionHandler_PGDB='sessionStore',
        SessionHandler_PGTable='Sessions',
        SessionHandler_PGIDColumn='id',
        SessionHandler_PGPickleColumn='pickle',
        SessionHandler_PGTimestampColumn='accesstime',
        
        # directory where pickle files are stored (for FSSessionStore)
        SessionHandler_FSSessionDir=os.path.join(Configuration.SkunkRoot, 'var/run/skunksessions'),
        
        # reap interval (in seconds).  A negative value, or zero,
        # will turn off reaping.  it would be reasonable for at most
        # one server to reap any given session store.
        SessionReapInterval=300,
        SessionStore=None
        )
Пример #8
0
def __initConfig():
    from SkunkWeb import Configuration
    Configuration.mergeDefaults(
        # session timeout, in seconds.
        SessionTimeout=30 * 60,

        # the key under which the session is kept
        SessionIDKey='sessionID',

        # the host, user, password, and database (for MySQLSessionStoreImpl)
        SessionHandler_MySQLHost='localhost',
        SessionHandler_MySQLUser='******',
        SessionHandler_MySQLPass='******',
        SessionHandler_MySQLDB='sessionStore',

        # table, id column, session value column, and timestamp column
        # (for MySQLSessionStoreImpl)
        SessionHandler_MySQLTable='Sessions',
        SessionHandler_MySQLIDColumn='id',
        SessionHandler_MySQLPickleColumn='pickle',
        SessionHandler_MySQLTimestampColumn='accessTime',

        # the same, for PostgreSQLSessionStoreImpl
        SessionHandler_PGHost='localhost',
        SessionHandler_PGUser='******',
        SessionHandler_PGPass='******',
        SessionHandler_PGDB='sessionStore',
        SessionHandler_PGTable='Sessions',
        SessionHandler_PGIDColumn='id',
        SessionHandler_PGPickleColumn='pickle',
        SessionHandler_PGTimestampColumn='accesstime',

        # directory where pickle files are stored (for FSSessionStore)
        SessionHandler_FSSessionDir=os.path.join(Configuration.SkunkRoot,
                                                 'var/run/skunksessions'),

        # reap interval (in seconds).  A negative value, or zero,
        # will turn off reaping.  it would be reasonable for at most
        # one server to reap any given session store.
        SessionReapInterval=300,
        SessionStore=None)
Пример #9
0
########################################################################
#  Copyright (C) 2004 Andrew T. Csillag <*****@*****.**>,
#                     Jacob Smullyan <*****@*****.**>
#  
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
########################################################################

from SkunkWeb import Configuration
import PsycopgCache

Configuration.mergeDefaults(PsycopgConnectParams = {})

for u, p in Configuration.PsycopgConnectParams.items():
    PsycopgCache.initUser (u, p)

def rollback(*args):
    for v in PsycopgCache._connections.values():
        v.rollback()

from requestHandler.requestHandler import CleanupRequest
CleanupRequest.addFunction(rollback)
Пример #10
0
#  
#  Copyright (C) 2001 Andrew T. Csillag <*****@*****.**>
#  
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
#   
# $Id: userdir.py,v 1.7 2003/05/01 20:45:53 drew_csillag Exp $
########################################################################

import pwd
from SkunkWeb import Configuration

Configuration.mergeDefaults(userDir = 1,
                            userDirPath = 'public_html')

from SkunkWeb import ServiceRegistry
ServiceRegistry.registerService('userdir')
from SkunkWeb.LogObj import DEBUG
from SkunkWeb.ServiceRegistry import USERDIR    

def doUserDirPre(connection, sessionDict):
    """
    hook for web.protocol.PreHandleConnection
    """
    
    if not Configuration.userDir:
        return
    if connection.uri[:2] != '/~':
        return
    else:
Пример #11
0
# Time-stamp: <03/04/15 00:23:55 smulloni>
# $Id: spreadcache_service.py,v 1.2 2003/05/01 20:45:53 drew_csillag Exp $

########################################################################
#  Copyright (C) 2003 Jacob Smullyan <*****@*****.**>
#
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
#
########################################################################

from SkunkWeb import Configuration
import spreadcache

Configuration.mergeDefaults(SpreadConnectParams={})

for alias, params in Configuration.SpreadConnectParams.items():
    spreadcache.initAlias(alias, **params)
Пример #12
0
########################################################################
#  Copyright (C) 2002 Andrew T. Csillag <*****@*****.**>
#  
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
########################################################################

from SkunkWeb import Configuration
import PyPgSQLcache

Configuration.mergeDefaults(
    PyPgSQLConnectParams = {},
    )

for u, p in Configuration.PyPgSQLConnectParams.items():
    PyPgSQLcache.initUser ( u, p )

def rollback(*args):
    for v in PyPgSQLcache._connections.values():
        v.rollback()

from requestHandler.requestHandler import CleanupRequest
CleanupRequest.addFunction(rollback)
Пример #13
0
########################################################################
#  Copyright (C) 2002 Andrew T. Csillag <*****@*****.**>
#
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
########################################################################

from SkunkWeb import Configuration
import PyPgSQLcache

Configuration.mergeDefaults(PyPgSQLConnectParams={}, )

for u, p in Configuration.PyPgSQLConnectParams.items():
    PyPgSQLcache.initUser(u, p)


def rollback(*args):
    for v in PyPgSQLcache._connections.values():
        v.rollback()


from requestHandler.requestHandler import CleanupRequest

CleanupRequest.addFunction(rollback)
Пример #14
0
#
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
#

from SkunkWeb import Configuration, ServiceRegistry
from SkunkWeb.LogObj import DEBUG
from requestHandler.protocol import PreemptiveResponse
import AE.Cache
import os
import Authenticator
import sys
import base64

Configuration.mergeDefaults(basicAuthName=None, basicAuthFile=None)
ServiceRegistry.registerService("basicauth")
AUTH = ServiceRegistry.BASICAUTH


def getAuthorizationFromHeaders(conn, sessionDict):
    """
    pulls REMOTE_USER, REMOTE_PASSWORD, and AUTH_TYPE out of request headers.
    """
    DEBUG(AUTH, "looking for authorization headers")
    auth = conn.requestHeaders.get(
        'Authorization', conn.requestHeaders.get('Proxy-Authorization'))
    if auth:
        DEBUG(AUTH, "found authorization")
        conn.authType, ai = auth.split()
        ucp = base64.decodestring(ai)
Пример #15
0
#  Copyright (C) 2001 Andrew T. Csillag <*****@*****.**>
#  
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
#
########################################################################

from SkunkWeb import Configuration
import MySQL
from SkunkExcept import SkunkStandardError
from requestHandler.requestHandler import CleanupRequest

Configuration.mergeDefaults(
    MySQLConnectParams = {},
    MySQLRollback=0,
    MySQLTestFunc=None
    )

# add test function (used by MySQL connection cache to test
# connections before handing them out)
MySQL.connection_test=Configuration.MySQLTestFunc

for u, p in Configuration.MySQLConnectParams.items():
    MySQL.initUser(u, p)

# optional rollback
def rollback(*args):
    for v in MySQL._connections.values():
        try:
            v.rollback()
Пример #16
0
#

from SkunkWeb import Configuration, ServiceRegistry
from SkunkWeb.LogObj import DEBUG, ERROR, logException
from requestHandler.protocol import PreemptiveResponse
import AE.Cache
import AE.Component
import os
import Authenticator
import sys
import base64
import armor

Configuration.mergeDefaults(
    authAuthorizer=None,
    authActivated=None,
    authAuthorizerCtorArgs=(),
)
ServiceRegistry.registerService("auth")
AUTH = ServiceRegistry.AUTH


class OK(Exception):
    pass


# an authorizer
#class authorizer:
#    def __init__(self, ......):
#    """
#    The ...... will be filled with the contents of
Пример #17
0
will affect all products, or by adding the product-name to the
Configuration.productPaths mapping.

This service will also contain a utility for creating products, creating
the MANIFEST file, byte-compiling the python modules, and creating the
archive file.
"""

import SkunkWeb.Configuration as Cfg
from loader import *
from manifest import *
import os

Cfg.mergeDefaults(productDirectory='products',
                  products='*',
                  defaultProductPath='products',
                  productPaths={},
                  )

proddir=loader.product_directory()
if not os.path.isdir(proddir):
    try:
        os.makedirs(proddir)
    except:
        ERROR(("product service needs a product directory,"
               "currently configured as %s") % proddir)
        raise
del proddir

for p in loader.listProducts():
    p.load()
Пример #18
0
#   

from SkunkWeb import Configuration, ServiceRegistry
from SkunkWeb.LogObj import DEBUG, ERROR, logException
from requestHandler.protocol import PreemptiveResponse
import AE.Cache
import AE.Component
import os
import Authenticator
import sys
import base64
import armor

Configuration.mergeDefaults(
    authAuthorizer = None,
    authActivated = None,
    authAuthorizerCtorArgs = (),
    )
ServiceRegistry.registerService("auth")
AUTH=ServiceRegistry.AUTH

class OK(Exception): pass

# an authorizer 
#class authorizer:
#    def __init__(self, ......):
#    """
#    The ...... will be filled with the contents of
#    Configuration.authAuthorizerCtorArgs when this object is instantiated.
#    """
#
Пример #19
0
########################################################################
#  
#  Copyright (C) 2003 Andrew T. Csillag <*****@*****.**>,
#                     Jacob Smullyan <*****@*****.**>
#  
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
#   
########################################################################

# contributed by Brian Olsen.

from SkunkWeb import Configuration
import Firebird

Configuration.mergeDefaults(
    FirebirdConnectParams = {},
    )

for u, p in Configuration.FirebirdConnectParams.items():
    Firebird.initUser(u, p)

def rollback(*args):
    for v in Firebird._connections.values():
        v.rollback()

from requestHandler.requestHandler import CleanupRequest
CleanupRequest.addFunction(rollback)
Пример #20
0
will affect all products, or by adding the product-name to the
Configuration.productPaths mapping.

This service will also contain a utility for creating products, creating
the MANIFEST file, byte-compiling the python modules, and creating the
archive file.
"""

import SkunkWeb.Configuration as Cfg
from loader import *
from manifest import *
import os

Cfg.mergeDefaults(
    productDirectory='products',
    products='*',
    defaultProductPath='products',
    productPaths={},
)

proddir = loader.product_directory()
if not os.path.isdir(proddir):
    try:
        os.makedirs(proddir)
    except:
        ERROR(("product service needs a product directory,"
               "currently configured as %s") % proddir)
        raise
del proddir

for p in loader.listProducts():
    p.load()
Пример #21
0
# Time-stamp: <01/05/04 17:32:39 smulloni>
########################################################################

from SkunkWeb import Configuration, ServiceRegistry, Hooks
from SkunkWeb.LogObj import DEBUG, DEBUGIT, logException
import os
import select
import sys
import rfc822
import cStringIO

ServiceRegistry.registerService('extcgi')
EXTCGI = ServiceRegistry.EXTCGI

Configuration.mergeDefaults(CGIProgram=None,
                            CGIProgramArgs=(),
                            CGIProgramBase='')


def _fix(dict):  #fixup the environment variables
    nd = {}
    for k, v in dict.items():
        nd[str(k)] = str(v)
    pb = Configuration.CGIProgramBase
    if nd["SCRIPT_NAME"][:len(pb)] == pb:
        remnant = nd["SCRIPT_NAME"][len(pb):]
        if remnant:
            nd["PATH_INFO"] = '/' + remnant
        else:
            nd["PATH_INFO"] = ''
Пример #22
0
class AddressValidationError( MailError ):
    """
    Error if addresses are most likely not deliverable
    """
    def __init__(self, message, bad, good=None):
        MailError.__init__(self, message)
        self.bad = bad
        self.good = good or []
	self.message = message


# Init some variables
Configuration.mergeDefaults(
    MailMethod = 'sendmail',
    MailHost = 'localhost',
    SendmailCommand = '/usr/lib/sendmail',
    FromAddress = "root@localhost",
    QmailInject = "/var/qmail/bin/qmail-inject",
    AddressCheckLevel = 1
    )
# AddressCheckLevel
# 0 - no checks are done
# 1 - simple format check
# 2 - full syntax check (not implemented yet)

valid_charsets = ['iso-8859-1', 'us-ascii']

# shows the mail method: 'sendmail' (default) or 'relay' or 'qmail'
_method = Configuration.MailMethod

# mailhost for relaying SMTP server (default localhost)
_mailhost = Configuration.MailHost
Пример #23
0
# Time-stamp: <01/05/04 17:32:39 smulloni>
########################################################################

from SkunkWeb import Configuration, ServiceRegistry, Hooks
from SkunkWeb.LogObj import DEBUG, DEBUGIT, logException
import os
import select
import sys
import rfc822
import cStringIO

ServiceRegistry.registerService('extcgi')
EXTCGI=ServiceRegistry.EXTCGI

Configuration.mergeDefaults(CGIProgram = None,
                            CGIProgramArgs = (),
                            CGIProgramBase = '')

def _fix(dict): #fixup the environment variables
    nd = {}
    for k,v in dict.items():
        nd[str(k)] = str(v)
    pb = Configuration.CGIProgramBase
    if nd["SCRIPT_NAME"][:len(pb)] == pb:
        remnant = nd["SCRIPT_NAME"][len(pb):]
        if remnant:
            nd["PATH_INFO"] = '/' + remnant
        else:
            nd["PATH_INFO"] = ''
        
        if pb and pb[-1] == '/':
Пример #24
0
#      but WITHOUT ANY WARRANTY; without even the implied warranty of
#      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#      GNU General Public License for more details.
#  
#      You should have received a copy of the GNU General Public License
#      along with this program; if not, write to the Free Software
#      Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
#   
from SkunkWeb import Configuration, LogObj, ServiceRegistry
from requestHandler.requestHandler import CleanupRequest
import Oracle

ServiceRegistry.registerService('oracle')

Configuration.mergeDefaults(
    OracleConnectStrings = {},
    OracleProcedurePackageLists = {}
    )

for u, str in Configuration.OracleConnectStrings.items():
    LogObj.DEBUG(ServiceRegistry.ORACLE, 'initializing user %s' % u)
    Oracle.initUser(u, str)

for u, pkglist in Configuration.OracleProcedurePackageLists:
    Oracle.loadSignatures(u, pkglist, LogObj.LOG,
                       lambda x: LogObj.DEBUG(ServiceRegistry.ORACLE, x))

def rollbackConnection(*args):
    for v in Oracle._connections.values():
        v.rollback()

CleanupRequest.addFunction(rollbackConnection)
Пример #25
0
import SkunkWeb.Configuration as Cfg
from SkunkWeb import Context
from web.protocol import RouteConnection
from SkunkWeb.constants import WEB_JOB

# the controller service is required
import controller

# make sure that the context object is installed
import context

from mvc.log import debug

__all__=['url_for', 'redirect_to']

Cfg.mergeDefaults(routes=[])

def _do_redirect(url):
    Context.Connection.redirect(url)

def routing_hook(connection, sessionDict):
    if not Cfg.MvcOn:
        return
    debug("in routing hook")
    # initialize routes request config
    rcfg=request_config()
    rcfg.redirect=_do_redirect
    rcfg.mapper=map=Mapper()
    rcfg.host=connection.host
    if connection.env.get('HTTPS', False):
        rcfg.protocol='HTTPS'
# Time-stamp: <03/04/15 00:23:55 smulloni>

########################################################################
#  Copyright (C) 2003 Jacob Smullyan <*****@*****.**>
#
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
#
########################################################################

from SkunkWeb import Configuration
import spreadcache

Configuration.mergeDefaults(SpreadConnectParams={})

for alias, params in Configuration.SpreadConnectParams.items():
    spreadcache.initAlias(alias, **params)
Пример #27
0
########################################################################
#  
#  Copyright (C) 2003 Andrew T. Csillag <*****@*****.**>,
#                     Jacob Smullyan <*****@*****.**>
#  
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
#   
########################################################################

# contributed by Brian Olsen.

from SkunkWeb import Configuration
import Firebird

Configuration.mergeDefaults(
    FirebirdConnectParams = {},
    )

for u, p in Configuration.FirebirdConnectParams.items():
    Firebird.initUser(u, p)

def rollback(*args):
    for v in Firebird._connections.values():
        v.rollback()

from requestHandler.requestHandler import CleanupRequest
CleanupRequest.addFunction(rollback)
Пример #28
0
        else:
            self.lbuf = ''
            
def redirectStdOutErr():
    if sys.__stderr__ == sys.stderr and not sys.stderr.isatty():
        sys.stderr = Redirector(Logger.ERROR)
    if sys.__stderr__ == sys.stderr and not sys.stdout.isatty():
        sys.stdout = Redirector(Logger.LOG)

########################################################################        

Configuration.mergeDefaults(
    accessLog =  confvars.DEFAULT_ACCESS_LOG,
    errorLog =   confvars.DEFAULT_ERROR_LOG,
    regularLog = confvars.DEFAULT_REGULAR_LOG,
    debugLog =   confvars.DEFAULT_DEBUG_LOG,
    httpAccessLog = confvars.DEFAULT_HTTP_ACCESS_LOG,
    stampEveryLine = 1,
    logDateFormat = '%a, %d %b %Y %H:%M:%S GMT',
    initialDebugServices=[]
    )

Logger._logStamp = "[%d]initializing... %%s -- " % os.getpid()

# enable the logger to print the service name from the debug flag passed
# to debug statements.
Logger.getSourceFromKind=ServiceRegistry.getSourceFromKind
Logger.config=Configuration        

Hooks.ServerStart.append(Logger.initLogStamp)
Hooks.ServerStart.append(redirectStdOutErr)
Hooks.ChildStart.append(Logger.initLogStamp)
Пример #29
0
import AE.Component
from web.protocol import Redirect
from SkunkWeb.LogObj import DEBUG
from SkunkWeb.ServiceRegistry import TEMPLATING
import SkunkWeb.Configuration as Config

# for img tag, try to import PIL (to get default image width and height)
try:
    import PIL.Image as Image
    import AE.Cache as Cache
    _havePIL = 1
    import pil_preload
except:
    _havePIL = 0

Config.mergeDefaults(tagsGenerateXHTML=1, autosizeImages=1)


def _genUrl(path, query={}, need_full=0, noescape=None):
    """
    Generate the URL given a URI. If need_full is 1, the generated URL 
    will contain the server part.
    """

    if noescape is None:
        path = urllib.quote(path)

    if query:
        path = path + skunklib.urlencode(query)

    if need_full:
Пример #30
0
import time
import types
import browser
from SkunkWeb.Hooks import KeyedHook, Hook
import argextract
import base64
import md5
try:
    import gzip
except:
    pass
import re
rangere = re.compile(r'bytes=([0-9]*)-([0-9]*)$')

Configuration.mergeDefaults(
    textCompression=0,
    generateEtagHeader=1,
    )
headersOnlyMethods=['HEAD'] 
headersOnlyStatuses=[100, 101, 102, 204, 304]

HaveConnection=KeyedHook()
PreHandleConnection=KeyedHook()
RouteConnection=KeyedHook()
HandleConnection=KeyedHook()
ProcessResponse=Hook()

class HTTPConnection:
    '''
    The connection object used for HTTP, passed to various web hooks.
    '''
    def __init__(self, requestData):
Пример #31
0
def __initConnections():
    from protocol import SkunkWebRemoteProtocol

    Configuration.mergeDefaults(RemoteListenPorts=["TCP:localhost:9887"])
    if Configuration.RemoteListenPorts:
        requestHandler.requestHandler.addRequestHandler(SkunkWebRemoteProtocol(), Configuration.RemoteListenPorts)
Пример #32
0
                 from_addr=None,
                 to_addrs=[]):
        self.from_addr=from_addr
        self.to_addrs=to_addrs 

    def out(self, msg, job):
        self.send(msg, 'SkunkWeb Cron Output: %s' % str(job.jobFunc))

    def err(self, msg, job):
        self.send(msg, "SkunkWeb Cron Error: %s" % str(job.jobFunc))

    def send(self, msg,subject):
        to_addrs=self.to_addrs or _C.CronToAddrs
        from_addr=self.from_addr or _C.CronFromAddress or _C.FromAddress
        sendmail(to_addrs,
                 subject,
                 msg,
                 from_addr=from_addr)        

_C.mergeDefaults(CronJobs=[],
                 CronLogger=SkunkMailLogger(),
                 CronFromAddress=None,
                 CronToAddrs=None)


CronTab=cronjob.CronTab(logger=_C.CronLogger,
                        cronjobs=_C.CronJobs)


__all__=['CronTab', 'SkunkMailLogger']
Пример #33
0
def __initFlag():
    from SkunkWeb import ServiceRegistry
    ServiceRegistry.registerService('web', 'WEB')
    import SkunkWeb.Configuration as C
    C.mergeDefaults(mergeQueryStringWithPostData=1,
                    HttpLoggingOn=0)
Пример #34
0
import time
import types
import browser
from SkunkWeb.Hooks import KeyedHook, Hook
import argextract
import base64
import md5
try:
    import gzip
except:
    pass
import re
rangere = re.compile(r'bytes=([0-9]*)-([0-9]*)$')

Configuration.mergeDefaults(
    textCompression=0,
    generateEtagHeader=1,
)
headersOnlyMethods = ['HEAD']
headersOnlyStatuses = [100, 101, 102, 204, 304]

HaveConnection = KeyedHook()
PreHandleConnection = KeyedHook()
HandleConnection = KeyedHook()
ProcessResponse = Hook()


class HTTPConnection:
    '''
    The connection object used for HTTP, passed to various web hooks.
    '''
    def __init__(self, requestData):
Пример #35
0
from SkunkWeb import ServiceRegistry, Configuration, constants
ServiceRegistry.registerService('rewrite')
from SkunkWeb.LogObj import DEBUG, logException
from SkunkWeb.ServiceRegistry import REWRITE
import re
import sys
from requestHandler.protocol import PreemptiveResponse
from skunklib import normpath


def _fixPath(root, path):
    return normpath('%s/%s' % (root, path))


Configuration.mergeDefaults(rewriteBeforeScope=1,
                            rewriteRules=[],
                            rewriteApplyAll=1,
                            rewriteMatchToArgs=1)

_sre_pattern_type = type(re.compile('foo'))

_patdict = {}


def _getcompiled(regex):
    if type(regex) == _sre_pattern_type:
        _patdict.setdefault(regex.pattern, regex)
        return regex
    if not _patdict.has_key(regex):
        pat = re.compile(regex)
        _patdict[regex] = pat
        return pat
Пример #36
0
_config_attrs=tuple([("usertrackingCookie%s" % \
                      x.replace('-', '_').capitalize(), x) \
                     for x in _cookie_attrs])

Configuration.mergeDefaults(
    # whether usertracking is on
    usertrackingOn=0,
    # whether Configuration.usertrackingCookieExpires is an
    # absolute timestamp, or an interval to be added to the
    # current time (the latter is the default)
    usertrackingExpiresAbsolute=0,
    # function to generate unique ids; should take one argument,
    # the CONNECTION.  If None, a uuid will be generated.
    usertrackingGenUIDFunc=None,
    # function to verify a usertracking cookie;
    # by default, None
    usertrackingVerifyCookieFunc=None,
    # name of the cookie
    usertrackingCookieName="SKUNKTREK_ID",
    # values for cookie parameters
    usertrackingCookiePath=None,
    usertrackingCookieExpires=None,
    usertrackingCookieDomain=None,
    usertrackingCookieComment=None,
    usertrackingCookieVersion=None,
    usertrackingCookieMax_age=None)

def _verify_cookie(conn, cookiename):
    if conn.requestCookie.has_key(cookiename):
        v=conn.requestCookie[cookiename]
        f=Configuration.usertrackingVerifyCookieFunc
Пример #37
0
import SkunkWeb.Configuration as C
C.mergeDefaults(MvcOn=False)
Пример #38
0
import _shared
import SkunkWeb.Configuration as Cfg
from web.protocol import PreemptiveResponse, HandleConnection
from templating.Handler import _handleException
from SkunkWeb.constants import WEB_JOB
from SkunkWeb.LogObj import logException
from mvc.log import debug, info
from mvc.utils import is_exposed, _import_a_class
from mvc.base import Response
import types

Cfg.mergeDefaults(controllers={},
                  defaultErrorMimetype='text/html')

def _resolve_string(controllerName):
    try:
        c=_import_a_class(controllerName)
    except ImportError:
        logException()
        return None
    else:
        # do we need to instantiate one?
        # who says this needs to be a instance anyway?
        return c

def controllerHandler(connection, sessionDict):
    if not Cfg.MvcOn:
        return
    cname=sessionDict.get('CONTROLLER')
    data=sessionDict.get('CONTROLLER_ARGS')
    aname=sessionDict.get('ACTION')
Пример #39
0
# Time-stamp: <02/10/30 09:27:03 smulloni>

# default values for Configuration variables go here.
import SkunkWeb.Configuration as C

# whether to disallow "guest" (anonymous) logins
C.mergeDefaults(HoptimeRequireValidUser=0) 

# make certain that the postgresql service is loaded
import postgresql

# initialize the db connection caching mechanism with a connectstring
import hopapi
hopapi.initDB(hopapi.SW_CONNECTSTRING)

# hopapi has a debug method that prints to stderr by default.
# replace it with SkunkWeb's debug method.
import SkunkWeb.ServiceRegistry as _SR
from SkunkWeb.LogObj import DEBUG as _d

def _munge_debug():
    _SR.registerService('hoptime.service', 'HOPTIME')
    HOPTIME=_SR.HOPTIME
    def _debug(message):
        _d(HOPTIME, str(message))
    hopapi.DEBUG=_debug

_munge_debug()
Пример #40
0
#
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
#
# $Id: __init__.py,v 1.5 2004/03/01 16:27:04 smulloni Exp $
# Time-stamp: <01/05/04 13:27:45 smulloni>
########################################################################

import SkunkWeb.ServiceRegistry
SkunkWeb.ServiceRegistry.registerService("httpd")

from SkunkWeb import Configuration, Hooks
from socket import getfqdn as _getfqdn
Configuration.mergeDefaults(lookupHTTPRemoteHost=0,
                            HTTPKeepAliveTimeout=0,
                            HTTPListenPorts=['TCP::8080'],
                            ServerName=_getfqdn())


class _hooker:
    def __init__(self, handler, adder, ports):
        self.adder = adder
        self.handler = handler
        self.ports = ports

    def __call__(self, *a, **kw):
        self.adder(self.handler, self.ports)


if Configuration.HTTPListenPorts:
    import requestHandler.requestHandler as rh
Пример #41
0
def __initConnections():
    from protocol import SkunkWebRemoteProtocol
    Configuration.mergeDefaults(RemoteListenPorts=['TCP:localhost:9887'])
    if Configuration.RemoteListenPorts:
        requestHandler.requestHandler.addRequestHandler(
            SkunkWebRemoteProtocol(), Configuration.RemoteListenPorts)
Пример #42
0
import os
import datetime
import computils
from AE.Component import DT_INCLUDE
import SkunkWeb.Configuration as C

C.mergeDefaults(skinDir='/comp/skins',
                defaultSkin='default')

import threading
_local=threading.local()
_local.SLOTSTACK=[]

def getCurrentSlot():
    if _local.SLOTSTACK:
        return _local.SLOTSTACK[-1]

def push_slot(slot):
    _local.SLOTSTACK.append(slot)

def pop_slot():
    if _local.SLOTSTACK:
        _local.SLOTSTACK.pop()

class Slot(object):
    def __init__(self, name):
        self.name=name

class ComponentSlot(Slot):
    def __init__(self, name, compname, comptype=None, cache=computils.NO, **kw):
        Slot.__init__(self, name)
Пример #43
0
    def marshalException(self, exc_text, sessionDict):
        '''
        should return response data appropriate for the current exception.
        '''
        res = RequestFailed(Configuration.job, exc_text, sessionDict)
        if res:
            return self._marshalData(res)
        else:
            return self._marshalData(exc_text)

    def _marshalData(self, data):
        return data


Configuration.mergeDefaults(SCGIListenPorts=['TCP:localhost:9999'])
if Configuration.SCGIListenPorts:
    requestHandler.requestHandler.addRequestHandler(
        SCGIProtocol(), Configuration.SCGIListenPorts)

########################################################################
# $Log: scgi.py,v $
# Revision 1.3  2003/05/01 20:45:53  drew_csillag
# Changed license text
#
# Revision 1.2  2002/06/18 20:09:38  drew_csillag
# fixed typo that caused problems on POSTs
#
# Revision 1.1  2002/06/17 19:29:52  drew_csillag
# added
#
Пример #44
0
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
#   
# $Id$
# Time-stamp: <01/05/04 13:27:45 smulloni>
########################################################################

import SkunkWeb.ServiceRegistry
SkunkWeb.ServiceRegistry.registerService("httpd")


from SkunkWeb import Configuration, Hooks
from socket import getfqdn as _getfqdn
Configuration.mergeDefaults(lookupHTTPRemoteHost=0,
                            HTTPKeepAliveTimeout=0,
                            HTTPListenPorts=['TCP::8080'],
                            ServerName=_getfqdn())

class _hooker:
    def __init__(self, handler, adder, ports):
        self.adder=adder
        self.handler=handler
        self.ports=ports

    def __call__(self, *a, **kw):
        self.adder(self.handler, self.ports)
    
if Configuration.HTTPListenPorts:
    import requestHandler.requestHandler as rh
    import protocol as prot
    httpProt=prot.HTTPProtocol()
Пример #45
0
import AE.Component
from web.protocol import Redirect
from SkunkWeb.LogObj import DEBUG
from SkunkWeb.ServiceRegistry import TEMPLATING
import SkunkWeb.Configuration as Config

# for img tag, try to import PIL (to get default image width and height)
try:
    import PIL.Image as Image
    import AE.Cache as Cache
    _havePIL=1
    import pil_preload
except:
    _havePIL=0

Config.mergeDefaults(tagsGenerateXHTML=1,
                     autosizeImages=1)
                     

def _genUrl ( path, query = {}, need_full = 0, noescape=None ):
    """
    Generate the URL given a URI. If need_full is 1, the generated URL 
    will contain the server part.
    """

    if noescape is None:
	path = urllib.quote(path)

    if query:
        path = path + skunklib.urlencode ( query )

    if need_full:
Пример #46
0
for the component cache.

To turn this on, define memcacheCacheBackend to be a list of ip
address of memcache servers.  If it is None, this will fall back to
the usual skunk cache.

"""
import cPickle

import memcache

import AE.Cache
from Logger import logException, ERROR
import SkunkWeb.Configuration as C

C.mergeDefaults(memcacheCacheBackend=None,
                memcachePathPrefix='component_')

_clients={}
def _get_memcache_client():
    global _clients
    servers=C.memcacheCacheBackend
    if not servers:
        return None
    servers.sort()
    servers=tuple(servers)
    try:
        return _clients[servers]
    except KeyError:
        client=memcache.Client(servers, False)
        _clients[servers]=client
        return client
Пример #47
0
class AddressValidationError( MailError ):
    """
    Error if addresses are most likely not deliverable
    """
    def __init__(self, message, bad, good=None):
        MailError.__init__(self, message)
        self.bad = bad
        self.good = good or []
	self.message = message


# Init some variables
Configuration.mergeDefaults(
    MailMethod = 'sendmail',
    MailHost = 'localhost',
    SendmailCommand = '/usr/lib/sendmail',
    FromAddress = "root@localhost",
    QmailInject = "/var/qmail/bin/qmail-inject",
    AddressCheckLevel = 1
    )
# AddressCheckLevel
# 0 - no checks are done
# 1 - simple format check
# 2 - full syntax check (not implemented yet)

valid_charsets = ['iso-8859-1', 'us-ascii']

# shows the mail method: 'sendmail' (default) or 'relay' or 'qmail'
_method = Configuration.MailMethod

# mailhost for relaying SMTP server (default localhost)
_mailhost = Configuration.MailHost
Пример #48
0
            self.lbuf = ''


def redirectStdOutErr():
    if not sys.stderr.isatty():
        sys.stderr = Redirector(Logger.ERROR)
    if not sys.stdout.isatty():
        sys.stdout = Redirector(Logger.LOG)


########################################################################

Configuration.mergeDefaults(accessLog=confvars.DEFAULT_ACCESS_LOG,
                            errorLog=confvars.DEFAULT_ERROR_LOG,
                            regularLog=confvars.DEFAULT_REGULAR_LOG,
                            debugLog=confvars.DEFAULT_DEBUG_LOG,
                            stampEveryLine=1,
                            logDateFormat='%a, %d %b %Y %H:%M:%S GMT',
                            initialDebugServices=[])

Logger._logStamp = "[%d]initializing... %%s -- " % os.getpid()

# enable the logger to print the service name from the debug flag passed
# to debug statements.
Logger.getSourceFromKind = ServiceRegistry.getSourceFromKind
Logger.config = Configuration

Hooks.ServerStart.append(Logger.initLogStamp)
Hooks.ServerStart.append(redirectStdOutErr)
Hooks.ChildStart.append(Logger.initLogStamp)
Пример #49
0
########################################################################
#  Copyright (C) 2001 Andrew T. Csillag <*****@*****.**>
#
#      You may distribute under the terms of either the GNU General
#      Public License or the SkunkWeb License, as specified in the
#      README file.
#
########################################################################

from SkunkWeb import Configuration
import MySQL
from SkunkExcept import SkunkStandardError
from requestHandler.requestHandler import CleanupRequest

Configuration.mergeDefaults(MySQLConnectParams={},
                            MySQLRollback=0,
                            MySQLTestFunc=None)

# add test function (used by MySQL connection cache to test
# connections before handing them out)
MySQL.connection_test = Configuration.MySQLTestFunc

for u, p in Configuration.MySQLConnectParams.items():
    MySQL.initUser(u, p)


# optional rollback
def rollback(*args):
    for v in MySQL._connections.values():
        try:
            v.rollback()
Пример #50
0
    def marshalException(self, exc_text, sessionDict):
        '''
        should return response data appropriate for the current exception.
        '''
        res=RequestFailed(Configuration.job,
                          exc_text,
                          sessionDict)
        if res:
            return self._marshalData(res)
        else:
            return self._marshalData(exc_text)

    def _marshalData(self, data):
        return data

Configuration.mergeDefaults(SCGIListenPorts=['TCP:localhost:9999'])
if Configuration.SCGIListenPorts:
    requestHandler.requestHandler.addRequestHandler(
        SCGIProtocol(), Configuration.SCGIListenPorts)

########################################################################
# $Log: scgi.py,v $
# Revision 1.3  2003/05/01 20:45:53  drew_csillag
# Changed license text
#
# Revision 1.2  2002/06/18 20:09:38  drew_csillag
# fixed typo that caused problems on POSTs
#
# Revision 1.1  2002/06/17 19:29:52  drew_csillag
# added
#
Пример #51
0
import AE.Error
import AE.Executables
from SkunkWeb import Configuration
import stat
import sys
from SkunkWeb.LogObj import ACCESS, ERROR, DEBUG
from web.protocol import Redirect
from SkunkWeb.ServiceRegistry import TEMPLATING
import vfs
from skunk.date.format import HTTPDate

Configuration.mergeDefaults(
    indexDocuments=['index.html'],
    hideMimeTypes=[
        "text/x-stml-component", "text/x-stml-python-component",
        "text/x-stml-data-component", "text/x-stml-python-data-component",
        "text/x-stml-include", "text/x-stml-python-include"
    ],
    interpretMimeTypes=["text/html", "application/x-python"],
    defaultIndexHtml=None,
    mimeHandlers={})


def _handleException(connObj):
    text = AE.Error.logException()
    ERROR(text)
    import cStringIO
    connObj.setStatus(500)
    if (hasattr(Configuration, 'errorTemplate')
            and Configuration.errorTemplate):
        connObj.write(
            AE.Component.callComponent(Configuration.errorTemplate, {
Пример #52
0
# Time-stamp: <02/10/30 09:27:03 smulloni>
# $Id: service.py,v 1.2 2002/11/01 17:54:17 smulloni Exp $

# default values for Configuration variables go here.
import SkunkWeb.Configuration as C

# whether to disallow "guest" (anonymous) logins
C.mergeDefaults(HoptimeRequireValidUser=0) 

# make certain that the postgresql service is loaded
import postgresql

# initialize the db connection caching mechanism with a connectstring
import hopapi
hopapi.initDB(hopapi.SW_CONNECTSTRING)

# hopapi has a debug method that prints to stderr by default.
# replace it with SkunkWeb's debug method.
import SkunkWeb.ServiceRegistry as _SR
from SkunkWeb.LogObj import DEBUG as _d

def _munge_debug():
    _SR.registerService('hoptime.service', 'HOPTIME')
    HOPTIME=_SR.HOPTIME
    def _debug(message):
        _d(HOPTIME, str(message))
    hopapi.DEBUG=_debug

_munge_debug()
Пример #53
0
def __initConfig():
    from SkunkWeb import Configuration
    Configuration.mergeDefaults(DocumentTimeout=30,
                                PostResponseTimeout=20,
                                job=None)
Пример #54
0
import SkunkWeb.Configuration as Cfg
from SkunkWeb import Context
from web.protocol import RouteConnection
from SkunkWeb.constants import WEB_JOB

# the controller service is required
import controller

# make sure that the context object is installed
import context

from mvc.log import debug

__all__ = ['url_for', 'redirect_to']

Cfg.mergeDefaults(routes=[])


def _do_redirect(url):
    Context.Connection.redirect(url)


def routing_hook(connection, sessionDict):
    if not Cfg.MvcOn:
        return
    debug("in routing hook")
    # initialize routes request config
    rcfg = request_config()
    rcfg.redirect = _do_redirect
    rcfg.mapper = map = Mapper()
    rcfg.host = connection.host
Пример #55
0
        res = RequestFailed(Configuration.job, exc_text, sessionDict)
        if res:
            return self._marshalData(res)
        else:
            return self._marshalData(exc_text)

    def _marshalData(self, data):
        return "%10d%s" % (len(data), data)


def _serverStartHook(*args, **kw):
    requestHandler.requestHandler.addRequestHandler(
        AecgiProtocol(), Configuration.AecgiListenPorts)


Configuration.mergeDefaults(AecgiListenPorts=['TCP:localhost:9888'])
if Configuration.AecgiListenPorts:
    Hooks.ServerStart.append(_serverStartHook)

########################################################################
# $Log: aecgi.py,v $
# Revision 1.4  2003/05/01 20:45:53  drew_csillag
# Changed license text
#
# Revision 1.3  2002/07/19 16:21:02  smulloni
# removed spurious dependencies on aecgi from httpd and templating by
# moving the RequestFailed hook into requestHandler.
#
# Revision 1.2  2002/05/24 20:56:20  smulloni
# now add request handlers in ServerStart hook
#
Пример #56
0
import stat
import sys
from SkunkWeb.LogObj import ACCESS, ERROR, DEBUG
from web.protocol import Redirect
from SkunkWeb.ServiceRegistry import TEMPLATING
import vfs
import Date

Configuration.mergeDefaults(
    indexDocuments = ['index.html'],
    hideMimeTypes = [
        "text/x-stml-component",
        "text/x-stml-python-component",
        "text/x-stml-data-component",
        "text/x-stml-python-data-component",
        ],
    interpretMimeTypes = [
        "text/html",
        "application/x-python"
        ],
    defaultIndexHtml = None,
    mimeHandlers = {}
    )

def _handleException(connObj):
    text = AE.Error.logException()
    ERROR(text)
    import cStringIO
    connObj.setStatus(500)
    if (hasattr(Configuration, 'errorTemplate') and
        Configuration.errorTemplate):