Exemple #1
0
    def prepare(self, context):
        """ Setup basic stuff needed for all pages """

        context.__dict__['whatsnewdays'] = self.whatsnewdays
        context.__dict__['lastplay_count'] = self.lastplay_count
        try:
            djrow = context.db.lastplay.query(DJs).filter(
                DJs.dj == context.djname).one()
        except NoResultFound:
            raise HTTPNotFound('Host Not Found')

        context.__dict__['djname'] = djrow.dj

        package = 'web.app.djrq.model.' + djrow.databasetype

        context.__dict__['databasetype'] = djrow.databasetype
        context.__dict__['queries'] = load(package + '.queries:Queries')(
            db=context.db.default)
        Listeners = load(package + '.listeners:Listeners')
        context.__dict__['Users'] = load(package + '.users:Users')

        try:
            album = load(package + '.album:Album', default='Album')
        except ImportError:
            album = 'Album'
        try:
            artist = load(package + '.artist:Artist', default='Artist')
        except ImportError:
            artist = 'Artist'

        context.__dict__['artist'] = artist
        context.__dict__['album'] = album
        context.__dict__['requestlist'] = load(package +
                                               '.requestlist:RequestList')
        context.__dict__['mistags'] = load(package + '.mistags:Mistags')
        context.__dict__['suggestions'] = load(package +
                                               '.suggestions:Suggestions')
        if context.queries.db is None:
            raise HTTPError("Queries is None!")
        context.__dict__['dbstats'] = context.queries.get_song_stats()
        context.__dict__['requests_info'] = context.queries.get_requests_info()
        context.__dict__['new_counts'] = context.queries.get_new_counts(
            days=context.whatsnewdays)

        try:
            context.__dict__['listeners'] = context.db.default.query(
                Listeners).one()
        except NoResultFound:
            context.__dict__['listeners'] = None
        context.__dict__['alldjs'] = context.db.lastplay.query(DJs).filter(
            DJs.hide_from_menu == 0).order_by(DJs.dj)
        context.siteoptions = context.queries.get_siteoptions()
        context.suggestions_count = context.queries.get_suggestions_count(
        ).suggestions_count
        context.mistags_count = context.queries.get_mistags_count(
        ).mistags_count
Exemple #2
0
def ringleader(queue, keys):
    keystore = dict(keys)

    while True:
        message = queue.recv()

        if not isinstance(message, tuple):
            continue

        if len(message) < 2:
            continue

        sequence, operation = message[:2]
        message = message[2:]

        if operation not in ('quit', 'register', 'sign', 'verify'):
            continue

        if operation == 'quit':
            break

        if operation == 'register':
            name, value = message
            keystore[name] = value
            continue

        if operation == 'unregister':
            keystore.pop(message[0])
            continue

        if operation == 'sign':
            name, algorithm, value = message
        elif operation == 'verify':
            name, algorithm, value, signature = message

        key = keystore.get(name, name if len(name) >= 32 else None)
        algorithm = load(
            algorithm,
            'pep-247')  # Load the PEP 247-compatible keyed hashing algorithm.

        # Will usually be hmac:HMAC, can also be something like web.security.fastecdsa:P256.

        signer = algorithm(key, value)
        result = signer.digest()

        if operation == 'sign':
            queue.send((sequence, result))
            continue

        if hasattr(signer, 'verify'):
            result = signer.verify(value, signature)
            queue.send((sequence, result))
            continue

        result = compare_digest(signature, result)
        queue.send((sequence, result))

    queue.close()
	def __html_stream__(self):
		target = self.target
		handler, _, cls = target.handler.rpartition(':')
		cls = cls.partition('.')[0]
		# print(target.handler, handler, cls, handler + ':' + cls, self.handler)
		controller = load(handler + ':' + cls)(None, target)
		result = getattr(controller, self.handler)()
		
		return render_reference_block(self, result)
Exemple #4
0
    def start(self, context):
        """Called to load the authentication callbacks and attach them to the context, with glue."""

        if isinstance(self._lookup, (str, unicode)):
            self._lookup = load(self._lookup, 'web.auth.lookup')

        if isinstance(self._authenticate, (str, unicode)):
            self._authenticate = load(self._authenticate,
                                      'web.auth.authenticate')

        if self._name:
            context[self._name] = None

        # TODO: context.user = lazy(...)
        context.authenticate = lazy(
            partialmethod(partialmethod, self.authenticate), 'authenticate')
        context.deauthenticate = lazy(
            partialmethod(partialmethod, self.deauthenticate),
            'deauthenticate')
Exemple #5
0
	def __init__(self, engine, uri, safe=True, protect=True, alias=None, **kw):
		"""Prepare configuration options."""
		
		self.engine = engine
		self.uri = uri
		self.safe = safe  # Thread safe? When False, create a connection for the duration of a request only.
		self.protect = protect
		self.alias = alias
		self.config = kw
		
		self._connector = load(engine, 'db_api_connect')
		
		if self.safe:  # pragma: no cover
			self.start = self._connect
			self.stop = self._disconnect
		else:
			self.prepare = self._connect
			self.done = self._disconnect
