Commit 232c2ae6 authored by Gero Müller's avatar Gero Müller
Browse files

add wsgi support

parent 5dcf7299
......@@ -94,7 +94,7 @@ def parse_commandline():
def run():
args = parse_commandline()
server = Server(args)
server = Server(**vars(args))
browser = Browser()
server.start()
......
......@@ -238,5 +238,5 @@ if __name__ == "__main__":
print "Unknown action!"
sys.exit(2)
else:
Server(args).run()
Server(**vars(args)).run()
sys.exit(0)
# -*- coding: utf-8 -*-
# imports
import vispa
from vispa.models.workspace import Workspace
import cherrypy
import uuid
import inspect
import json
import logging
import os
import inspect
import uuid
from vispa.models.workspace import Workspace
import cherrypy
import vispa
logger = logging.getLogger(__name__)
def strongly_expire(func):
......@@ -49,10 +53,11 @@ class AbstractController(object):
def mount_static(self, path=None, url='static'):
if path and not os.path.isabs(path):
os.path.join(os.path.dirname(inspect.getabsfile(self.__class__)), path)
path = os.path.join(os.path.dirname(inspect.getabsfile(self.__class__)), path)
elif not path:
path = os.path.join(os.path.dirname(inspect.getabsfile(self.__class__)), 'static')
logger.info("Mount static controller. path: %s, url: %s" % (path, url))
setattr(self, url, StaticController(path))
# a little helper
......
......@@ -19,7 +19,7 @@ logger = logging.getLogger(__name__)
class AjaxController(AbstractController):
def __init__(self, root):
AbstractController.__init__(self)
AbstractController.__init__(self, mount_static=False)
self._root = root
self.fs = FSAjaxController()
......
......@@ -5,13 +5,17 @@ import cherrypy
import vispa
from vispa.controller import AbstractController
from vispa.socketbus import SocketPublisher, PollingPublisher, add_session, \
USE_SOCKETS, SUBSCRIBERS, POLLING_TIMESTAMPS
USE_SOCKETS, SUBSCRIBERS, POLLING_TIMESTAMPS
from vispa import MessageException
from time import time
import json
class BusController(AbstractController):
def __init__(self):
AbstractController.__init__(self, mount_static=False)
@cherrypy.expose
def index(self, *args, **kwargs):
pass
......
......@@ -12,6 +12,9 @@ import cherrypy
class FSController(AbstractController):
def __init__(self):
AbstractController.__init__(self, mount_static=False)
@cherrypy.expose
@cherrypy.tools.ajax(on=False)
def getfile(self, path, download=None, **kwargs):
......
# -*- coding: utf-8 -*-
# imports
import vispa
import StringIO
import inspect
import logging
import os
from vispa.controller import AbstractController, strongly_expire
from vispa.controller.ajax import AjaxController
from vispa.controller.filesystem import FSController
from vispa.controller.bus import BusController
from vispa.controller.error import ErrorController
from vispa.controller.filesystem import FSController
from vispa.models.preference import VispaPreference, ExtensionPreference
from vispa.models.user import User
from vispa.models.workspace import Workspace
from vispa.models.preference import VispaPreference, ExtensionPreference
from vispa.models.shortcuts import VispaShortcuts, ExtensionShortcuts
import cherrypy
import logging
import os
import json as JSON
import StringIO
import vispa
from vispa.models.shortcuts import VispaShortcuts, ExtensionShortcuts
import json as JSON
logger = logging.getLogger(__name__)
......@@ -26,11 +28,11 @@ class RootController(AbstractController):
The Constructor. Members from other classes
are added as pages for cherrypy URL mapping.
"""
AbstractController.__init__(self)
AbstractController.__init__(self, mount_static=False)
self.mount_static(os.path.join(os.path.dirname(inspect.getabsfile(vispa)), 'static'))
self.ajax = AjaxController(self)
self.fs = FSController()
self.extensions = AbstractController()
self.extensions = AbstractController(mount_static=False)
self.bus = BusController()
if not vispa.config("web", "dev_mode", True):
self.error = ErrorController()
......
......@@ -85,9 +85,9 @@ class User(Base):
@staticmethod
def login(session, username, password):
if username == None:
if username is None:
raise MessageException('Invalid username')
if password == None:
if password is None:
raise MessageException('Invalid password')
user = User.get_by_name(session, username)
......
......@@ -24,8 +24,8 @@ from vispa.models.shortcuts import *
logger = logging.getLogger(__name__)
class AbstractExtension(object):
""" Base class for Extensions """
def __init__(self, server):
......@@ -112,7 +112,6 @@ class AbstractExtension(object):
class Server(object):
__default_server_config = {
'tools.proxy.on': False,
'server.socket_host': '127.0.0.1',
'server.socket_port': 4282,
'server.thread_pool': 10,
......@@ -124,6 +123,7 @@ class Server(object):
base_static = vispa.url.static('/', timestamp=False)
return {
'/': {
'tools.proxy.on': False,
'tools.encode.on': False,
'tools.db.on': True,
'tools.private_parameters.on': True,
......@@ -134,10 +134,11 @@ class Server(object):
'tools.sessions.storage_type': 'file',
'tools.sessions.storage_path': vispa.datapath('sessions'),
'tools.sessions.timeout': 1440,
'tools.staticdir.root': vispa.codepath('vispa', 'static'),
'tools.staticdir.on': False,
'tools.gzip.on': True,
'tools.gzip.mime_types': ['text/html', 'text/css',
'application/x-javascript', 'application/json'],
'application/x-javascript',
'application/json'],
'tools.render.common_data': {
'base_dynamic': base_dynamic,
'base_static': base_static
......@@ -154,30 +155,19 @@ class Server(object):
'/ajax/fs': {
'tools.workspace.on': True
},
'/static': {
'tools.db.on': False,
'tools.user.on': False,
'tools.workspace.on': False,
'tools.etags.on': True,
'tools.staticdir.on': True,
'tools.staticdir.dir': '',
'tools.sessions.on': False,
'tools.expires.on': True,
'tools.expires.secs': 3600 * 24 * 365,
}
}
def __init__(self, args):
self.__init_paths(args)
self.__init_logging(args)
self.__init_database(args)
self.__init_tools(args)
self.__init_platform(args)
self.__init_plugins(args)
def __init__(self, **kwargs):
self.__init_paths(**kwargs)
self.__init_logging(**kwargs)
self.__init_database(**kwargs)
self.__init_tools(**kwargs)
self.__init_platform(**kwargs)
self.__init_plugins(**kwargs)
def __init_paths(self, args):
def __init_paths(self, **kwargs):
# dir for variable files and folders
self.var_dir = os.path.abspath(args.vardir)
self.var_dir = os.path.abspath(kwargs.get('vardir', ''))
if not os.path.exists(self.var_dir):
os.makedirs(self.var_dir)
......@@ -205,27 +195,28 @@ class Server(object):
os.mkdir(self.cache_dir)
# conf dir
self.conf_dir = os.path.abspath(args.configdir)
self.conf_dir = os.path.abspath(kwargs.get('configdir', ''))
logger.info('Using %s as config dir.' % self.conf_dir)
vispa.set_configpath(self.conf_dir)
vispa.config.read(vispa.configpath('vispa.ini'))
def __init_logging(self, args):
def __init_logging(self, **kwargs):
# setup the logging
logging_conf = os.path.join(self.conf_dir, 'logging.ini')
logformat = '%(asctime)s - %(levelname)-6s - %(name)-s - %(message)s'
datefmt = '%Y-%m-%d %H:%M'
loglevel = kwargs.get('loglevel', '')
if os.path.isfile(logging_conf):
loggingcfg.fileConfig(logging_conf,
defaults={"log_dir": self.log_dir})
elif args.loglevel == "info":
elif loglevel == "info":
logging.basicConfig(level=logging.INFO,
format=logformat,
datefmt=datefmt)
cherrypy.log.screen = False
cherrypy.log.access_file = os.path.join(self.log_dir, "access.log")
elif args.loglevel == "debug":
elif loglevel == "debug":
logging.basicConfig(level=logging.DEBUG,
format=logformat,
datefmt=datefmt)
......@@ -236,13 +227,14 @@ class Server(object):
cherrypy.log.access_file = os.path.join(self.log_dir, "access.log")
cherrypy.log.screen = False
def __init_database(self, args):
def __init_database(self, **kwargs):
sa_identifier = vispa.config('database', 'sqlalchemy.url',
'sqlite:///%s/vispa.db' % self.var_dir)
logger.info('Use database %s.' % sa_identifier)
self._engine = sqlalchemy.create_engine(sa_identifier, echo=False)
if vispa.config('alembic', 'use_alembic', not sa_identifier.startswith('sqlite')):
if vispa.config('alembic', 'use_alembic',
not sa_identifier.startswith('sqlite')):
logger.info("Use alembic")
if vispa.config('alembic', 'auto_migrate', True):
vispa.models.alembic.migrate(self._engine)
......@@ -250,7 +242,7 @@ class Server(object):
logger.info("Do not use alembic")
sql_base.metadata.create_all(self._engine)
def __init_plugins(self, args):
def __init_plugins(self, **kwargs):
if vispa.config('websockets', 'enabled', False):
from ws4py.server.cherrypyserver import WebSocketPlugin
WebSocketPlugin(cherrypy.engine).subscribe()
......@@ -261,9 +253,9 @@ class Server(object):
vispa.plugins.template.MakoPlugin(cherrypy.engine,
base_dir=mako_lookup_dir,
module_dir=self.cache_dir
).subscribe()
).subscribe()
def __init_tools(self, args):
def __init_tools(self, **kwargs):
from vispa.tools.template import MakoTool
cherrypy.tools.render = MakoTool()
......@@ -300,24 +292,25 @@ class Server(object):
except:
pass
def __init_platform(self, args):
def __init_platform(self, **kwargs):
cherrypy.config.update(self.__default_server_config)
cherrypy_conf = vispa.configpath('cherrypy.ini')
if os.path.isfile(cherrypy_conf):
cherrypy.config.update(cherrypy_conf)
if args.port:
cherrypy.config.update({'server.socket_port': int(args.port)})
port = kwargs.get('port', None)
if port:
cherrypy.config.update({'server.socket_port': int(port)})
from vispa.controller.root import RootController
self.controller = RootController()
self._load_extensions()
script_name = vispa.url.dynamic('/', encoding='utf-8')
app = cherrypy.tree.mount(self.controller, script_name,
self.__default_mount_config())
self.__application = cherrypy.tree.mount(self.controller, script_name,
self.__default_mount_config())
if os.path.isfile(cherrypy_conf):
app.merge(cherrypy_conf)
self.__application.merge(cherrypy_conf)
def start(self):
if hasattr(cherrypy.engine, 'signal_handler'):
......@@ -424,7 +417,9 @@ class Server(object):
try:
extension.setup()
except:
logger.warn("Extension '%s' failed to setup!" % extension.name())
logger.warn(
"Extension '%s' failed to setup!" %
extension.name())
vispa.log_exception()
def extension(self, name):
......@@ -432,3 +427,6 @@ class Server(object):
def extensions(self):
return self._extensions.values()
def application(self):
return self.__application
......@@ -98,7 +98,7 @@ def directory_files(local, remote, **kwargs):
def add_directory_files(local, remote, **kwargs):
files = directory_files(local, remote)
_remote_files.extend(files)
logger.info(_remote_files)
logger.debug(_remote_files)
def package_files(pkg, target_path, **kwargs):
......
import logging
import os
import cherrypy
logger = logging.getLogger(__name__)
vispa_server = None
def application(environ, start_response):
global vispa_server
if vispa_server is None:
configdir = os.environ.get(
'VISPA_CONFIG_PATH',
'/etc/vispa')
configdir = environ.get(
'VISPA_CONFIG_PATH',
configdir)
datadir = os.environ.get(
'VISPA_DATA_PATH',
'/var/lib/vispa')
datadir = environ.get(
'VISPA_DATA_PATH',
datadir)
loglevel = os.environ.get(
'VISPA_LOG_LEVEL',
None)
loglevel = environ.get(
'VISPA_LOG_LEVEL',
loglevel)
from vispa import server
vispa_server = server.Server(
configdir=configdir,
datadir=datadir,
loglevel=loglevel)
vispa_server.start()
logger.info("server startet.")
return cherrypy.tree(environ, start_response)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment