Python bottle.response() Examples
The following are 24
code examples of bottle.response().
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
, or try the search function
.
Example #1
Source File: app.py From glim with MIT License | 6 votes |
def register_routes(self): """ Function creates instances of controllers, adds into bottle routes """ routes = self.flatten_urls(self.urls) self.controllers = {} controller_names = set() for route in routes: cname = route['endpoint'].split('.')[0] controller_names.add(cname) for cname in controller_names: attr = getattr(self.mcontrollers, cname) instance = attr(request, response) self.controllers[cname] = instance for route in routes: cname, aname = route['endpoint'].split('.') action = getattr(self.controllers[cname], aname) self.wsgi.route(route['url'], route['methods'], action)
Example #2
Source File: oauth2.py From bottle-oauthlib with BSD 3-Clause "New" or "Revised" License | 6 votes |
def create_metadata_response(self): def decorator(f): @functools.wraps(f) def wrapper(): assert self._oauthlib, "BottleOAuth2 not initialized with OAuthLib" uri, http_method, body, headers = extract_params(bottle.request) try: resp_headers, resp_body, resp_status = self._oauthlib.create_metadata_response( uri, http_method, body, headers ) except OAuth2Error as e: resp_headers, resp_body, resp_status = e.headers, e.json, e.status_code set_response(bottle.request, bottle.response, resp_status, resp_headers, resp_body, force_json=True) func_response = f() if func_response: return func_response return bottle.response return wrapper return decorator
Example #3
Source File: oauth2.py From bottle-oauthlib with BSD 3-Clause "New" or "Revised" License | 6 votes |
def create_introspect_response(self): def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): assert self._oauthlib, "BottleOAuth2 not initialized with OAuthLib" uri, http_method, body, headers = extract_params(bottle.request) try: resp_headers, resp_body, resp_status = self._oauthlib.create_introspect_response( uri, http_method, body, headers ) except OAuth2Error as e: resp_headers, resp_body, resp_status = e.headers, e.json, e.status_code set_response(bottle.request, bottle.response, resp_status, resp_headers, resp_body, force_json=True) func_response = f(*args, **kwargs) if func_response: return func_response return bottle.response return wrapper return decorator
Example #4
Source File: oauth2.py From bottle-oauthlib with BSD 3-Clause "New" or "Revised" License | 6 votes |
def create_userinfo_response(self): def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): assert self._oauthlib, "BottleOAuth2 not initialized with OAuthLib" uri, http_method, body, headers = extract_params(bottle.request) try: resp_headers, resp_body, resp_status = self._oauthlib.create_userinfo_response( uri, http_method=http_method, body=body, headers=headers ) except OAuth2Error as e: resp_headers, resp_body, resp_status = e.headers, e.json, e.status_code set_response(bottle.request, bottle.response, resp_status, resp_headers, resp_body, force_json=True) func_response = f(*args, **kwargs) if func_response: return func_response return bottle.response return wrapper return decorator
Example #5
Source File: gnomecast.py From gnomecast with GNU General Public License v3.0 | 6 votes |
def error_callback(self, msg): def f(): dialogWindow = Gtk.MessageDialog(self.win, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.INFO, Gtk.ButtonsType.OK, '\nGnomecast encountered an error converting your file.') dialogWindow.set_title('Transcoding Error') dialogWindow.set_default_size(1, 400) dialogBox = dialogWindow.get_content_area() buffer1 = Gtk.TextBuffer() buffer1.set_text(msg) text_view = Gtk.TextView(buffer=buffer1) text_view.set_editable(False) scrolled_window = Gtk.ScrolledWindow() scrolled_window.set_border_width(5) # we scroll only if needed scrolled_window.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) scrolled_window.add(text_view) dialogBox.pack_end(scrolled_window, True, True, 0) dialogWindow.show_all() response = dialogWindow.run() dialogWindow.destroy() GLib.idle_add(f)
Example #6
Source File: gnomecast.py From gnomecast with GNU General Public License v3.0 | 6 votes |
def on_download_subtitle_clicked(self): dialog = Gtk.FileChooserDialog("Please choose a subtitle file...", self.win, Gtk.FileChooserAction.OPEN, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK)) if self.fn: dialog.set_current_folder(os.path.dirname(self.fn)) filter_py = Gtk.FileFilter() filter_py.set_name("Subtitles") filter_py.add_pattern("*.srt") filter_py.add_pattern("*.vtt") dialog.add_filter(filter_py) response = dialog.run() if response == Gtk.ResponseType.OK: print("Open clicked") print("File selected: " + dialog.get_filename()) self.select_subtitles_file(dialog.get_filename()) elif response == Gtk.ResponseType.CANCEL: print("Cancel clicked") self.subtitle_combo.set_active(0) dialog.destroy()
Example #7
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 #8
Source File: gnomecast.py From gnomecast with GNU General Public License v3.0 | 6 votes |
def on_new_subtitle_clicked(self): dialog = Gtk.FileChooserDialog("Please choose a subtitle file...", self.win, Gtk.FileChooserAction.OPEN, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK)) if self.fn: dialog.set_current_folder(os.path.dirname(self.fn)) filter_py = Gtk.FileFilter() filter_py.set_name("Subtitles") filter_py.add_pattern("*.srt") filter_py.add_pattern("*.vtt") dialog.add_filter(filter_py) response = dialog.run() if response == Gtk.ResponseType.OK: print("Open clicked") print("File selected: " + dialog.get_filename()) self.select_subtitles_file(dialog.get_filename()) elif response == Gtk.ResponseType.CANCEL: print("Cancel clicked") self.subtitle_combo.set_active(0) dialog.destroy()
Example #9
Source File: webapi.py From RPi-InfoScreen-Kivy with GNU General Public License v3.0 | 5 votes |
def default(self): # Generic response for unknown requests result = self.api_error("Invalid method.") return json.dumps(result)
Example #10
Source File: __init__.py From NSC_BUILDER with MIT License | 5 votes |
def _set_response_headers(response): if _start_args['disable_cache']: # https://stackoverflow.com/a/24748094/280852 response.set_header('Cache-Control', 'no-store')
Example #11
Source File: __init__.py From NSC_BUILDER with MIT License | 5 votes |
def _static(path): response = None if 'jinja_env' in _start_args and 'jinja_templates' in _start_args: template_prefix = _start_args['jinja_templates'] + '/' if path.startswith(template_prefix): n = len(template_prefix) template = _start_args['jinja_env'].get_template(path[n:]) response = btl.HTTPResponse(template.render()) if response is None: response = btl.static_file(path, root=root_path) _set_response_headers(response) return response
Example #12
Source File: __init__.py From NSC_BUILDER with MIT License | 5 votes |
def _eel(): start_geometry = {'default': {'size': _start_args['size'], 'position': _start_args['position']}, 'pages': _start_args['geometry']} page = _eel_js.replace('/** _py_functions **/', '_py_functions: %s,' % list(_exposed_functions.keys())) page = page.replace('/** _start_geometry **/', '_start_geometry: %s,' % _safe_json(start_geometry)) btl.response.content_type = 'application/javascript' _set_response_headers(btl.response) return page
Example #13
Source File: gnomecast.py From gnomecast with GNU General Public License v3.0 | 5 votes |
def get_nonlocal_cast(self): dialogWindow = Gtk.MessageDialog(self.win, Gtk.DialogFlags.MODAL | Gtk.DialogFlags.DESTROY_WITH_PARENT, Gtk.MessageType.QUESTION, Gtk.ButtonsType.OK_CANCEL, '\nPlease specify the IP address or hostname of a Chromecast device:') dialogWindow.set_title('Add a non-local Chromecast') dialogBox = dialogWindow.get_content_area() userEntry = Gtk.Entry() # userEntry.set_size_request(250,0) dialogBox.pack_end(userEntry, False, False, 0) dialogWindow.show_all() response = dialogWindow.run() text = userEntry.get_text() dialogWindow.destroy() if (response == Gtk.ResponseType.OK) and (text != ''): print(text) try: cast = pychromecast.Chromecast(text) self.cast_store.append([cast, text]) self.cast_combo.set_active(len(self.cast_store)-1) except pychromecast.error.ChromecastConnectionError: dialog = Gtk.MessageDialog(self.win, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, "Chromecast Not Found") dialog.format_secondary_text("The Chromecast '%s' wasn't found." % text) dialog.run() dialog.destroy()
Example #14
Source File: gnomecast.py From gnomecast with GNU General Public License v3.0 | 5 votes |
def on_file_clicked(self, widget): dialog = Gtk.FileChooserDialog("Please choose an audio or video file...", self.win, Gtk.FileChooserAction.OPEN, (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OPEN, Gtk.ResponseType.OK)) dialog.set_select_multiple(True) downloads_dir = os.path.expanduser('~/Downloads') if os.path.isdir(downloads_dir): dialog.set_current_folder(downloads_dir) filter_py = Gtk.FileFilter() filter_py.set_name("Videos") filter_py.add_mime_type("video/*") filter_py.add_mime_type("audio/*") dialog.add_filter(filter_py) response = dialog.run() if response == Gtk.ResponseType.OK: print("Open clicked") print("File selected:", dialog.get_filenames()) self.queue_files(dialog.get_filenames()) #self.select_file(dialog.get_filename()) elif response == Gtk.ResponseType.CANCEL: print("Cancel clicked") dialog.destroy()
Example #15
Source File: gnomecast.py From gnomecast with GNU General Public License v3.0 | 5 votes |
def start_server(self): app = self.app @app.route('/subtitles.vtt') def subtitles(): # response = bottle.static_file(self.subtitles_fn, root='/', mimetype='text/vtt') response = bottle.response response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = 'GET, HEAD' response.headers['Access-Control-Allow-Headers'] = 'Content-Type' response.headers['Content-Type'] = 'text/vtt' return self.subtitles @app.get('/media/<id>.<ext>') def video(id, ext): print(list(bottle.request.headers.items())) ranges = list(bottle.parse_range_header(bottle.request.environ['HTTP_RANGE'], 1000000000000)) print('ranges', ranges) offset, end = ranges[0] self.transcoder.wait_for_byte(offset) response = bottle.static_file(self.transcoder.fn, root='/') if 'Last-Modified' in response.headers: del response.headers['Last-Modified'] response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = 'GET, HEAD' response.headers['Access-Control-Allow-Headers'] = 'Content-Type' return response # app.run(host=self.ip, port=self.port, server='paste', daemon=True) from paste import httpserver from paste.translogger import TransLogger handler = TransLogger(app, setup_console_handler=True) httpserver.serve(handler, host=self.ip, port=str(self.port), daemon_threads=True)
Example #16
Source File: __init__.py From Eel with MIT License | 5 votes |
def _eel(): start_geometry = {'default': {'size': _start_args['size'], 'position': _start_args['position']}, 'pages': _start_args['geometry']} page = _eel_js.replace('/** _py_functions **/', '_py_functions: %s,' % list(_exposed_functions.keys())) page = page.replace('/** _start_geometry **/', '_start_geometry: %s,' % _safe_json(start_geometry)) btl.response.content_type = 'application/javascript' _set_response_headers(btl.response) return page
Example #17
Source File: webapi.py From RPi-InfoScreen-Kivy with GNU General Public License v3.0 | 5 votes |
def api_error(self, message): """Base method for response to unsuccessful API calls.""" return {"status": "error", "message": message}
Example #18
Source File: webapi.py From RPi-InfoScreen-Kivy with GNU General Public License v3.0 | 5 votes |
def api_success(self, data): """Base method for response to successful API calls.""" return {"status": "success", "data": data}
Example #19
Source File: oauth2.py From bottle-oauthlib with BSD 3-Clause "New" or "Revised" License | 5 votes |
def create_authorization_response(self): def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): assert self._oauthlib, "BottleOAuth2 not initialized with OAuthLib" uri, http_method, body, headers = extract_params(bottle.request) scope = bottle.request.params.get('scope', '').split(' ') try: resp_headers, resp_body, resp_status = self._oauthlib.create_authorization_response( uri, http_method=http_method, body=body, headers=headers, scopes=scope ) except FatalClientError as e: if self._error_uri: raise bottle.HTTPResponse(status=302, headers={"Location": add_params_to_uri( self._error_uri, {'error': e.error, 'error_description': e.description} )}) raise e except OAuth2Error as e: resp_headers, resp_body, resp_status = e.headers, e.json, e.status_code set_response(bottle.request, bottle.response, resp_status, resp_headers, resp_body) func_response = f(*args, **kwargs) if func_response: return func_response return bottle.response return wrapper return decorator
Example #20
Source File: oauth2.py From bottle-oauthlib with BSD 3-Clause "New" or "Revised" License | 5 votes |
def create_token_response(self, credentials=None): def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): assert self._oauthlib, "BottleOAuth2 not initialized with OAuthLib" # Get any additional creds try: credentials_extra = credentials(bottle.request) except TypeError: credentials_extra = credentials uri, http_method, body, headers = extract_params(bottle.request) try: resp_headers, resp_body, resp_status = self._oauthlib.create_token_response( uri, http_method, body, headers, credentials_extra ) except OAuth2Error as e: resp_headers, resp_body, resp_status = e.headers, e.json, e.status_code set_response(bottle.request, bottle.response, resp_status, resp_headers, resp_body) func_response = f(*args, **kwargs) if func_response: return func_response return bottle.response return wrapper return decorator
Example #21
Source File: __init__.py From Eel with MIT License | 5 votes |
def _set_response_headers(response): if _start_args['disable_cache']: # https://stackoverflow.com/a/24748094/280852 response.set_header('Cache-Control', 'no-store')
Example #22
Source File: __init__.py From Eel with MIT License | 5 votes |
def _static(path): response = None if 'jinja_env' in _start_args and 'jinja_templates' in _start_args: template_prefix = _start_args['jinja_templates'] + '/' if path.startswith(template_prefix): n = len(template_prefix) template = _start_args['jinja_env'].get_template(path[n:]) response = btl.HTTPResponse(template.render()) if response is None: response = btl.static_file(path, root=root_path) _set_response_headers(response) return response
Example #23
Source File: app.py From aerial_wildlife_detection with MIT License | 4 votes |
def _initBottle(self): with open(os.path.abspath(os.path.join('modules/ProjectConfiguration/static/templates/projectConfiguration.html')), 'r') as f: self.projConf_template = SimpleTemplate(f.read()) @self.app.route('/config/static/<filename:re:.*>') def send_static(filename): return static_file(filename, root=self.staticDir) @self.app.route('/configuration') def configuration_page(): if self.loginCheck(True): username = html.escape(request.get_cookie('username')) response = self.projConf_template.render( username=username, projectTitle=self.config.getProperty('Project', 'projectName'), projectDescr=self.config.getProperty('Project', 'projectDescription'), numImagesPerBatch=self.config.getProperty('LabelUI', 'numImagesPerBatch'), minImageWidth=self.config.getProperty('LabelUI', 'minImageWidth') ) # response.set_header("Cache-Control", "public, max-age=604800") else: response = bottle.response response.status = 303 response.set_header('Location', '/') return response @self.app.post('/getProjectConfiguration') def get_project_configuration(): if not self.loginCheck(True): abort(401, 'forbidden') @self.app.post('/saveProjectConfiguration') def save_project_configuration(): if not self.loginCheck(True): abort(401, 'forbidden')
Example #24
Source File: oauth2.py From bottle-oauthlib with BSD 3-Clause "New" or "Revised" License | 4 votes |
def set_response(bottle_request, bottle_response, status, headers, body, force_json=False): """Set status/headers/body into bottle_response. Headers is a dict Body is ideally a JSON string (not dict). """ if not isinstance(headers, dict): raise TypeError("a dict-like object is required, not {0}".format(type(headers))) bottle_response.status = status for k, v in headers.items(): bottle_response.headers[k] = v """Determine if response should be in json or not, based on request: OAuth2.0 RFC recommands json, but older clients use form-urlencoded. Note also that force_json can be set to be compliant with specific endpoints like introspect, which always returns json. Examples: rauth: send Accept:*/* but work only with response in form-urlencoded. requests-oauthlib: send Accept:application/json but work with both responses types. """ if not body: return if not isinstance(body, str): raise TypeError("a str-like object is required, not {0}".format(type(body))) log.debug("Creating bottle response from string body %s...", body) try: values = json.loads(body) except json.decoder.JSONDecodeError: # consider body as string but not JSON, we stop here. bottle_response.body = body log.debug("Body Bottle response body created as is: %r", bottle_response.body) else: # consider body as JSON # request want a json as response if force_json is True or ( "Accept" in bottle_request.headers and "application/json" == bottle_request.headers["Accept"]): bottle_response["Content-Type"] = "application/json;charset=UTF-8" bottle_response.body = body log.debug("Body Bottle response body created as json: %r", bottle_response.body) else: from urllib.parse import quote bottle_response["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8" bottle_response.body = "&".join([ "{0}={1}".format( quote(k) if isinstance(k, str) else k, quote(v) if isinstance(v, str) else v ) for k, v in values.items() ]) log.debug("Body Bottle response body created as form-urlencoded: %r", bottle_response.body)