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 download_hard(cluster): g = get_network_from_cluster(cluster) hard = cluster_hard(g) s = str(hard) r = Response(body=s, status=200) r.set_header('Content-Type', 'text/txt') r.set_header('Content-Disposition', 'attachment; filename="phylonetwork_soft.txt"') return r
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 handler(self, request: Request, response: Response, *args, **kwargs): handler = getattr(self, request.method.lower(), None) if handler is None: response.status = 401 response.content_type = 'application/json' response.body = '{"code": 401, "message": "method not allowed"}' return response return handler(request, response, *args, **kwargs)
def install(): data = { "command" : "Install", "result" : None } data["result"] = driver.install(request.json) response = Response(json.dumps(data, sort_keys = True, indent = 4)) response.mimetype = "server/json" return response
def disconnect(): data = { "command" : "Disconnect", "result" : None } data["result"] = driver.disconnect() response = Response(json.dumps(data, sort_keys = True, indent = 4)) response.mimetype = "server/json" return response
def stop(): data = { "command" : "Stop", "result" : None } data["result"] = driver.stop() response = Response(json.dumps(data, sort_keys = True, indent = 4)) response.mimetype = "server/json" return response
def play(SLOT): data = { "command" : "Play", "slot" : SLOT, "result" : None } data["result"] = driver.play(SLOT) response = Response(json.dumps(data, sort_keys = True, indent = 4)) response.mimetype = "server/json" return response
def enable_cors(request: Request, response: Response, allow_credentials: bool = True, max_age: int = 86400) -> bool: """ This function detects whether the request is a cross-origin request or a preflight request based on certain characteristic headers, and then adds the corresponding response headers as needed. :param request: The bottle.request object (current request). :param response: The bottle.response object. :param allow_credentials: A bool flag indicates whether to send the response header "Access-Control-Allow-Credentials: true", if the request is a cross-origin request. :param max_age: The number of seconds that the results of the preflight request can be cached, if the request is a preflight request. :return: A Boolean value tells the caller whether the request is just a preflight request, so no further processing is required. """ is_preflight = False origin = request.get_header('Origin') if not origin: return is_preflight host = request.get_header('Host') if not host: host = request.urlparts.netloc if origin.lower().endswith('//' + host.lower()): return is_preflight response.set_header('Access-Control-Allow-Origin', origin) if allow_credentials: response.set_header('Access-Control-Allow-Credentials', 'true') if request.method == 'OPTIONS': cors_method = request.get_header('Access-Control-Request-Method') if cors_method: response.set_header('Access-Control-Allow-Methods', cors_method) if max_age: response.set_header('Access-Control-Max-Age', str(max_age)) is_preflight = True cors_headers = request.get_header('Access-Control-Request-Headers') if cors_headers: response.set_header('Access-Control-Allow-Headers', cors_headers) return is_preflight
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 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 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 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 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 handle(self, req: Request, resp: Response) -> str: if req.method == "GET": if self.app.oauth_flow is not None: oauth_flow: OAuthFlow = self.app.oauth_flow if req.path == oauth_flow.install_path: bolt_resp = oauth_flow.handle_installation(to_bolt_request(req)) set_response(bolt_resp, resp) return bolt_resp.body or "" elif req.path == oauth_flow.redirect_uri_path: bolt_resp = oauth_flow.handle_callback(to_bolt_request(req)) set_response(bolt_resp, resp) return bolt_resp.body or "" elif req.method == "POST": bolt_resp: BoltResponse = self.app.dispatch(to_bolt_request(req)) set_response(bolt_resp, resp) return bolt_resp.body or "" resp.status = 404 return "Not Found"
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)
@route("/network/<cluster>/soft/download") def download_soft(cluster): g = get_network_from_cluster(cluster) async = not DEBUG q = Queue(connection=Redis(), default_timeout=60*15, async=async) job = q.enqueue(cluster_soft, g) for i in range(10): if not job.result: time.sleep(5) else: break else: redirect("/?error='problem generating the file'") s = str(job.result) r = Response(body=s, status=200) r.set_header('Content-Type', 'text/txt') r.set_header('Content-Disposition', 'attachment; filename="phylonetwork_soft.txt"') return r ### # Queues and jobs @route("/job/families/<queue_key>/<job_id>") def process_job_treechild(queue_key, job_id): redis_connection = Redis() q = Queue.from_queue_key(queue_key, redis_connection) job = q.safe_fetch_job(job_id) if job.result != None: # This construction may seem weird but the tree-child families may return # empty so we cannot just check against «if job.result» if not job.result:
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 index(): """ Return a standard text response to show the app is up and running. """ return Response("Bottle app running!")
def set_response(bolt_resp: BoltResponse, resp: Response) -> None: resp.status = bolt_resp.status for k, values in bolt_resp.headers.items(): for v in values: resp.add_header(k, v)
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 home(): html = Response("<html><body>Hello world</body></html>") return html
def index(): return Response("Hello, It works!")
def error404(error): return Response("Something went wrong :/")
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)}