def send_response(code, message=None): r = HTTPResponse(status=code) r.add_header('Access-Control-Allow-Origin', '*') r.set_header('Content-Type', 'application/json') if message is None: r.set_header('Content-Type', 'text/plain') elif type(message) is str: e = {'error': message} r.body = json.dumps(e) elif type(message) is dict: r.body = json.dumps(message) else: r.body = message return r
def _create_response(self, event): local_response = HTTPResponse(headers=event.headers) status, status_message = event.status local_response.status = "{code} {message}".format(code=status, message=status_message) local_response.set_header("Content-Type", event.content_type) local_response.body = "" if int(status) == 204 else self._format_response_data(event) return local_response
def get_powerstatus(request, _xbox): # args = get_request_log_args(request) # try: # isOn = _xbox.power_status() # data = {'isOn': isOn} # status = httpStatusSuccess # args['result'] = logPass args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status response.body = data enable_cors(response) # return response # except Exception as e: status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def get_ui_index(request): # args = get_request_log_args(request) # try: with open( os.path.join(os.path.dirname(__file__), '..', 'webfiles/index.html'), 'r') as f: page_body = f.read() # status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status response.body = page_body enable_cors(response) # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def get_commands(request, _virginmedia_tivo): # args = get_request_log_args(request) # try: # data = _virginmedia_tivo.getCommands() # status = httpStatusSuccess # args['result'] = logPass args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status response.body = data # return response # except Exception as e: status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def success(): response = HTTPResponse() response.status = 200 response.body = json.dumps( { 'message': 'Success' } ) + "\n" return response
def apikeyNotValid(): response = HTTPResponse() response.status = 200 response.body = json.dumps( { 'message': 'api key not valid', } ) + "\n" return response
def badRequest(key): response = HTTPResponse() response.status = 400 response.body = json.dumps( { 'message': 'Failed', 'BadRequest': key } ) + "\n" return response
def cannotTweet(): response = HTTPResponse() response.status = 500 response.body = json.dumps( { 'message': 'Failed', 'Error': 'CannotTweet' } ) + "\n" return response
def get_headlines(request, option): # args = get_request_log_args(request) args['timestamp'] = datetime.now() args['process'] = 'inbound' # try: # data = {} # if option == 'sources': data['articles'] = cache.cache['headlines']['sources'] data['sources'] = cache.cache['sources']['sources'] elif option == 'categories': data['articles'] = cache.cache['headlines']['categories'] data['sources'] = cache.cache['sources']['categories'] elif option == 'country': data['articles'] = cache.cache['headlines']['country'] data['sources'] = cache.cache['sources']['country'] elif option == 'language': data['articles'] = cache.cache['headlines']['language'] data['sources'] = cache.cache['sources']['language'] else: data = False # if not bool(data): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' cache.logQ.put(args) # response = HTTPResponse() response.status = status # if not isinstance(data, bool): response.body = data # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e cache.logQ.put(args) # raise HTTPError(status)
def get_calendar_daterange(request, option, dateFrom, dateTo): # args = get_request_log_args(request) args['timestamp'] = datetime.now() args['process'] = 'inbound' # try: # '_dateFrom' and '_dateTo' should be in format "yyyy-mm-dd" _dateFrom = datetime.strptime(dateFrom, '%Y-%m-%d') _dateTo = datetime.strptime(dateTo, '%Y-%m-%d') # if option == str_calendar_events: data = { str_calendar_events: cache.cache['_icloud'].get_events_daterange( _dateFrom, _dateTo) } elif option == str_calendar_birthdays: data = { str_calendar_birthdays: get_birthdays_daterange(_dateFrom, _dateTo) } else: data = False # if not bool(data): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' cache.logQ.put(args) # response = HTTPResponse() response.status = status # if not isinstance(data, bool): response.body = data # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e cache.logQ.put(args) # raise HTTPError(status)
def hello(): # pylint: disable=unused-variable paper_id = str(request.params.paper_id) # pylint: disable=no-member paper_pdf_url = str(request.params.paper_pdf_url) # pylint: disable=no-member response = HTTPResponse(status=200) if (not paper_id) or (not paper_pdf_url): response.status = 400 response.body = {'status': response.status} parse_xhtml(paper_id, paper_pdf_url) return response
def api_get_info(): response = HTTPResponse() all_ = request.query.get('all') issue = request.query.get('issue') if all_ in ['1', 'True', 'true']: rows = get_all_info() response.body = json.dumps( rows, default=default_datetime_format ) + "\n" elif issue is not None: row = get_info(issue) response.body = json.dumps( row, default=default_datetime_format ) + "\n" else: row = get_latest_info() response.body = json.dumps( row, default=default_datetime_format ) + "\n" return response
def get_sunrisesunset(request, _weather, _sunrisesunset, date): # # 'date' in YYYY-MM-DD format. Also accepts other date formats and even relative date formats. # If not present, date defaults to current date. Optional. # args = get_request_log_args(request) # try: # location = _weather.get_location() lat = location['latitude'] long = location['longitude'] # if date: data = _sunrisesunset.get_sunrise_sunset(lat, long, date) else: data = _sunrisesunset.get_sunrise_sunset(lat, long, 'today') # if not bool(data): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status # if not isinstance(data, bool): response.body = data # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def get_data_infoservice(service=False, resource_requested=False): # global infoservices # log = log_msg(request, uri_data_infoservice) # try: # if (not service) or (not resource_requested): log_error('{log} - {error}'.format(log=log, error='URI invalid')) raise HTTPError(404) # try: info_seq = get_cfg_info_seq(service) except Exception as e: log_error('{log} - {error}'.format(log=log, error=e)) raise HTTPError(404) # data_dict = {'data': resource_requested} # if len(request.query.decode()) > 0: data_dict.update(request.query.decode()) # # rsp = infoservices[info_seq].getData(data_dict) # response = HTTPResponse() enable_cors(response) # if isinstance(rsp, bool): if rsp: response.status = 200 else: response.status = 400 else: if bool(rsp): response.body = str(rsp) response.status = 200 else: response.status = 400 # log_general(log) return response # except Exception as e: log_error('{log} - {error}'.format(log=log, error=e)) raise HTTPError(500)
def get_calendar_all(request, option): # args = get_request_log_args(request) args['timestamp'] = datetime.now() args['process'] = 'inbound' # try: # if option == str_calendar_events: data = {str_calendar_events: cache.cache['calendar']['events']} elif option == str_calendar_birthdays: data = { str_calendar_birthdays: cache.cache['calendar']['birthdays'] } else: data = False # if not bool(data): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' cache.logQ.put(args) # response = HTTPResponse() response.status = status # if not isinstance(data, bool): response.body = data # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e cache.logQ.put(args) # raise HTTPError(status)
def get_all(request, _weather, _sunrisesunset): # args = get_request_log_args(request) # try: # data = _weather.get_weather_forecast() # if not bool(data): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # for day_key in data['days'].keys(): # data['days'][day_key][ 'sunRiseSet'] = _sunrisesunset.get_sunrise_sunset( data['location']['latitude'], data['location']['longitude'], data['days'][day_key]['date']) # # args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status # if not isinstance(data, bool): response.body = data # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def get_forecast(request, _weather, option): # args = get_request_log_args(request) # try: # if option == 'all': data = _weather.get_weather_forecast() elif option == '3hourly': data = False elif option == 'daily': data = False else: data = False # if not bool(data): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status # if not isinstance(data, bool): response.body = data # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def trigger(): group_id = request.query.group_id start_time = request.query.start_time duration = request.query.duration hashtag = request.query.hashtag hashtag = hashtag.replace('#', '\#') start_time = fetch_unix_time() print(start_time, flush=True) cmd = 'php filter-oauth.php {} {}'.format(group_id, hashtag) Thread(target=run_cmd, args=(cmd, start_time, duration)).start() res = HTTPResponse(200) res.body = {} res.body['start_time'] = start_time return res
def get_apps_all(request, _tvlgnetcast): # args = get_request_log_args(request) # try: # r = _tvlgnetcast.getApps_all() # # Add URI for retrieving image item for k in r.keys(): r[k]['image'] = '/img/appicon/{auid}'.format(auid=r[k]['auid']) # if not bool(r): status = httpStatusFailure result = logFail else: status = httpStatusSuccess result = logPass # args['result'] = result args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status enable_cors(response) # if not isinstance(r, bool): response.body = r # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def get_news_config_html(request): # args = get_request_log_args(request) args['timestamp'] = datetime.now() args['process'] = 'inbound' # try: # data = {} # body = build_page() # if not bool(body): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' cache.logQ.put(args) # response = HTTPResponse() response.status = status # if not isinstance(data, bool): response.body = body # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e cache.logQ.put(args) # raise HTTPError(status)
def render_response(self, resp): # always ensure we have a http response instance if not isinstance(resp, HTTPResponse): resp = HTTPResponse(resp) # create new response type nresp = HTTPResponse() resp.apply(nresp) if not request.nctx.renderer: return nresp # apply rendering nresp.body = request.nctx.renderer.render(nresp.body) nresp.content_type = request.nctx.response_content_type # XXX: manually append charset due to bug # https://github.com/bottlepy/bottle/issues/1048 if request.nctx.renderer.charset: to_append = '; charset={}'.format(request.nctx.renderer.charset.upper()) nresp.content_type += to_append return nresp
def get_volume(request, _tvlgnetcast): # args = get_request_log_args(request) # try: # r = _tvlgnetcast.getVolume() # if not bool(r): status = httpStatusFailure result = logFail else: status = httpStatusSuccess result = logPass # args['result'] = result args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status enable_cors(response) # if not isinstance(r, bool): response.body = r # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def render_response(self, resp): # always ensure we have a http response instance if not isinstance(resp, HTTPResponse): resp = HTTPResponse(resp) # create new response type nresp = HTTPResponse() resp.apply(nresp) if not request.nctx.renderer: return nresp # apply rendering nresp.body = request.nctx.renderer.render(nresp.body) nresp.content_type = request.nctx.response_content_type # XXX: manually append charset due to bug # https://github.com/bottlepy/bottle/issues/1048 if request.nctx.renderer.charset: to_append = '; charset={}'.format( request.nctx.renderer.charset.upper()) nresp.content_type += to_append return nresp
def consume(self, event, *args, **kwargs): # There is an error that results in responding with an empty list that will cause an internal server error original_event_class, response_queue = self.responders.pop(event.event_id, None) if response_queue: accept = event.get('accept', original_event_class.content_type) if not isinstance(event, self.CONTENT_TYPE_MAP[accept]): self.logger.warning( "Incoming event did did not match the clients Accept format. Converting '{current}' to '{new}'".format( current=type(event), new=original_event_class.__name__)) event = event.convert(self.CONTENT_TYPE_MAP[accept]) local_response = HTTPResponse() status, status_message = event.status local_response.status = "{code} {message}".format(code=status, message=status_message) for header, value in event.headers.iteritems(): local_response.set_header(header, value) local_response.set_header("Content-Type", event.content_type) if int(status) == 204: response_data = "" else: response_data = self.format_response_data(event) local_response.body = response_data response_queue.put(local_response) response_queue.put(StopIteration) self.logger.info("[{status}] Service '{service}' Returned in {time:0.0f} ms".format( service=event.service, status=local_response.status, time=(datetime.now()-event.created).total_seconds() * 1000), event=event) else: self.logger.warning("Received event response for an unknown event ID. The request might have already received a response", event=event)
def post_2fa_code_request(request): # args = get_request_log_args(request) args['timestamp'] = datetime.now() args['process'] = 'inbound' # try: r = cache.cache['_icloud'].request_validation_code_default() # if r['result']: status = httpStatusSuccess args['result'] = logPass else: status = httpStatusFailure args['result'] = logFail # args['http_response_code'] = status args['description'] = '-' cache.logQ.put(args) # response = HTTPResponse() response.status = status response.body = r enable_cors(response) # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e cache.logQ.put(args) # raise HTTPError(status)
def get_devices_type(request, _nest, device_type): # args = get_request_log_args(request) # try: # r = _nest.getDevicesType(device_type) # if not bool(r): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status # if not isinstance(r, bool): response.body = r # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def get_location(request, _weather): # args = get_request_log_args(request) # try: # data = _weather.get_location() # if not bool(data): status = httpStatusFailure args['result'] = logFail else: status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status # if not isinstance(data, bool): response.body = data # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def api_update_info(id_): response = HTTPResponse() required_key = ['apikey'] optional_key = ['type', 'service', 'begin', 'end', 'detail'] try: params = require(required_key) except RequireNotSatisfiedError as e: return badRequest(e.message) params.update(optional(optional_key)) tw_flg = request.forms.get('tweet', False) if params['apikey'] != cfg['API_KEY']: return apikeyNotValid() for value in params.values(): if value is not None: if update(id_, params) and tw_flg: tweet(get_status(get_info(id_))) break row = get_info(id_) response.body = json.dumps( row, default=default_datetime_format )+"\n" return response
def get_recordings(request, _virginmedia_tivo): # args = get_request_log_args(request) # try: # r = _virginmedia_tivo.getRecordings() # if not bool(r): status = httpStatusFailure else: status = httpStatusSuccess # args['result'] = logPass args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status # if not isinstance(r, bool): response.body = r # return response # except Exception as e: status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def get_checkchannels(request): # args = get_request_log_args(request) # try: # r = checkChannels() # if not r: status = httpStatusFailure else: status = httpStatusSuccess # args['result'] = logPass args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # response = HTTPResponse() response.status = status # if not isinstance(r, bool): response.body = r # return response # except Exception as e: status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPError(status)
def jsonify(body='', status=200): response = HTTPResponse(content_type='application/json') response.body = json.dumps(body) response.status = status return response
def jsonify(obj, status=200): response = HTTPResponse(content_type='application/json') response.body = json.dumps(obj, encoding='latin1') response.status = status return response
def get_js(file_path): r = HTTPResponse(status=200) r.headers['Content-Type'] = 'text/css; charset=utf-8' r.body = static_file(file_path, root='./css') return r
def get_ui_config(request): # args = get_request_log_args(request) # try: # status = httpStatusSuccess args['result'] = logPass # args['http_response_code'] = status args['description'] = '-' log_inbound(**args) # modules = get_cfg_details_modules() tempModules = {} for module in modules: if not module['group'] in tempModules: tempModules[module['group']] = {} tempModules[module['group']][module['index']] = module # r = 'window.onload=function() {' # for groupKey in tempModules: modules = tempModules[groupKey] # for moduleKey in sorted(modules.keys()): module = modules[moduleKey] # moduleType = module['module'] group = module['group'] index = module['index'] # try: r += "module_init('{module}', '{group}', {index}, '{url}');\n".format( module=moduleType, group=group, index=index, url=module['url']) except: r += "module_init('{module}', '{group}', {index});\n".format( module=moduleType, group=group, index=index) # r += '}' # response = HTTPResponse() response.body = r response.status = status enable_cors(response) # return response # except Exception as e: # status = httpStatusServererror # args['result'] = logException args['http_response_code'] = status args['description'] = '-' args['exception'] = e log_inbound(**args) # raise HTTPResponse(status=status)