Python bottle.request.json() Examples
The following are 30
code examples of bottle.request.json().
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 also want to check out all available functions/classes of the module
bottle.request
, or try the search function
.
Example #1
Source File: index.py From MozDef with Mozilla Public License 2.0 | 6 votes |
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 #2
Source File: index.py From MozDef with Mozilla Public License 2.0 | 6 votes |
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 #3
Source File: web.py From mailur with GNU General Public License v3.0 | 6 votes |
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 #4
Source File: web.py From mailur with GNU General Public License v3.0 | 6 votes |
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 #5
Source File: api.py From awe with MIT License | 6 votes |
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 #6
Source File: index.py From MozDef with Mozilla Public License 2.0 | 6 votes |
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 #7
Source File: index.py From MozDef with Mozilla Public License 2.0 | 6 votes |
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 #8
Source File: index.py From MozDef with Mozilla Public License 2.0 | 6 votes |
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 #9
Source File: runner.py From puppet with MIT License | 6 votes |
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 #10
Source File: webapi.py From RPi-InfoScreen-Kivy with GNU General Public License v3.0 | 6 votes |
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 #11
Source File: webapi.py From eavatar-me with Apache License 2.0 | 6 votes |
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 #12
Source File: main.py From indiwebmanager with GNU Lesser General Public License v2.1 | 6 votes |
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 #13
Source File: trigger.py From infrabox with MIT License | 6 votes |
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 #14
Source File: admincontroller.py From conifer with Apache License 2.0 | 6 votes |
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 #15
Source File: index.py From MozDef with Mozilla Public License 2.0 | 5 votes |
def status(): '''endpoint for a status/health check''' if request.body: request.body.read() request.body.close() response.status = 200 response.content_type = "application/json" response.body = json.dumps(dict(status='ok', service='restapi')) sendMessgeToPlugins(request, response, 'status') return response
Example #16
Source File: main.py From indiwebmanager with GNU Lesser General Public License v2.1 | 5 votes |
def get_json_drivers(): """Get all drivers (JSON)""" response.content_type = 'application/json' return json.dumps([ob.__dict__ for ob in collection.drivers])
Example #17
Source File: main.py From indiwebmanager with GNU Lesser General Public License v2.1 | 5 votes |
def get_json_groups(): """Get all driver families (JSON)""" response.content_type = 'application/json' families = collection.get_families() return json.dumps(sorted(families.keys()))
Example #18
Source File: main.py From indiwebmanager with GNU Lesser General Public License v2.1 | 5 votes |
def get_server_drivers(): """List server drivers""" # status = [] # for driver in indi_server.get_running_drivers(): # status.append({'driver': driver}) # return json.dumps(status) # labels = [] # for label in sorted(indi_server.get_running_drivers().keys()): # labels.append({'driver': label}) # return json.dumps(labels) drivers = [] if indi_server.is_running() is True: for driver in indi_server.get_running_drivers().values(): drivers.append(driver.__dict__) return json.dumps(drivers)
Example #19
Source File: main.py From indiwebmanager with GNU Lesser General Public License v2.1 | 5 votes |
def get_server_status(): """Server status""" status = [{'status': str(indi_server.is_running()), 'active_profile': active_profile}] return json.dumps(status)
Example #20
Source File: main.py From indiwebmanager with GNU Lesser General Public License v2.1 | 5 votes |
def get_remote_drivers(item): """Get remote drivers of specific profile""" results = db.get_profile_remote_drivers(item) if results is None: results = {} return json.dumps(results) ############################################################################### # Server endpoints ###############################################################################
Example #21
Source File: main.py From indiwebmanager with GNU Lesser General Public License v2.1 | 5 votes |
def save_profile_custom_driver(): """Add custom driver to existing profile""" data = request.json db.save_profile_custom_driver(data) collection.clear_custom_drivers() collection.parse_custom_drivers(db.get_custom_drivers())
Example #22
Source File: main.py From indiwebmanager with GNU Lesser General Public License v2.1 | 5 votes |
def save_profile_drivers(name): """Add drivers to existing profile""" data = request.json db.save_profile_drivers(name, data)
Example #23
Source File: main.py From indiwebmanager with GNU Lesser General Public License v2.1 | 5 votes |
def update_profile(name): """Update profile info (port & autostart & autoconnect)""" response.set_cookie("indiserver_profile", name, None, max_age=3600000, path='/') data = request.json port = data.get('port', args.indi_port) autostart = bool(data.get('autostart', 0)) autoconnect = bool(data.get('autoconnect', 0)) db.update_profile(name, port, autostart, autoconnect)
Example #24
Source File: main.py From indiwebmanager with GNU Lesser General Public License v2.1 | 5 votes |
def get_json_profile(item): """Get one profile info""" results = db.get_profile(item) return json.dumps(results)
Example #25
Source File: main.py From indiwebmanager with GNU Lesser General Public License v2.1 | 5 votes |
def get_json_profiles(): """Get all profiles (JSON)""" results = db.get_profiles() return json.dumps(results)
Example #26
Source File: weblcds.py From artisan with GNU General Public License v3.0 | 5 votes |
def send(): send_all(jdumps(request.json)) # route that establishes the websocket between the Artisan app and the clients
Example #27
Source File: bugreportcontroller.py From conifer with Apache License 2.0 | 5 votes |
def add_bug_report(self, report): report = json.dumps(report) self.redis.rpush('h:reports', report) if self.reports_email: subject = "[Doesn't Look Right] Error Report - {0}".format(now) email_text = self.email_view(report) self.cork.mailer.send_email(self.reports_email, subject, email_text) return True
Example #28
Source File: admincontroller.py From conifer with Apache License 2.0 | 5 votes |
def fetch_coll_table(self): colls = self.redis.get(self.CACHE_COLL_TABLE) if colls: return json.loads(colls) column_keys = ['slug', 'title', 'size', 'owner', 'created_at', 'updated_at', 'public'] colls = [] for coll_key in self.redis.scan_iter('c:*:info', count=100): coll_data = self.redis.hmget(coll_key, column_keys) # exclude temp user collections try: user = self.user_manager.all_users[coll_data[3]] if user.is_anon(): continue except: continue coll_data[2] = int(coll_data[2]) coll_data[4] = self.parse_iso_or_ts(coll_data[4]) coll_data[5] = self.parse_iso_or_ts(coll_data[5]) coll_data.append(self.redis.zcard(coll_key.replace(':info', ':lists'))) colls.append(coll_data) self.redis.setex(self.CACHE_COLL_TABLE, self.CACHE_TTL, json.dumps(colls)) return colls
Example #29
Source File: permissioned.py From crankycoin with MIT License | 5 votes |
def get_transactions_index(block_hash): blockchain = Blockchain() transaction_inv = blockchain.get_transaction_hashes_by_block_hash(block_hash) if transaction_inv: return json.dumps({'tx_hashes': transaction_inv}) response.status = 404 return json.dumps({'success': False, 'reason': 'Transactions Not Found'})
Example #30
Source File: main.py From indiwebmanager with GNU Lesser General Public License v2.1 | 5 votes |
def get_indihub_status(): """INDIHUB Agent status""" mode = indihub_agent.get_mode() is_running = indihub_agent.is_running() response.content_type = 'application/json' status = [{'status': str(is_running), 'mode': mode, 'active_profile': active_profile}] return json.dumps(status)