How to use the cherrypy.tools function in CherryPy

To help you get started, we’ve selected a few CherryPy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ncqgm / gnumed / gnumed / gnumed / test-area / CherryPy / gmGuiWeb.py View on Github external
    @cherrypy.expose
    @cherrypy.tools.jsonrpchdl()
    def services(self, *args, **kwargs):
        print "echo service"
        print args
        print kwargs
        method = kwargs['method']
        f = getattr(self,method)
        res = f(*kwargs['params'])
        return dumps({'id':kwargs['id'],'result':res,'error':None})
    def echo(self, text):
github cherrypy / cherrypy / cherrypy / _cprequest.py View on Github external
HTTPError, which are more properly called 'exceptions', not errors)."""

    closed = False
    """True once the close method has been called, False otherwise."""

    stage = None
    """
    A string containing the stage reached in the request-handling process.
    This is useful when debugging a live server with hung requests."""

    namespaces = reprconf.NamespaceSet(
        **{'hooks': hooks_namespace,
           'request': request_namespace,
           'response': response_namespace,
           'error_page': error_page_namespace,
           'tools': cherrypy.tools,
           })

    def __init__(self, local_host, remote_host, scheme='http',
                 server_protocol='HTTP/1.1'):
        """Populate a new Request object.

        local_host should be an httputil.Host object with the server info.
        remote_host should be an httputil.Host object with the client info.
        scheme should be a string, either "http" or "https".
        """
        self.local = local_host
        self.remote = remote_host
        self.scheme = scheme
        self.server_protocol = server_protocol

        self.closed = False
github waymarkedtrails / waymarked-trails-site / api / vector_tiles.py View on Github external
    @cherrypy.tools.etags(autotags=True)
    @cherrypy.tools.expires(secs=21600, force=True)
    @cherrypy.tools.gzip(mime_types=['text/json'])
    def index(self, zoom, x, y):
        if zoom != '12':
            raise cherrypy.HTTPError(400, 'Only zoom level 12 available')

        ypt = y.find('.')

        if ypt <= 0 or y[ypt+1:] != 'json':
            raise cherrypy.NotFound()

        x = int(x)
        y = int(y[:ypt])

        if x < 0 or x > 2**12 or y < 0 or y > 2**12:
            raise cherrypy.NotFound()
github styxit / HTPC-Manager / htpc / updater.py View on Github external
    @cherrypy.expose()
    @cherrypy.tools.json_out()
    def index(self):
        """ Handle server requests. Update on POST. Get status on GET. """
        if self.git == '':
            self.logger.warning('Git not configured. Automatic update disabled.')
            return -1
        if cherrypy.request.method.upper() == 'POST':
            Thread(target=self.git_update).start()
            return 1
        else:
            return self.check_update()
github edvm / pysenteishon / pysenteishon / app.py View on Github external
    @cherrypy.tools.json_out()
    def network_information(self):
        """Return a JSON response with network information.

        GET URL Example:
            http://127.0.0.1:8080/ifconfig

        For example:
        [
            {"addresses": "192.168.0.13", "name": "wlp1s0"},
            {"addresses": "172.17.0.1", "name": "docker0"}
        ]
        """
        network_info = get_network_interface_list()
        return network_info
github willzeng / WikiNets / server / server.py View on Github external
  @cherrypy.tools.json_out()
  def get_nodes(self):
    return self.provider.get_nodes();
github ned14 / static-website-activitypub / static_website_activitypub / actors.py View on Github external
    @cherrypy.tools.json_out()
    def index(self, actor):
        if actor == self.user_account:
            return self.cached_response
        raise cherrypy.HTTPError(404, 'Actor not found')
github GOVCERT-LU / ce1sus / ce1sus / web / views / admin / subgroups.py View on Github external
  @cherrypy.tools.allow(methods=['POST'])
  def edit_subgroup_groups(self, identifier, operation,
                           existing=None, remaining=None):
    """
    modifies the relation between a group and its subgroups

    :param groupID: The groupID of the group
    :type groupID: Integer
    :param operation: the operation used in the context (either add or remove)
    :type operation: String
    :param remainingUsers: The identifiers of the users which the group is not
                            groupd to
    :type remainingUsers: Integer array
    :param groupUsers: The identifiers of the users which the group is
                       groupd to
    :type groupUsers: Integer array
github Lawouach / WebSocket-for-Python / ws4py / server / cherrypyserver.py View on Github external
"""
        Broadcasts a message to all connected clients known to
        the server.

        :param message: a message suitable to pass to the send() method
          of the connected handler.
        :param binary: whether or not the message is a binary one
        """
        self.manager.broadcast(message, binary)

if __name__ == '__main__':
    import random
    cherrypy.config.update({'server.socket_host': '127.0.0.1',
                            'server.socket_port': 9000})
    WebSocketPlugin(cherrypy.engine).subscribe()
    cherrypy.tools.websocket = WebSocketTool()

    class Root(object):
        @cherrypy.expose
        @cherrypy.tools.websocket(on=False)
        def ws(self):
            return """
        
          
github styxit / HTPC-Manager / libs / cherrypy / lib / auth2.py View on Github external
conditions that the user must fulfill"""

    p = '%sauth/login' % htpc.WEBDIR
    conditions = cherrypy.request.config.get('auth.require', None)
    if conditions is not None:
        username = cherrypy.session.get(SESSION_KEY)
        if username:
            cherrypy.request.login = username
            for condition in conditions:
                # A condition is just a callable that returns true or false
                if not condition():
                    raise cherrypy.HTTPRedirect(p)
        else:
            raise cherrypy.HTTPRedirect(p)

cherrypy.tools.auth = cherrypy.Tool('before_handler', check_auth)


def require(*conditions):
    """A decorator that appends conditions to the auth.require config
    variable."""
    def decorate(f):
        if not hasattr(f, '_cp_config'):
            f._cp_config = dict()
        if 'auth.require' not in f._cp_config:
            f._cp_config['auth.require'] = []
        f._cp_config['auth.require'].extend(conditions)
        return f
    return decorate


# Conditions are callables that return True