Ejemplo n.º 1
0
    def __init__(self, name, app_root=None, ini=None):
        try:
            with Timer() as elapsed:
                # Set current app as global
                g.app = self

                # Attempt to determine application root.
                g.app_root = self.app_root = app_root = determine_app_root(
                    name, app_root)

                # Set Application Name
                self.name = name

                # Load Configuration
                if ini is None:
                    g.config = self.config = load_config(self.app_root +
                                                         '/settings.ini')
                else:
                    g.config = self.config = load_config(ini)

                # Configure Logger.
                GetLogger().app_configure()

                # Started Application
                log.info('Started Application'
                         ' %s' % name + ' app_root: %s' % app_root,
                         timer=elapsed())

        except Exception:
            trace = str(traceback.format_exc())
            log.critical("%s" % trace)
            raise
Ejemplo n.º 2
0
import hashlib
import traceback
import pickle
from time import time

from decorator import decorator

from luxon import g
from luxon.core.logger import GetLogger
from luxon.structs.models.fields import BaseField
from luxon.helpers.redis import strict
from luxon.utils.encoding import if_unicode_to_bytes
from luxon.exceptions import NoContextError
from luxon.utils.objects import object_name

log = GetLogger(__name__)


class Cache(object):
    def __init__(self):
        try:
            redis = g.config.get('redis', 'host', fallback=None)
            if redis is not None:
                self.redis = strict()
            else:
                self.redis = None
        except NoContextError:
            self.redis = None

    def store(self, reference, obj, expire):
        if self.redis is not None:
Ejemplo n.º 3
0
    def __call__(self):
        """Application Request Interface.

        A clean request and response object is provided to the interface that
        is unique this to this thread.

        It passes any args and kwargs to the interface.

        Response object is returned.
        """
        parser = argparse.ArgumentParser(description=g.app.name)
        action = parser.add_mutually_exclusive_group()
        action.add_argument('-f',
                            '--fork',
                            action='store_true',
                            help='Fork Process')
        action.add_argument('-k',
                            '--kill',
                            action='store_true',
                            help='Stop/Kill Process')
        action.add_argument('-r',
                            '--restart',
                            action='store_true',
                            help='Restart Process')
        action.add_argument('-d', '--debug', action='store_true', help='Debug')
        parser.add_argument('-a',
                            '--app',
                            dest='app',
                            default=None,
                            help='Application Path')
        parser.add_argument('-p',
                            '--pid',
                            dest='pid',
                            default=None,
                            help='PID File')
        subparsers = parser.add_subparsers(dest='method', help='Methods')
        subparsers.required = True

        methods = router.methods
        for m in methods:
            m = m.lower()
            sub = subparsers.add_parser(m, help='%s resources' % m)
            sub.set_defaults(method=m.upper())
            sub.add_argument('route',
                             nargs='?',
                             default=None,
                             help='Resource Route')

        args = parser.parse_args()

        if hasattr(args, 'route') and isinstance(args.route, str):
            args.route = args.route.strip('/')
        if args.method is not None:
            args.method = args.method.lower()

        if hasattr(args, 'route') and args.route is None:
            parser.print_help()
            print('\nroutes for %s:' % args.method)
            index = router.routes
            for route in index:
                if route[1] == args.method.upper():
                    print("\t/%s" % route[0])
            exit()

        pid_file = g.app.name.replace(' ', '_').lower()
        pid_file += '_' + args.method.lower() + '_'
        pid_file += args.route.replace('/', '_').lower()
        pid_file += '.pid'

        if args.app:
            g.app._path = os.path.abspath(args.app)
            App(g.app.name, path=args.app)
            pid_file = g.app.path + '/tmp/' + pid_file

        if args.pid:
            pid_file = args.pid

        if not args.app and not args.pid:
            pid_file = g.app.path + '/' + pid_file

        if args.debug:
            GetLogger().level = 'DEBUG'

        if self._middleware:
            if isinstance(self._middleware, (
                    tuple,
                    list,
            )):
                for func in self._middleware:
                    func()
            else:
                self._middleware()

        fork = Daemon(pid_file,
                      run=self.proc,
                      args=(
                          args.method,
                          args.route,
                      ))
        if args.fork:
            fork.start()
        elif args.kill is True:
            fork.stop()
            exit()
        elif args.restart is True:
            fork.restart()
            exit()
        else:
            fork.start(fork=False)
Ejemplo n.º 4
0
from luxon.core.globals import Globals
from luxon.core.config import Config
from luxon.core.request import RequestBase
from luxon.core.response import ResponseBase
from luxon.exceptions import (
    Error,
    NotFound,
    HTTPError,
    AccessDenied,
    NoContextError,
)
from luxon.utils import imports
from luxon.utils.timer import Timer
from luxon.utils.objects import object_name

log = GetLogger()


def determine_app_root(name, app_root=None):
    if app_root is None:
        if name == "__main__" or "_mod_wsgi" in name:
            app_mod = imports.import_module(name)
            return os.path.abspath( \
                os.path.dirname( \
                    app_mod.__file__)).rstrip('/')
        else:
            log.error("Unable to determine application root." +
                      " Using current working directory '%s'" % os.getcwd())
            return os.getcwd().rstrip('/')
    else:
        if os.path.exists(app_root) and not os.path.isfile(app_root):