def dispatch_request(self, urls, request): """Dispatch the incoming *request* to the given view function or class. If the "request" is a socket.io message, route it to the registered namespace. :param urls: The URLs parsed by binding the URL map to the environment. :param request: The current HTTP request. :type request :class:`werkzeug.Request`: """ if request.path.startswith('/socket.io'): try: socketio_manage(request.environ, self._namespaces, request) except: print("Exception while handling socketio connection") return Response() else: response = urls.dispatch( lambda e, v: self._routes[e]( request, **v)) if isinstance(response, (unicode, str)): headers = {'Content-type': 'text/html'} response = Response(response, headers=headers) if not response: headers = {'Content-type': 'text/html'} response = Response('404 Not Found', headers=headers) response.status_code = 404 return response
def xml_response(doc): pywps_version_comment = '<!-- PyWPS %s -->\n' % __version__ xml = lxml.etree.tostring(doc, pretty_print=True) response = Response(pywps_version_comment.encode('utf8') + xml, content_type='text/xml') response.status_percentage = 100; return response
def wsgi_app(self, environ, start_response): route = self.router.bind_to_environ(environ) try: endpoint, args = route.match() except HTTPException as exc: return exc(environ, start_response) assert endpoint == "sublist" request = Request(environ) request.encoding_errors = "strict" if request.accept_mimetypes.quality("application/json") <= 0: raise NotAcceptable() result = list() for task_id in self.task_store._store.keys(): result.extend( self.scoring_store.get_submissions( args["user_id"], task_id ).values() ) result.sort(key=lambda x: (x.task, x.time)) result = list(a.__dict__ for a in result) response = Response() response.status_code = 200 response.mimetype = "application/json" response.data = json.dumps(result) return response(environ, start_response)
def wsgi_app(self, environ, start_response): """ Main WSGI Interface """ request = Request(environ) for route in self._routes: log.debug("Attempting route: %s", route) method = route.match(request.path, request.method) if method is None: continue ### EEW. Not sure I like this. extra_params = self._extract_params_from_request(method, request) value_map = method(**extra_params) if value_map is not None: # for now, we're doing dict only response = Response(mimetype="application/json") # EEW. It doesn't get any better on the response. self.apply_consumer_mutations(value_map, response) json_dump = json.dumps(value_map) response.data = json_dump return response(environ, start_response) raise NotFound()
def __get_response(self, environ, args, kwargs, endpoint): if endpoint.__name__ == "service_check": result = endpoint(*args, **kwargs) response = Response(result['body']) response.status_code = result['status'] return response response = { 'server_info': { 'http_headers': dict(EnvironHeaders(environ)), 'response_id': 0, 'arguments': repr(args) if args else repr(kwargs), 'processing_time': 0.0 }, 'response': {} } start_time = time.time() # Make the call result = endpoint(*args, **kwargs) # Send the API call response response['response'] = result response['server_info']['processing_time'] = 1000*(time.time() - start_time) try: response = json.dumps(response) except (TypeError, UnicodeError): return InternalServerError(description = "Could not encode service response") response = Response(response) response.headers['content-type'] = 'application/json' return response
def send_private_file(path): path = os.path.join(frappe.local.conf.get( 'private_path', 'private'), path.strip("/")) filename = os.path.basename(path) if frappe.local.request.headers.get('X-Use-X-Accel-Redirect'): path = '/protected/' + path response = Response() response.headers[b'X-Accel-Redirect'] = frappe.utils.encode(path) else: filepath = frappe.utils.get_site_path(path) try: f = open(filepath, 'rb') except IOError: raise NotFound response = Response( wrap_file(frappe.local.request.environ, f), direct_passthrough=True) # no need for content disposition and force download. let browser handle its opening. # response.headers.add(b'Content-Disposition', b'attachment', filename=filename.encode("utf-8")) response.mimetype = mimetypes.guess_type( filename)[0] or b'application/octet-stream' return response
def get_favicon(self, request): f = path.join(self.www_dp, 'icons', 'loris-icon.png') r = Response(file(f), content_type='image/x-icon') if self.enable_caching: r.add_etag() r.make_conditional(request) return r
def list_products(): status = 200 subcat = request.args['subcat'] resp_json = random.sample(subcat_dict[subcat], 100) response = Response(json.dumps(resp_json), mimetype="application/json", status=status) response.headers['Access-Control-Allow-Origin'] = '*' return response
def as_txt(): response = Response() response.mimetype = 'text' response.charset = 'utf-8' response.headers["Content-Disposition"] = ("attachment; filename=\"%s.txt\"" % frappe.response['doctype'].replace(' ', '_')).encode("utf-8") response.data = frappe.response['result'] return response
def test_proxy_fix(self): @Request.application def app(request): return Response('%s|%s' % ( request.remote_addr, # do not use request.host as this fixes too :) request.environ['HTTP_HOST'] )) app = fixers.ProxyFix(app, num_proxies=2) environ = dict( create_environ(), HTTP_X_FORWARDED_PROTO="https", HTTP_X_FORWARDED_HOST='example.com', HTTP_X_FORWARDED_FOR='1.2.3.4, 5.6.7.8', REMOTE_ADDR='127.0.0.1', HTTP_HOST='fake' ) response = Response.from_app(app, environ) assert response.get_data() == b'1.2.3.4|example.com' # And we must check that if it is a redirection it is # correctly done: redirect_app = redirect('/foo/bar.hml') response = Response.from_app(redirect_app, environ) wsgi_headers = response.get_wsgi_headers(environ) assert wsgi_headers['Location'] == 'https://example.com/foo/bar.hml'
def redirect(location, code=302): """Return a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it's not a real redirect and 304 because it's the answer for a request with a request with defined If-Modified-Since headers. .. versionadded:: 0.6 The location can now be a unicode string that is encoded using the :func:`iri_to_uri` function. :param location: the location the response should redirect to. :param code: the redirect status code. defaults to 302. """ from werkzeug.wrappers import Response display_location = escape(location) if isinstance(location, text_type): from werkzeug.urls import iri_to_uri location = iri_to_uri(location) response = Response( '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">\n' '<title>Redirecting...</title>\n' '<h1>Redirecting...</h1>\n' '<p>You should be redirected automatically to target URL: ' '<a href="%s">%s</a>. If not click the link.' % (escape(location), display_location), code, mimetype='text/html') response.headers['Location'] = location return response
def run_application(self, environment: dict, start_response: typing.Callable) -> asyncio.Task: """ Runs Kyoukai for the current request. This is **not** a coroutine - it returns a single item (a Task), which is awaited on to get the response. :param environment: The WSGI environment to run this request with. :param start_response: A callable that can be used to start the response. :return: A new :class:`asyncio.Task` that can be awaited on to get a response from the \ application. """ is_async = environment.get("wsgi.async", False) if not is_async: # Damnit. Return a WSGI response that ells the user they're stupid. r = Response("<h1>Error</h1><br/>You did not use the <code>gaiohttp</code> " "gunicorn worker. This is an " "error! Please switch to the gaiohttp worker instead.") r.headers["Content-Type"] = "text/html; charset=utf-8" r.status_code = 500 return r(environment, start_response) coro = self._run_application(environment, start_response) loop = asyncio.get_event_loop() t = loop.create_task(coro) environment["kyoukai.task"] = t return t
def wsgi_app(self, environ, start_response): """Execute this instance as a WSGI application. See the PEP for the meaning of parameters. The separation of __call__ and wsgi_app eases the insertion of middlewares. """ urls = self._url_map.bind_to_environ(environ) try: endpoint, args = urls.match() except HTTPException as exc: return exc assert endpoint == "get" request = Request(environ) request.encoding_errors = "strict" response = Response() result = dict() for task_type in self._task_types: result[task_type.__name__] = \ list(p.describe() for p in task_type.ACCEPTED_PARAMETERS) response.status_code = 200 response.mimetype = "application/json" response.data = json.dumps(result) return response
def refine(): pog_ids = []; target_cat = request.args['target_cat'] if target_cat == "top": if 'footwear_pog_id' in request.args: footwear_pog_id = request.args['footwear_pog_id'] pog_ids = nn_dict[footwear_pog_id]['top'] elif 'bottom_pog_id' in request.args: bottom_pog_id = request.args['bottom_pog_id'] pog_ids = nn_dict[bottom_pog_id]['top'] elif target_cat == "bottom": if 'footwear_pog_id' in request.args: footwear_pog_id = request.args['footwear_pog_id'] pog_ids = nn_dict[footwear_pog_id]['bottom'] elif 'top_pog_id' in request.args: top_pog_id = request.args['top_pog_id'] pog_ids = nn_dict[top_pog_id]['bottom'] elif target_cat == "footwear": if 'bottom_pog_id' in request.args: bottom_pog_id = request.args['bottom_pog_id'] pog_ids = nn_dict[bottom_pog_id]['footwear'] elif 'top_pog_id' in request.args: top_pog_id = request.args['top_pog_id'] pog_ids = nn_dict[top_pog_id]['footwear'] data = {target_cat: [pog_dict[pog_id]['details'] for pog_id in pog_ids]} status = 200 response = Response(json.dumps(data), mimetype="application/json", status=status) response.headers['Access-Control-Allow-Origin'] = '*' return response
def _try_special_request(self, environ, request): static_mount = '/__piecrust_static/' if request.path.startswith(static_mount): rel_req_path = request.path[len(static_mount):] mount = os.path.join(RESOURCES_DIR, 'server') full_path = os.path.join(mount, rel_req_path) try: response = self._make_wrapped_file_response( environ, request, full_path) return response except OSError: pass debug_mount = '/__piecrust_debug/' if request.path.startswith(debug_mount): rel_req_path = request.path[len(debug_mount):] if rel_req_path == 'pipeline_status': from piecrust.serving.procloop import ( PipelineStatusServerSideEventProducer) provider = PipelineStatusServerSideEventProducer( self._proc_loop.status_queue) it = ClosingIterator(provider.run(), [provider.close]) response = Response(it) response.headers['Cache-Control'] = 'no-cache' if 'text/event-stream' in request.accept_mimetypes: response.mimetype = 'text/event-stream' response.direct_passthrough = True response.implicit_sequence_conversion = False return response return None
def get_pog_info(): pog_ids = request.args.getlist('pog_ids') resp_json = [pog_dict[pog_id]['details'] for pog_id in pog_ids] status = 200 response = Response(json.dumps(resp_json), mimetype="application/json", status=status) response.headers['Access-Control-Allow-Origin'] = '*' return response
def index(self, request): # werkzeug have a low level session support, # you need send session id to browser cookie manually sid = request.cookies.get(self.COOKIE_NAME) if sid is None: # don't have a session id, create new session request.session = session_store.new() else: request.session = session_store.get_session(sid) if self.LUCKY_NUM_KEY in request.session: lucky_num = request.session[self.LUCKY_NUM_KEY] else: # random a new lucky number, # then store it in session # when user access again, will use the same lucky number lucky_num = random.randint(1, 10) request.session[self.LUCKY_NUM_KEY] = lucky_num response = Response('Hello, your lucky number is: %s' % (lucky_num,)) if sid is None: # if the user don't have a session id, # don't forgot send session id to cookie response.set_cookie(self.COOKIE_NAME, request.session.sid) # and you should save session manually if request.session.should_save: session_store.set(request.session.sid, dict(request.session)) return response
def __call__(self, environ, start_response): path = environ.get('PATH_INFO') or '/' method = environ.get('REQUEST_METHOD') request = Request(environ) response = Response() if method == 'POST': # trap all post requests for example content_type_header = request.headers.get('Content-Type') if not content_type_header: response.status_code = 405 return response(environ, start_response) transport = TIOStreamTransport(request.stream, response.stream) if 'application/x-thrift' in content_type_header: protocol = TBinaryProtocol.TBinaryProtocol(transport) elif 'application/json' in content_type_header: protocol = TJSONProtocol.TJSONProtocol(transport) else: response.status_code = 405 return response(environ, start_response) self.bb_processor.process(protocol, protocol) return response(environ, start_response) else: return self.app(environ, start_response)
def handle(self, request): request.app = self response = self.dashboard(request) if isinstance(response, str): response = Response(response) response.headers['Content-Type'] = 'text/html' return response
def as_binary(): response = Response() response.mimetype = 'application/octet-stream' response.headers[b"Content-Disposition"] = ( "filename=\"%s\"" % frappe.response['filename'].replace(' ', '_')).encode("utf-8") response.data = frappe.response['filecontent'] return response
def ignored_callback(environ, start_response): response = Response('{"Error":"NotAuthenticated"}') # response.status = '401 Unauthorized' response.status = '200 OK' response.headers['Content-Type'] = 'application/json' return response(environ, start_response)
def wsgi_app(self, environ, start_response): route = self.router.bind_to_environ(environ) try: endpoint, args = route.match() except HTTPException as exc: return exc request = Request(environ) request.encoding_errors = "strict" response = Response() response.headers[b'X-Frame-Options'] = b'SAMEORIGIN' try: if endpoint == "get": self.get(request, response, args["key"]) elif endpoint == "get_list": self.get_list(request, response) elif endpoint == "put": self.put(request, response, args["key"]) elif endpoint == "put_list": self.put_list(request, response) elif endpoint == "delete": self.delete(request, response, args["key"]) elif endpoint == "delete_list": self.delete_list(request, response) else: raise RuntimeError() except HTTPException as exc: return exc return response
def test_date_no_clobber(self): r = Response() r.date = 0 r.last_modified = 0 v.add_date_fields(r) self.assertEquals(r.date.year, 1970) self.assertEquals(r.last_modified.year, 1970)
def cookie_app(environ, start_response): """A WSGI application which sets a cookie, and returns as a response any cookie which exists. """ response = Response(environ.get("HTTP_COOKIE", "No Cookie"), mimetype="text/plain") response.set_cookie("test", "test") return response(environ, start_response)
def application(request): if request.method == 'GET': path = list(filter((lambda x: len(x) > 0), re.split('/+', request.path))) if len(path) == 0: return view_root(request) elif len(path) >= 1 and path[0] == 'messages': if len(path) == 1: return view_messages_list(request) elif len(path) == 2: return view_message(request, path[1]) elif len(path) == 3 and path[2] == 'editor': return edit_message(request, path[1]) else: return NotFound() elif len(path) >= 1 and path[0] == 'services': if len(path) == 1: return view_services_list(request) elif len(path) == 2: return view_ports_list(request, path[1]) elif len(path) == 3: return view_operations_list(request, path[1], path[2]) else: return NotFound() else: return NotFound() elif request.method == 'POST': return Response('post') else: response = Response() response.status_code = 400 return response
def application(request): logger = logging.getLogger('presence_detection') logger.setLevel(logging.INFO) fh = logging.FileHandler(os.path.expanduser('~/presence2/log/presence_detection.log'),mode='a', encoding=None, delay=False) formatter = logging.Formatter('%(asctime)s - %(levelname)r - %(message)s') fh.setFormatter(formatter) logger.addHandler(fh) rsa_key='AAAAB3NzaC1yc2EAAAADAQABAAAAgwCjvHkbqL/V0ytnfa5pIak7bxBfj6nF4S7vy51ZG8LlWYAXcQ9WGfUGfhG+l1GW9hPeQzQbeRyNiQM+ufue/M9+JKCXTIugksAnN3W+NV/DeDcq9sKR9MiiNH3ZeNtGSyPGYjcLVmK6aSVTUoEO2yRrha9fiWBy5hb93UdmJX+QguC9' router_address='makerbar.berthartm.org' router_port = 2222 stdin, stdout, stderr =get_router_mac_addresses(rsa_key,router_address,router_port) usermap = get_dict() attendance = set() for line in stdout: MAC = line[10:27] if MAC in usermap: attendance.add(usermap[MAC]) logger.info('%s (%s) is at the MakerBar.' % (usermap[MAC],MAC)) else: logger.info('Unknown user(%s) is at the MakerBar.' % MAC) output = '' for user in attendance: output += user + '\n' response = Response(output) if output == '': response.status_code = 204 # No content fh.close() return response
def __build_response(self, output): res = Response(output) res.content_type = self.content_type res.expires = datetime.today() + timedelta(7) for header, value in self.__headers: res.headers[header] = value return res
def index(self, request, file_name, file_data): pdf_data = open(file_data,'rb').read() response = Response(pdf_data) response.headers['Content-Type'] = 'application/pdf' #response.headers['Content-Disposition'] = 'attachment; filename="%s.pdf"'%file_name response.headers['Content-Disposition'] = content_disposition(file_name, request) return response
def response(self): try: return self._getStaticResponse() except (OSError, IOError): rs = Response('Not found') rs.status_code = 404 return rs
def cookie_app(environ, start_response): """A WSGI application which sets a cookie, and returns as a ersponse any cookie which exists. """ response = Response(environ.get('HTTP_COOKIE', 'No Cookie'), mimetype='text/plain') response.set_cookie('test', 'test') return response(environ, start_response)
def render_template(self, template_name, **context): t = self.jinja_env.get_template(template_name) return Response(t.render(context), mimetype="text/html")
def paste_traceback(self, request, traceback): """Paste the traceback and return a JSON response.""" paste_id = traceback.paste() return Response('{"url": "http://paste.pocoo.org/show/%s/", "id": %s}' % (paste_id, paste_id), mimetype='application/json')
def register_user_availability(self, request): data = json.loads(request.get_data(as_text=True)) response = self.users_rpc.register_availability(data) return Response(status=response['status'], mimetype='text/plain')
def default(self, environ, start_response): resp = Response("\n".join(self.isso.keys()), 404, content_type="text/plain") return resp(environ, start_response)
def execute_command(self, request, command, frame): """Execute a command in a console.""" return Response(frame.console.eval(command), mimetype='text/html')
def app(request): return Response('%s|%s' % ( request.remote_addr, # do not use request.host as this fixes too :) request.environ['HTTP_HOST']))
def path_check_app(request): return Response('PATH_INFO: %s\nSCRIPT_NAME: %s' % (request.environ.get( 'PATH_INFO', ''), request.environ.get('SCRIPT_NAME', '')))
def multi_value_post_app(environ, start_response): req = Request(environ) assert req.form['field'] == 'val1', req.form['field'] assert req.form.getlist('field') == ['val1', 'val2'], req.form.getlist('field') response = Response('ok') return response(environ, start_response)
def external_subdomain_redirect_demo_app(environ, start_response): if 'test.example.com' in environ['HTTP_HOST']: response = Response('redirected successfully to subdomain') else: response = redirect('http://test.example.com/login') return response(environ, start_response)
def get_colors(self): custom_css = '' current_user = request.env['res.users'].sudo().search([('id', '=', request.context.get('uid'))]) if current_user and current_user[0].company_color_theme: custom_css = current_user[0].company_color_theme.css return Response(str(custom_css), mimetype='text/css')
def render_template(template, **context): return Response(jinja_env.get_template(template).render(**context), mimetype='text/html')
def dispatch_request(self, environ): request = environ['leanengine.request'] app_params = environ['_app_params'] adapter = self.url_map.bind_to_environ(request.environ) try: endpoint, values = adapter.match() except HTTPException as e: return e params = request.get_data(as_text=True) values['params'] = json.loads(params) if params != '' else {} try: if endpoint == 'cloud_function': result = { 'result': dispatch_cloud_func(self.cloud_codes, app_params, decode_object=False, **values) } elif endpoint == 'rpc_function': result = { 'result': dispatch_cloud_func(self.cloud_codes, app_params, decode_object=True, **values) } elif endpoint == 'cloud_hook': result = dispatch_cloud_hook(self.cloud_codes, app_params, **values) elif endpoint == 'on_verified': result = { 'result': dispatch_on_verified(self.cloud_codes, app_params, **values) } elif endpoint == 'on_login': result = { 'result': dispatch_on_login(self.cloud_codes, app_params, **values) } elif endpoint == 'ops_meta_data': from .authorization import MASTER_KEY if request.environ.get('_app_params', {}).get('master_key') != MASTER_KEY: raise LeanEngineError(code=401, message='Unauthorized.') result = {'result': dispatch_ops_meta_data(self.cloud_codes)} elif endpoint == 'on_bigquery': result = { 'result': dispatch_on_bigquery(self.cloud_codes, app_params, **values) } else: raise ValueError # impossible return Response(json.dumps(result), mimetype='application/json') except LeanEngineError as e: return Response(json.dumps({ 'code': e.code, 'error': e.message }), status=e.code if e.code else 400, mimetype='application/json') except Exception: print(traceback.format_exc(), file=sys.stderr) return Response(json.dumps({ 'code': 141, 'error': 'Cloud Code script had an error.' }), status=500, mimetype='application/json')
def test_expected_request_response(httpserver: HTTPServer): httpserver.expect_request("/foobar").respond_with_response(Response(JSON_STRING)) assert requests.get(httpserver.url_for("/foobar")).json() == {'foo': 'bar'}
def __call__(self, environ, start_response): if wsgi.get_path_info(environ).startswith(self._prefixes): resp = Response(self._template, status=451, mimetype='text/html') return resp(environ, start_response) return self.application(environ, start_response)
def h_full_response(_): return Response(self.raw_data, status=requests.codes.OK)
def test_app(request): return Response(request.form.get('x', None))
def app(request): return Response(request.remote_addr)
def test_app(request): return Response(request.args['x'])
def test_cgi_root_fix_custom_app_root(self): app = fixers.CGIRootFix(path_check_app, app_root='/baz/poop/') response = Response.from_app( app, dict(create_environ(), SCRIPT_NAME='/foo', PATH_INFO='/bar')) self.assert_equal(response.get_data(), b'PATH_INFO: /foo/bar\nSCRIPT_NAME: baz/poop')
def test_app(request): return Response(str(request.environ['werkzeug._foo']))
def application(request): return Response("", headers=[('X-Foo', 'bar')])
def test_app(request): response = Response(repr(sorted(request.cookies.items()))) response.set_cookie(u'test1', b'foo') response.set_cookie(u'test2', b'bar') return response
def display_console(self, request): """Display a standalone shell.""" if 0 not in self.frames: self.frames[0] = _ConsoleFrame(self.console_init_func()) return Response(render_template('console.html'), mimetype='text/html')
def application(environ, start_response): response = Response('Hello World!', mimetype='text/plain') return response(environ, start_response)
def get_source(self, request, frame): """Render the source viewer.""" return Response(frame.render_source(), mimetype='text/html')
def dispatch_request(self, request): return Response('Hello World')
def get_user_availability(self, request, user_id): response = self.users_rpc.get_availability(user_id) return Response(json.dumps({'availability': response['availability']}), status=response['status'], mimetype='text/plain')
def error_response(self, exception, trace): return Response(trace, status='500 not ok (%s)' % exception)
def on_logout(self, request): return Response( response="You are logged out.", status=401, )
def get_users_by_role(self, request, role): response = self.users_rpc.get_by_role(role) return Response(json.dumps({'users': response['users']}), status=response['status'], mimetype='text/plain')