Python bottle.request.json() Examples

The following are 30 code examples for showing how to use bottle.request.json(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module bottle.request , or try the search function .

Example 1
Project: awe   Author: dankilman   File: api.py    License: MIT License 6 votes vote down vote up
def _new_element(self, element_id=None):
        body = request.json
        root_id = body.get('root_id')
        parent_id = body.get('parent_id')
        new_root = body.get('new_root')
        obj = body.get('obj')
        params = body.get('params') or {}
        assert obj
        assert not (root_id and parent_id)
        assert not (root_id and new_root)
        if parent_id:
            parent = self._registry.elements[parent_id]
        elif new_root:
            parent = self._registry.roots['root']._new_root()
        else:
            parent = self._registry.roots[root_id or 'root']
        element = parent.new(obj, id=element_id, **params)
        return self._get_element(element.id) 
Example 2
Project: mailur   Author: naspeh   File: web.py    License: GNU General Public License v3.0 6 votes vote down vote up
def jsonify(fn):
    @ft.wraps(fn)
    def inner(*a, **kw):
        response.content_type = 'application/json'
        try:
            data = fn(*a, **kw)
        except HTTPError as e:
            response.status = e.status_code
            data = {'errors': [e.body]}
        except schema.Error as e:
            response.status = 400
            data = {'errors': e.errors, 'schema': e.schema}
        except Exception as e:
            log.exception(e)
            response.status = 500
            data = {'errors': [str(e)]}
        return json.dumps(data or {}, indent=2, ensure_ascii=False)
    return inner 
Example 3
Project: mailur   Author: naspeh   File: web.py    License: GNU General Public License v3.0 6 votes vote down vote up
def login():
    data = schema.validate(request.json, {
        'type': 'object',
        'properties': {
            'username': {'type': 'string'},
            'password': {'type': 'string'},
            'timezone': {'type': 'string', 'enum': all_timezones},
            'theme': {'type': 'string', 'default': 'base'}
        },
        'required': ['username', 'password', 'timezone']
    })

    try:
        local.connect(data['username'], data['password'])
    except imap.Error as e:
        response.status = 400
        return {'errors': ['Authentication failed.'], 'details': str(e)}

    del data['password']
    request.session.update(data)
    return {} 
Example 4
Project: puppet   Author: Raytone-D   File: runner.py    License: MIT License 6 votes vote down vote up
def run(host='127.0.0.1', port=10086):
    from bottle import post, run, request, response

    @post('/puppet')
    def serve():
        '''Puppet Web Trading Interface'''
        task = request.json
        if task:
            try:
                return getattr(acc, task.pop('action'))(**task)
            except Exception as e:
                response.bind(status=502)
                return {'puppet': str(e)}
        return {'puppet': '仅支持json格式'}

    print('Puppet version:', __version__)
    acc = Account()
    run(host=host, port=port) 
Example 5
Project: RPi-InfoScreen-Kivy   Author: elParaguayo   File: webapi.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_config(self, screen):
        """Method to retrieve config file for screen."""

        # Define the path to the config file
        conffile = os.path.join(self.folder, "screens", screen, "conf.json")

        if os.path.isfile(conffile):

            # Get the config file
            with open(conffile, "r") as cfg_file:

                # Load the JSON object
                conf = json.load(cfg_file)

            # Return the "params" section
            result = self.api_success(conf.get("params", dict()))

        else:

            # Something's gone wrong
            result = self.api_error("No screen called: {}".format(screen))

        # Provide the response
        return json.dumps(result) 
Example 6
Project: infrabox   Author: InfraBox   File: trigger.py    License: MIT License 6 votes vote down vote up
def create_job(self, commit_id, clone_url, build_id, project_id, github_private_repo, branch, env=None, fork=False):
        git_repo = {
            "commit": commit_id,
            "clone_url": clone_url,
            "github_private_repo": github_private_repo,
            "branch": branch,
            "fork": fork
        }

        self.execute('''
            INSERT INTO job (id, state, build_id, type,
                             name, project_id, build_only,
                             dockerfile, cpu, memory, repo, env_var, cluster_name)
            VALUES (gen_random_uuid(), 'queued', %s, 'create_job_matrix',
                    'Create Jobs', %s, false, '', 1, 1024, %s, %s, 'master')
        ''', [build_id, project_id, json.dumps(git_repo), env], fetch=False) 
Example 7
Project: conifer   Author: Rhizome-Conifer   File: admincontroller.py    License: Apache License 2.0 6 votes vote down vote up
def grafana_time_stats(self, req):
        req = request.json or {}
        from_var = req['range']['from'][:10]
        to_var = req['range']['to'][:10]

        from_dt = datetime.strptime(from_var, '%Y-%m-%d')
        to_dt = datetime.strptime(to_var, '%Y-%m-%d')
        td = timedelta(days=1)

        dates = []
        timestamps = []

        while from_dt <= to_dt:
            dates.append(from_dt.date().isoformat())
            timestamps.append(from_dt.timestamp() * 1000)
            from_dt += td

        resp = [self.load_series(target, dates, timestamps) for target in req['targets']]

        return resp 
Example 8
Project: indiwebmanager   Author: knro   File: main.py    License: GNU Lesser General Public License v2.1 6 votes vote down vote up
def change_indihub_agent_mode(mode):
    """Change INDIHUB Agent mode with a current INDI-profile"""

    if active_profile == "" or not indi_server.is_running():
        response.content_type = 'application/json'
        response.status = 500
        return json.dumps({'message': 'INDI-server is not running. You need to run INDI-server first.'})

    indihub_agent.stop()

    if mode == 'off':
        return

    indihub_agent.start(active_profile, mode)


###############################################################################
# Startup standalone server
############################################################################### 
Example 9
Project: eavatar-me   Author: eavatar   File: webapi.py    License: Apache License 2.0 6 votes vote down vote up
def job_create():
    _logger.debug("job_create")
    try:
        job_data = request.json
    except ValueError:
        response.status = defines.HTTP_STATUS_BAD_REQUEST
        return dict(status=defines.ERROR, reason='No valid JSON object.')

    if job_data is None:
        response.status = defines.HTTP_STATUS_BAD_REQUEST
        return dict(status=defines.ERROR, reason='No script provided.')

    try:
        job_id = get_job_engine().submit_job(job_data)
        return dict(status=defines.SUCCESS, data=job_id)
    except (ScriptSyntaxError, SyntaxError) as ex:
        response.status = defines.HTTP_STATUS_BAD_REQUEST
        return dict(status=defines.ERROR, reason=str(ex)) 
Example 10
Project: MozDef   Author: mozilla   File: index.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def index():
    '''return a json version of whois for an ip address'''
    if request.body:
        arequest = request.body.read()
        request.body.close()
    # valid json?
    try:
        requestDict = json.loads(arequest)
    except ValueError:
        response.status = 500

    if 'ipaddress' in requestDict and isIPv4(requestDict['ipaddress']):
        response.content_type = "application/json"
        response.body = getWhois(requestDict['ipaddress'])
    else:
        response.status = 500

    sendMessgeToPlugins(request, response, 'ipwhois')
    return response 
Example 11
Project: MozDef   Author: mozilla   File: index.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def index():
    '''an endpoint to return alert schedules'''
    if request.body:
        request.body.read()
        request.body.close()
    response.content_type = "application/json"
    mongoclient = MongoClient(options.mongohost, options.mongoport)
    schedulers_db = mongoclient.meteor['alertschedules'].with_options(codec_options=CodecOptions(tz_aware=True))

    mongodb_alerts = schedulers_db.find()
    alert_schedules_dict = {}
    for mongodb_alert in mongodb_alerts:
        if mongodb_alert['last_run_at']:
            mongodb_alert['last_run_at'] = mongodb_alert['last_run_at'].isoformat()
        if 'modifiedat' in mongodb_alert:
            mongodb_alert['modifiedat'] = mongodb_alert['modifiedat'].isoformat()
        alert_schedules_dict[mongodb_alert['name']] = mongodb_alert

    response.body = json.dumps(alert_schedules_dict)
    response.status = 200
    return response 
Example 12
Project: MozDef   Author: mozilla   File: index.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def sync_alert_schedules():
    '''an endpoint to return alerts schedules'''
    if not request.body:
        response.status = 503
        return response

    alert_schedules = json.loads(request.body.read())
    request.body.close()

    response.content_type = "application/json"
    mongoclient = MongoClient(options.mongohost, options.mongoport)
    schedulers_db = mongoclient.meteor['alertschedules'].with_options(codec_options=CodecOptions(tz_aware=True))
    results = schedulers_db.find()
    for result in results:
        if result['name'] in alert_schedules:
            new_sched = alert_schedules[result['name']]
            result['total_run_count'] = new_sched['total_run_count']
            result['last_run_at'] = new_sched['last_run_at']
            if result['last_run_at']:
                result['last_run_at'] = toUTC(result['last_run_at'])
            logger.debug("Inserting schedule for {0} into mongodb".format(result['name']))
            schedulers_db.save(result)

    response.status = 200
    return response 
Example 13
Project: MozDef   Author: mozilla   File: index.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def update_alert_schedules():
    '''an endpoint to return alerts schedules'''
    if not request.body:
        response.status = 503
        return response

    alert_schedules = json.loads(request.body.read())
    request.body.close()

    response.content_type = "application/json"
    mongoclient = MongoClient(options.mongohost, options.mongoport)
    schedulers_db = mongoclient.meteor['alertschedules'].with_options(codec_options=CodecOptions(tz_aware=True))
    schedulers_db.remove()

    for alert_name, alert_schedule in alert_schedules.items():
        if alert_schedule['last_run_at']:
            alert_schedule['last_run_at'] = toUTC(alert_schedule['last_run_at'])
        logger.debug("Inserting schedule for {0} into mongodb".format(alert_name))
        schedulers_db.insert(alert_schedule)

    response.status = 200
    return response 
Example 14
Project: MozDef   Author: mozilla   File: index.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def verisSummary(verisRegex=None):
    try:
        # aggregate the veris tags from the incidents collection and return as json
        client = MongoClient(options.mongohost, options.mongoport)
        # use meteor db
        incidents = client.meteor['incidents']

        iveris = incidents.aggregate([
            {"$match": {"tags": {"$exists": True}}},
            {"$unwind": "$tags"},
            {"$match": {"tags": {"$regex": ''}}},
            {"$project": {
                "dateOpened": 1,
                "tags": 1,
                "phase": 1,
                "_id": 0
            }}
        ])
        if iveris:
            return json.dumps(list(iveris), default=json_util.default)
        else:
            return json.dumps(list())
    except Exception as e:
            logger.error('Exception while aggregating veris summary: {0}\n'.format(e)) 
Example 15
Project: awe   Author: dankilman   File: api.py    License: MIT License 5 votes vote down vote up
def _callback_wrapper(self, callback):
        def wrapper(*args, **kwargs):
            request.content_type = 'application/json'
            result = callback(*args, **kwargs)
            return self._encoder.to_json(result)
        return wrapper 
Example 16
Project: awe   Author: dankilman   File: api.py    License: MIT License 5 votes vote down vote up
def _update_data(self, element_id):
        element = self._registry.elements[element_id]
        body = request.json
        data = body.get('data')
        assert data
        element.update_data(data)
        return {'id': element_id, 'status': 'success'} 
Example 17
Project: awe   Author: dankilman   File: api.py    License: MIT License 5 votes vote down vote up
def _update_props(self, element_id):
        element = self._registry.elements[element_id]
        body = request.json
        props = body.get('props')
        prop_path = body.get('path')
        prop_value = body.get('value')
        assert props or (prop_path and prop_value)
        assert not (props and (prop_path or prop_value))
        if props:
            element.update_props(props)
        else:
            element.update_prop(prop_path, prop_value)
        return {'id': element_id, 'status': 'success'} 
Example 18
Project: awe   Author: dankilman   File: api.py    License: MIT License 5 votes vote down vote up
def _call_method(self, element_id, method):
        element = self._registry.elements[element_id]
        body = request.json
        kwargs = body.get('kwargs') or {}
        if method.startswith('_'):
            raise RuntimeError('cannot call private methods')
        assert hasattr(element, method)
        fn = getattr(element, method)
        fn(**kwargs)
        return {'id': element_id, 'status': 'success'} 
Example 19
Project: awe   Author: dankilman   File: api.py    License: MIT License 5 votes vote down vote up
def _update_variable(self, variable_id):
        body = request.json
        value = body.get('value')
        assert variable_id in self._registry.variables
        assert value
        self._message_handler.handle({
            'type': 'updateVariable',
            'variableId': variable_id,
            'value': value
        })
        return {'id': variable_id, 'status': 'success'} 
Example 20
Project: awe   Author: dankilman   File: api.py    License: MIT License 5 votes vote down vote up
def _call_function(self, function_id):
        body = request.json
        kwargs = body.get('kwargs') or {}
        assert function_id in self._registry.functions
        self._message_handler.handle({
            'type': 'call',
            'functionId': function_id,
            'kwargs': kwargs
        })
        return {'id': function_id, 'status': 'success'} 
Example 21
Project: mailur   Author: naspeh   File: web.py    License: GNU General Public License v3.0 5 votes vote down vote up
def tag():
    data = schema.validate(request.json, {
        'type': 'object',
        'properties': {
            'name': {
                'type': 'string',
                'pattern': r'^[^\\#]'
            },
        },
        'required': ['name']
    })
    tag = local.get_tag(data['name'])
    return wrap_tags({tag['id']: tag})['info'][tag['id']] 
Example 22
Project: mailur   Author: naspeh   File: web.py    License: GNU General Public License v3.0 5 votes vote down vote up
def expunge_tag():
    data = schema.validate(request.json, {
        'type': 'object',
        'properties': {
            'name': {
                'type': 'string',
                'enum': ['#trash', '#spam']
            },
        },
        'required': ['name']
    })
    local.msgs_expunge(data['name']) 
Example 23
Project: mailur   Author: naspeh   File: web.py    License: GNU General Public License v3.0 5 votes vote down vote up
def filters():
    def run():
        query, opts = parse_query(data['query'])
        if opts.get('thread') and opts.get('uids'):
            uids = opts['uids']
            oids = uids and local.pair_parsed_uids(uids)
            query = 'uid %s' % imap.pack_uids(oids)
        try:
            local.sieve_run(query, data['body'])
        except imap.Error as e:
            abort(400, e.args[0].decode())
        local.sync_flags_to_all()

    data = schema.validate(request.json, {
        'type': 'object',
        'properties': {
            'action': {'type': 'string', 'enum': ['save', 'run']},
            'name': {'type': 'string', 'enum': ['auto', 'manual']},
            'body': {'type': 'string'},
            'query': {'type': 'string'},
        },
        'required': ['action', 'name', 'body', 'query']
    })
    if data['action'] == 'save':
        run()
        local.data_filters({data['name']: data['body']})
        return local.sieve_scripts()

    body = data['body']
    if not body:
        return

    run() 
Example 24
Project: mailur   Author: naspeh   File: web.py    License: GNU General Public License v3.0 5 votes vote down vote up
def thrs_info():
    uids = request.json['uids']
    hide_tags = request.json.get('hide_tags', [])
    if not uids:
        return abort(400)
    return wrap_msgs(local.thrs_info(uids, hide_tags), hide_tags) 
Example 25
Project: mailur   Author: naspeh   File: web.py    License: GNU General Public License v3.0 5 votes vote down vote up
def msgs_info():
    uids = request.json['uids']
    hide_tags = request.json.get('hide_tags', [])
    if not uids:
        return abort(400)
    return wrap_msgs(local.msgs_info(uids), hide_tags) 
Example 26
Project: mailur   Author: naspeh   File: web.py    License: GNU General Public License v3.0 5 votes vote down vote up
def msgs_body():
    uids = request.json['uids']
    read = request.json.get('read', True)
    fix_privacy = request.json.get('fix_privacy', True)
    if not uids:
        return abort(400)
    if read:
        unread = local.search_msgs('uid %s unseen' % ','.join(uids))
        if unread:
            local.msgs_flag(unread, [], ['\\Seen'])
    return dict(local.msgs_body(uids, fix_privacy)) 
Example 27
Project: mailur   Author: naspeh   File: web.py    License: GNU General Public License v3.0 5 votes vote down vote up
def thrs_link():
    uids = request.json['uids']
    if not uids:
        return {}
    return {'uids': local.link_threads(uids)} 
Example 28
Project: mailur   Author: naspeh   File: web.py    License: GNU General Public License v3.0 5 votes vote down vote up
def thrs_unlink():
    uids = request.json['uids']
    if not uids:
        return {}
    uids = local.unlink_threads(uids)
    return {'query': ':threads uid:%s' % ','.join(uids)} 
Example 29
Project: mailur   Author: naspeh   File: web.py    License: GNU General Public License v3.0 5 votes vote down vote up
def markdown():
    txt = request.json.get('txt')
    return html.markdown(txt) 
Example 30
Project: mailur   Author: naspeh   File: web.py    License: GNU General Public License v3.0 5 votes vote down vote up
def themes():
    pkg = json.loads((root / 'package.json').read_text())
    return sorted(pkg['mailur']['themes'])