Exemple #6
0
    def serve(self, service="auto", **options):  # pragma: no cover
        """Initiate a web server service to serve this application.
		
		You can always use the Application instance as a bare WSGI application, of course.  This method is provided as
		a convienence.
		
		Pass in the name of the service you wish to use, and any additional configuration options appropriate for that
		service.  Almost all services accept `host` and `port` options, some also allow you to specify an on-disk
		`socket`.  By default all web servers will listen to `127.0.0.1` (loopback only) on port 8080.
		"""

        service = load(service, "web.server")  # We don't bother with a full registry for these one-time lookups.

        try:
            service(self, **options)
        except KeyboardInterrupt:  # We catch this as SIG_TERM or ^C are basically the only ways to stop most servers.
            pass

            # Notify extensions that the service has returned and we are exiting.
        for ext in self.__context.extension.signal.stop:
            ext(self.__context)
    def serve(self, service='auto', **options):  # pragma: no cover
        """Initiate a web server service to serve this application.
		
		You can always use the Application instance as a bare WSGI application, of course.  This method is provided as
		a convienence.
		
		Pass in the name of the service you wish to use, and any additional configuration options appropriate for that
		service.  Almost all services accept `host` and `port` options, some also allow you to specify an on-disk
		`socket`.  By default all web servers will listen to `127.0.0.1` (loopback only) on port 8080.
		"""

        service = load(
            service, 'web.server'
        )  # We don't bother with a full registry for these one-time lookups.

        try:
            service(self, **options)
        except KeyboardInterrupt:  # We catch this as SIG_TERM or ^C are basically the only ways to stop most servers.
            pass

        # Notify extensions that the service has returned and we are exiting.
        for ext in self.__context.extension.signal.stop:
            ext(self.__context)
Exemple #8
0
class Root(object):
    # Attach the REST resource collection and routed "sub-directories".
    people = People
    diz = Routed

    # We can easily load from another module without cluttering globals.
    foo = load('myapp.controllers.foo:FooController')

    # The following is a static page definition.
    about = 'myapp.templates.about', dict()

    # This works, too!  In fact, you can use any registry-handleable value!
    readme = open('../README.textile', 'r')

    def __init__(self, context):
        self._ctx = context

    def __call__(self):
        """Handle "index" lookups."""
        return "Path: /"

    def index(self):
        """Handle calls to /index -- this is no longer the 'default' index lookup."""
        return "Path: /index"

    def template(self):
        self._ctx.context.log.warning("Returning template result.")
        return 'mako:./test.html', dict()

    # If HTTP verbs are your thing...

    @method.get
    def login(self):
        return "Present login form."

    @login.post
    def login(self, **data):
        # can call login.get() to explicitly call that handler.
        return "Actually log in."

    # Or conditional template / serializer usage based on filename extension:

    @render('mako:myapp.templates.details')
    @render('json:')  # used if request.format == 'json'
    def details(self):
        return dict(name="Bob", age=27)

    # Or straight-up if/elif/else:

    @require(predicate)
    def foo(self):
        return "We matched the predicate."

    @foo.require(other_predicate)
    def foo(self):
        return "We matched a different predicate."

    @foo.otherwise
    def foo(self):
        return "We didn't match anything.  :("

    # If you need to be able to dynamically load the next path element...

    def __getattr__(self, name):
        if name.isdigit():
            return lambda: "Numerical lookup!"

        raise AttributeError()

    # Or dynamically redirect object dispatch, possibly consuming *multiple* path elements...

    def __lookup__(self, *parts, **data):
        return Controller(), ()
Exemple #9
0
	def test_unknown_entrypoint(self):
		with pytest.raises(LookupError):
			assert load('bob.dole', 'console_scripts')
Exemple #10
0
	def test_basic_entrypoint(self):
		assert load('py.test', 'console_scripts') is pytest.main
Exemple #11
0
	def test_basic_import(self):
		assert load('test.helper:Example') is helper.Example
Exemple #12
0
	def test_invalid_import_default(self):
		assert load('foo.bar:baz', default="hi") == "hi"
Exemple #13
0
	def test_invalid_import_nodefault(self):
		with pytest.raises(ImportError):
			assert load('foo.bar:baz')
Exemple #14
0
    for djrow in l:
        package = 'web.app.djrq.model.' + djrow.databasetype
        djname = djrow.dj.lower()
        djs[djname] = {
            'databasetype':
            djrow.databasetype,
            'package':
            'web.app.djrq.model.' + djrow.databasetype,
            'lp_id':
            None,
            'current_listeners':
            0,
            'current_max_listeners':
            0,
            'queries':
            load(package + '.queries:Queries'),
            'listeners':
            load(package + '.listeners:Listeners'),
            'websocket':
            'http://{}.rockitradio.info/pub?id={}'.format(djname, djname),
        }
        #djs[djname]['websocket'] = 'http://dj-{}.gelth.local/pub?id=dj-{}'.format(djname, djname)

    lp.Session.close()
    lp.stop(context)

    while 1:
        # Get the latest played for each DJ
        for dj in databases.engines:
            elements_to_update = {}
            if dj == 'lastplay': continue