def view_file(req): if not 'uploaded_file' in req.files: return BaseResponse('no file uploaded') f = req.files['uploaded_file'] return BaseResponse(wrap_file(req.environ, f), mimetype=f.content_type, direct_passthrough=True)
def template_viewer(environ, start_response): prefix, path_info = config.url_prefix, environ['PATH_INFO'] if not os.path.dirname(path_info).startswith(prefix.rstrip('/')): raise NotFound() path_info = path_info[len(prefix):] if path_info.endswith('/'): path_info += config.index_document fspath = os.path.join(config.dynamic_path, path_info.lstrip('/')) if not os.path.exists(fspath): raise NotFound() elif os.path.isdir(fspath): return append_slash_redirect(environ) template = loader.get_template(path_info) mimetype, _ = mimetypes.guess_type(path_info) mimetype = mimetype or 'text/plain' render_environ = dict(environ, PATH_INFO=path_info) render_environ['SCRIPT_NAME'] += prefix response = BaseResponse(mimetype=mimetype or 'text/plain') response.data = template.render(config=config, environ=environ) response.headers['Pragma'] = 'no-cache' response.headers['Cache-Control'] = 'no-cache, must-revalidate' response.headers['Expires'] = 'Sun, 13 Aug 1995 13:00:00 GMT' return response
def _open(self, url, method='GET', data=None, refer=True, content_type=None): before_browser_activity.send(self) open_started = time() environ = self._create_environ(url, method, data, refer, content_type) # keep a copy, the app may mutate the environ request_environ = dict(environ) logger.info('%s(%s) == %s', method, url, request_uri(environ)) request_started = time() rv = run_wsgi_app(self._wsgi_app, environ) response = BaseResponse(*rv) # TODO: # response.make_sequence() # werkzeug 0.6+ # For now, must: response.response = list(response.response) if hasattr(rv[0], 'close'): rv[0].close() # end TODO # request is complete after the app_iter (rv[0]) has been fully read + # closed down. request_ended = time() self._request_environ = request_environ self._cookie_jar.extract_from_werkzeug(response, environ) self.status_code = response.status_code # Automatically follow redirects if 301 <= self.status_code <= 302: logger.debug("Redirect to %s", response.headers['Location']) after_browser_activity.send(self) self._open(response.headers['Location']) return # redirects report the original referrer self._referrer = request_uri(environ) self.status = response.status self.headers = response.headers # TODO: unicodify self.response = response.data self._sync_document() # TODO: what does a http-equiv redirect report for referrer? if 'meta[http-equiv=refresh]' in self.document: refresh = self.document['meta[http-equiv=refresh]'][0] if 'content' in refresh.attrib: parts = refresh.get('content').split(';url=', 1) if len(parts) == 2: logger.debug("HTTP-EQUIV Redirect to %s", parts[1]) after_browser_activity.send(self) self._open(parts[1]) return open_ended = time() request_time = request_ended - request_started logger.info("Fetched %s in %0.3fsec + %0.3fsec browser overhead", url, request_time, open_ended - open_started - request_time) after_browser_activity.send(self)
def __init__(self, response=None, status=200, headers=None, mimetype=None, content_type=None): if isinstance(response, Stream): response = response.render('html', encoding=None, doctype='html') BaseResponse.__init__(self, response, status, headers, mimetype, content_type)
def handle_request(self, request): if request.method == 'POST': response = self._marshaled_dispatch(request.data) return BaseResponse(response, mimetype='application/xml') return BaseResponse('\n'.join(( '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">', '<title>XMLRPC Interface</title>', '<h1>XMLRPC Interface</h1>', '<p>This URL provides an XMLRPC interface. You have to ' 'connect to it using an XMLRPC client.</p>' )), 405, [('Allow', 'POST'), ('Content-Type', 'text/html')])
def view_file(req): if not 'uploaded_file' in req.files: return BaseResponse('no file uploaded') f = req.files['uploaded_file'] def stream(): while 1: data = f.read(65536) if not data: break yield data return BaseResponse(stream(), mimetype=f.content_type)
def __call__(self, *args, **kwargs): data = self.view_function(*args, **kwargs) if self.renderers is None: return data #Search the best renderer media_type = request.accept_mimetypes.best_match( [renderer.media_type for renderer in self.renderers], None) if media_type is None: abort(status.HTTP_406_NOT_ACCEPTABLE) renderer = filter(lambda x: x.media_type == media_type, self.renderers)[0] #preliminary response class to pass to the renderer beta_response = BaseResponse() #Render the result of the view function rendered_content = renderer.render( data, media_type, { 'request': request, 'response': beta_response, 'view': self.view_function, 'renderers': self.renderers }) #Create a matching response response = current_app.response_class(rendered_content, mimetype=media_type) return response
def upload_file(req): return BaseResponse(''' <h1>Upload File</h1> <form action="" method="post" enctype="multipart/form-data"> <input type="file" name="uploaded_file"> <input type="submit" value="Upload"> </form> ''', mimetype='text/html')
def dispatch_request(environ, start_response): adapter = url_map.bind_to_environ(environ) endpoint, values = adapter.match() if endpoint == "index": try: endpoint, values = adapter.match() request = BaseRequest(environ) response = BaseResponse(mimetype='text/html') response.data = "Pipeline home page" return response except HTTPException, e: return e
def application(environ, start_response): request = Request(environ) response = BaseResponse({ 'get': get_time, 'set': set_time }.get(request.path.strip('/'), index)(request), mimetype='text/html') request.session.save_cookie(response) return response(environ, start_response)
def dispatch_request(environ, start_response): """ A simple dispatch function that (if decorated with responder) is the complete WSGI application that does the template rendering and error handling. """ # first we bind the url map to the current request adapter = url_map.bind_to_environ(environ) # then we wrap all the calls in a try/except for HTTP exceptions try: # get the endpoint and the values (variable or parts) # of the adapter. If the match fails it raises a NotFound # exception which is a HTTPException which we catch endpoint, values = adapter.match() # create a new request object for the incoming WSGI environ request = BaseRequest(environ) # create an empty response object with the correct mimetype. response = BaseResponse(mimetype='text/html') # get the template and render it. Pass some useful stuff to # the template (request and response objects, the current # url endpoint, the url values and a url_for function which # can be used to generate urls template = domain.get_template(endpoint + '.html') response.write(template.evoque( request=request, response=response, endpoint=endpoint, url_for=lambda e, **v: adapter.build(e, v), url_values=values )) # return the response return response except HTTPException, e: # if an http exception is caught we can return it as # response because those exceptions render standard error # messages under wsgi return e
def dispatch_request(environ, start_response): """ A simple dispatch function that (if decorated with responder) is the complete WSGI application that does the template rendering and error handling. """ # first we bind the url map to the current request adapter = url_map.bind_to_environ(environ) # then we wrap all the calls in a try/except for HTTP exceptions try: # get the endpoint and the values (variable or parts) # of the adapter. If the match fails it raises a NotFound # exception which is a HTTPException which we catch endpoint, values = adapter.match() # create a new request object for the incoming WSGI environ request = BaseRequest(environ) # create an empty response object with the correct mimetype. response = BaseResponse(mimetype='text/html') # get the template and render it. Pass some useful stuff to # the template (request and response objects, the current # url endpoint, the url values and a url_for function which # can be used to generate urls template = domain.get_template(endpoint + '.html') response.write(template.evoque( request=request, response=response, endpoint=endpoint, url_for=lambda e, **v: adapter.build(e, v), url_values=values )) # return the response return response except HTTPException as e: # if an http exception is caught we can return it as # response because those exceptions render standard error # messages under wsgi return e
def test_appstats_middleware(self): request = Request({}) middleware = AppStatsMiddleware() r = middleware.process_request(request) self.assertTrue(r is None) r = middleware.process_response(request, BaseResponse("", 200)) self.assertTrue(isinstance(r, BaseResponse)) summary = recording.load_summary_protos() self.assert_(summary)
def not_found(self): # Change me. response = BaseResponse("HTTP 404") response.status = 404 return response
def foo(environ, start_response): return BaseResponse('Test')