How to use the cherrypy.tools.json_out 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 styxit / HTPC-Manager / htpc / log.py View on Github external
    @cherrypy.expose()
    @require()
    @cherrypy.tools.json_out()
    def getlog(self, lines=10, level=2):
        """ Get log as JSON """
        levels = ['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'][-int(level):]
        content = []
        try:
            for line in reversed(open(self.logfile, 'r').readlines()):
                line = line.split(' :: ')
                if len(line) > 1 and line[2] in levels:
                    content.append(line)
                    if len(content) >= int(lines):
                        break
        except IOError:
            # Can't log this error since there is no log file.
            pass

        return content
github sandialabs / slycat / packages / slycat / web / server / handlers.py View on Github external
@cherrypy.tools.json_out(on = True)
def get_user(uid):
  user = cherrypy.request.app.config["slycat"]["directory"].user(uid)
  if user is None:
    raise cherrypy.HTTPError(404)
  # Only project administrators can get user details ...
  if slycat.web.server.authentication.is_server_administrator():
    user["server-administrator"] = uid in cherrypy.request.app.config["slycat"]["server-admins"]
  return user
github luciddg / auth-tool / webapp / __init__.py View on Github external
    @cherrypy.tools.json_out()
    @cherrypy.tools.allowed(allowed_methods=['GET', 'POST', 'DELETE'])
    def sshkey(self, sshpubkey=None):
        http_method = cherrypy.request.method.upper()

        if cherrypy.session.get('auth', False):
            user = cherrypy.session['user']
            if http_method == 'POST':
                try:
                    newkey = SSHKey(sshpubkey)
                    user.add_key(newkey.key)
                    return {
                        'ok': True,
                        'fingerprint': newkey.fingerprint,
                        'comment': newkey.comment
                    }
                except UserModelException:
github styxit / HTPC-Manager / modules / couchpotato.py View on Github external
    @cherrypy.expose()
    @require()
    @cherrypy.tools.json_out()
    def SearchMovie(self, q=''):
        self.logger.debug("Searching for movie")
        return self.fetch('movie.search/?q=' + q)
github YoannQueret / ODR-EncoderManager / api / __init__.py View on Github external
    @cherrypy.tools.json_out()
    @require()
    def setNetworkCard(self):
        self.conf = Config(self.config_file)

        cl = cherrypy.request.headers['Content-Length']
        rawbody = cherrypy.request.body.read(int(cl))
        param = json.loads(rawbody.decode('utf-8'))

        output = { 'global': self.conf.config['global'], 'auth': self.conf.config['auth'], 'odr': self.conf.config['odr'] }

        change = False
        for i,value in enumerate(output['global']['network']['cards']):
            if value['card'] == param['card']:
                output['global']['network']['cards'][i]['dhcp'] = param['dhcp']
                output['global']['network']['cards'][i]['ip'] = param['ip']
                output['global']['network']['cards'][i]['netmask'] = param['netmask']
github cylc / cylc-flow / lib / cylc / network / httpserver.py View on Github external
    @cherrypy.tools.json_out()
    def get_suite_info(self):
        """Return a dict containing the suite title and description."""
        self._check_access_priv_and_report(PRIV_DESCRIPTION)
        return self.schd.info_get_suite_info()
github cylc / cylc-flow / lib / cylc / network / httpserver.py View on Github external
    @cherrypy.tools.json_out()
    def take_checkpoints(self, items):
        """Checkpoint current task pool.

        items[0] is the name of the checkpoint.
        """
        self._check_access_priv_and_report(PRIV_FULL_CONTROL)
        if not isinstance(items, list):
            items = [items]
        self.schd.command_queue.put(("take_checkpoints", (items,), {}))
        return (True, 'Command queued')
github sandialabs / slycat / packages / slycat / web / server / handlers.py View on Github external
@cherrypy.tools.json_out(on = True)
def put_project(pid):
  database = slycat.web.server.database.couchdb.connect()
  project = database.get("project", pid)
  slycat.web.server.authentication.require_project_writer(project)

  mutations = []
  if "acl" in cherrypy.request.json:
    slycat.web.server.authentication.require_project_administrator(project)
    if "administrators" not in cherrypy.request.json["acl"]:
      raise cherrypy.HTTPError("400 missing administrators")
    if "writers" not in cherrypy.request.json["acl"]:
      raise cherrypy.HTTPError("400 missing writers")
    if "readers" not in cherrypy.request.json["acl"]:
      raise cherrypy.HTTPError("400 missing readers")
    project["acl"] = cherrypy.request.json["acl"]
github YoannQueret / ODR-EncoderManager / api / __init__.py View on Github external
    @cherrypy.tools.json_out()
    @require()
    def getAlsaDevices(self):
        command = '/usr/bin/arecord -l'
        try:
            output = subprocess.check_output(command,
                                shell=True,
                                stderr=subprocess.STDOUT)
        except:
            return {'status': '-200', 'statusText': 'Error listing alsa devices', 'data': ''}
        return {'status': '0', 'statusText': 'Ok', 'data': str(output.decode('UTF-8'))}