def channel_data(self, channel_num): """ Pull the latest measurement data for the specified channel. """ try: limit = int(request.query.get('limit', 250)) if limit < 1: raise ValueError() except ValueError: return Response(body=json_dumps( {'error': 'Invalid Limit Value! Must be a positive integer.'}), type='application/json', status=400) else: return Response(body=json_dumps({ 'data': [ m.to_api_response() for m in reversed( select_latest_channel_measurements( self.db_conn, channel_num, limit=limit)) ], 'stationCountData': list( reversed( select_latest_channel_device_counts(self.db_conn, channel_num, limit=limit))) }), type='application/json', status=200)
def papers_fetch_remote_url(): try: url = request.query['url'] r = requests.get(url) resp = Response(body=r.text, status=r.status_code) return resp except Exception: return Response(body='', status=400)
def metrics(): """Return Prometheus metrics""" return generate_latest() response = Response() response.set_header('Content-Type', 'text/plain; version=0.0.4; charset=utf-8') response.body = generate_latest() return response
def twiml_response(): """Provides TwiML instructions in response to a Twilio POST webhook event so that Twilio knows how to handle the outbound phone call when someone picks up the phone. """ response = twiml.Response() response.say("Hello, this call is from a Bottle web application.") response.play("https://api.twilio.com/cowbell.mp3", loop=10) return Response(str(response))
def twiml_response(): """Provides TwiML instructions in response to a Twilio POST webhook event so that Twilio knows how to handle the outbound phone call when someone picks up the phone. """ response = twiml.Response() response.say("Sweet, this phone call is answered by your Bottle app!") response.play("https://api.twilio.com/cowbell.mp3", loop=10) return Response(str(response))
def outbound_call(outbound_phone_number): """Uses the Twilio Python helper library to send a POST request to Twilio telling it to dial an outbound phone call from our specific Twilio phone number (that phone number must be owned by our Twilio account). """ twilio_client.calls.create(to=outbound_phone_number, from_=TWILIO_NUMBER, url=BASE_URL) return Response('Calling ' + outbound_phone_number)
def papers_add(): body = request.body.read() body = json.loads(body) if _db.add_paper(body): body = 'ok' code = 200 else: body = 'failed' code = 400 resp = Response(body, status=code) return resp
def watch(url, quality): """Open a stream based on URL/quality and send it back""" stream = openStream(url, quality) try: sd = stream.open() except StreamError: abort(404) return Response(playStream(sd), mimetype="video/unknown")
def json_response(obj: Any, status: int = 200, headers: Optional[dict] = None) -> BaseResponse: """Makes right json response message.""" json_text = json_util.dumps(obj, indent=2, sort_keys=True, ensure_ascii=False) return Response(body=json_text, content_type='application/json', status=status, headers=headers)
def outbound_call(outbound_phone_number): """Uses the Twilio Python helper library to send a POST request to Twilio telling it to dial an outbound phone call from our specific Twilio phone number (that phone number must be owned by our Twilio account). """ # the url must match the Ngrok Forwarding URL plus the route defined in # the previous function that responds with TwiML instructions twilio_client.calls.create(to=outbound_phone_number, from_=TWILIO_NUMBER, url=NGROK_BASE_URL + '/twiml') return Response('phone call placed to ' + outbound_phone_number + '!')
def delete_user(user_uuid: str): """ tags: - userAPI summary: Delete a single user record description: Delete a user parameters: - name: user_uuid in: path description: UUID of the user to delete required: true type: string responses: '204': description: Delete is OK '404': description: User not found or already deleted schema: $ref: '#/definitions/Error' '405': description: Wrong method schema: $ref: '#/definitions/Error' """ validate_request( # do the validation request.headers, request.method, SUPPORTED_METHODS['/delete_user']) if request.method == 'DELETE': try: delete_by_uuid(user_uuid) return Response(status=204) except errors.UserNotFound as e: e.message_json = f'User {user_uuid} not found' log_exception(e) return json_error_response(e) except errors.InternalServerError as e: log_exception(e) return json_error_response(e)
def index(): """Returns standard text response to show app is working.""" return Response("wakie wakie is up and running!")
def index(): """Returns standard text response to show app is working.""" return Response("Bottle app up and running!")
def get_config_js(self): """ Return config for frontend **Example**:: window.CONFIG = { "default_language": "en", "show_region_info": true, "sentry": "http://*****:*****@sentry.ru/2", "region": "dev", "google_analytics": {"admin": "UA-62743660-2", "lk": "UA-62743660-1"}, "availability_zone": "local", "provider_info": {"support_email": "*****@*****.**", "site_url": "hosting.com", "support_phone": "+7 499 765-55-55"}, "support_subjects": ["Финансовые вопросы", "Технические вопросы"], "recaptcha_site_key": "6LdBgwgTAAAAAIf7gim356DhVC6TlaV-Yg3xkPGc", "horizon_url": "http://boss.ru/horizon", "version": "0.1.1" } """ provider = conf.provider.copy() if isinstance(provider["support_email"], list): provider["support_email"] = provider["support_email"][0] config = { "region": conf.region, "availability_zone": conf.availability_zone, "sentry": conf.sentry.js, "default_language": conf.ui.default_language, "show_region_info": conf.ui.show_region, "google_analytics": conf.ui.google_analytics, "support_subjects": conf.customer.support.subjects, "recaptcha_site_key": conf.api.secure.recaptcha.site_key, "provider_info": provider, "horizon_url": conf.openstack.horizon_url, "payments": { "cloudpayments": { "public_id": conf.payments.cloudpayments.public_id } }, "offer_link": conf.ui.offer_link, "promo_registration_only": conf.promocodes.promo_registration_only, "test_period": conf.customer.test_customer.test_period.blocking, "version": version("frontend_admin") if request_api_type() == API_ADMIN else version("frontend_cabinet"), "skyline": conf.skyline } response.content_type = "application/x-javascript" return Response("window.CONFIG = {};".format(json.dumps(config)))
def turn(state, relai_ch): lock_door.turn(state, int(relai_ch)) resp = Response(f"{datetime.now().strftime('%H:%M:%S')} {relai_ch} : {state}") resp.set_header('Access-Control-Allow-Origin', '*') return resp
def error404(error): return Response("Something went wrong :/")
def home(): html = Response("<html><body>Hello world</body></html>") return html
def index(): return Response("Hello, It works!")
def index(): """ Return a standard text response to show the app is up and running. """ return Response("Bottle app running!")
def Echo(): s = request.body.readline() self.assertEqual('abc', s) return Response(body=s, headers=[('Content-Type', 'application/json')], status='200 OK')
def fs(self, provider, userid, path, process=None, frmt=None): """ Args: provider: e.g. dropbox userid: a registered userid path: path to a filename (for creating/uploading/querying etc.) process (optional) : callback function to process the uploaded file descriptor and return a new file descriptor. This is used when extra content specific processing is required e.g. when record contents should be updated if there is a name conflict. """ #url unquote does not happend automatically path = urllib2.unquote(path) log.debug('fs( %s, %s, %s, %s, %s)' % (provider, userid, path, process, frmt)) #TODO: make a ProviderFactory class once we have >2 providers error = self.auth(provider, userid) #initializes self.provider if (error): return error method = self.request.method log.debug("Received %s request for userid : %s" % (method, userid)) try: ######## GET url is a directory -> List Directories ######## if method == "GET": md = self.provider.metadata(path) if md.is_dir(): msg = md.ls() return {"error": 0, "metadata": msg} ## GET url is a file -> Download file stream ######## else: if (provider == "local"): rpath = self.provider.realpath(path) log.debug("Serving static file: %s" % rpath) return static_file(os.path.basename(rpath), root=os.path.dirname(rpath)) else: #DROPBOX-specific error checks for editors and records. #TODO: Move outside /fs/ e.g. GET for /records/... #check here if there is an image part of and if image exists in dropbox httpres, metadata = self.provider.get_file_and_metadata( path) log.debug(metadata) body = httpres.read() headers = {} for name, value in httpres.getheaders(): if name != "connection": self.response[name] = value headers[name] = value log.debug(headers) if not "editors" in path: log.debug("not editors") if "image-" in body or "audio-" in body: log.debug("asset in record") obj = json.loads(body) log.debug(obj) for field in obj["properties"]["fields"]: if "image-" in field[ "id"] or "audio-" in field["id"]: res = self.provider.search( path.replace("record.json", ""), field["val"]) log.debug(len(res.md)) if len(res.md) == 0: log.debug("no such a file in dbox") self.response.status = 409 return { "error": 1, "msg": "The record is incomplete!" } #return httpres return Response(body=body, status='200 OK', headers=headers) else: #body = httpres.read() validator = FormValidator(body) if validator.validate(): log.debug("valid html5") if frmt == 'android': log.debug('it s an android') parser = COBWEBFormParser(body) body = parser.extract() return Response(body=body, status='200 OK', headers=headers) else: log.debug("non valid html5") self.response.status = 403 return { "error": 1, "msg": "The editor is not valid" } ######## PUT -> Upload/Overwrite file using dropbox rules ######## if method == "PUT": fp = self.request.body md = self.provider.upload(path, fp, overwrite=True) return {"error": 0, "msg": "File uploaded", "path": md.ls()} ######## POST -> Upload/Rename file using dropbox rules ######## if method == "POST": # POST needs multipart/form-data because that's what phonegap supports (but NOT dropbox) data = self.request.files.get('file') if data != None: log.debug("data not None") # if process is defined then pipe the body through process log.debug(data.filename) if data.filename.lower().endswith( ".jpg") or data.filename.lower().endswith(".jpeg"): body = data.file.read() fp = StringIO(body) if not process else process( data.file) paths = path.split(".") #give a new name to the resized image <name>_res.<extension> new_path = paths[0] + "_orig" + "." + paths[1] thumb_path = paths[0] + "_thumb" + "." + paths[1] md = self.provider.upload(new_path, fp) self.resizeImage(body, path) self.createThumb(body, thumb_path) else: fp = StringIO( data.file.read()) if not process else process( data.file) md = self.provider.upload(path, fp) return { "error": 0, "msg": "File uploaded", "path": md.ls() } else: log.debug("data is None") # if process is defined then pipe the body through process fp = self.request.body if not process else process( self.request.body) md = self.provider.upload(path, fp, overwrite=False) return { "error": 0, "msg": "File uploaded", "path": md.ls() } ####### DELETE file ############ if method == "DELETE": md = self.provider.file_delete(path) return {"error": 0, "msg": "%s deleted" % path} else: return {"error": 1, "msg": "invalid operation"} except Exception as e: # userid is probably invalid if not self.check_init_folders(path): log.exception("Exception: " + str(e)) return {"error": 1, "msg": str(e)}