def make_request(key, user_id, issue_time): return MockRequest( Headers([('x-annotator-consumer-key', key), ('x-annotator-auth-token', make_token(key, user_id, issue_time)), ('x-annotator-auth-token-issue-time', issue_time), ('x-annotator-user-id', user_id)]))
def send_file(): h = Headers() h.add('Content-type', 'application/octet-stream', charset='utf8') h.add('Content-disposition', 'attachment', filename='name.tar.gz') return Response(open( os.path.join(os.path.dirname(__file__), 'static', 'foo.tar.gz'), 'r'), headers=h)
def match_download(id): match = model.Match.get_by_id(id) match_data = model.MatchData.get_by_id(id) abort_if(not match) abort_if(not match_data) data = match_data.raw_data abort_if(not data) print len(data) from werkzeug import Headers import time headers = Headers() headers.add('Content-Disposition', 'attachment', filename=match.filename) rv = current_app.response_class( data, mimetype='application/octet-stream', headers=headers, direct_passthrough=True, ) rv.cache_control.public = True rv.cache_control.max_age = 86400 rv.expires = int(time.time() + 86400) return rv
def json_response(self, filename='export.json'): serializer = Serializer() prepared_query = self.prepare_query() field_dict = {} for field in prepared_query._select: field_dict.setdefault(field.model_class, []) field_dict[field.model_class].append(field.name) def generate(): i = prepared_query.count() yield '[\n' for obj in prepared_query: i -= 1 yield json.dumps(serializer.serialize_object(obj, field_dict)) if i > 0: yield ',\n' yield '\n]' headers = Headers() headers.add('Content-Type', 'application/javascript') headers.add('Content-Disposition', 'attachment; filename=%s' % filename) return Response(generate(), mimetype='text/javascript', headers=headers, direct_passthrough=True)
def check_start_response(self, status, headers, exc_info): check_string('status', status) status_code = status.split(None, 1)[0] if len(status_code) != 3 or not status_code.isdigit(): warn(WSGIWarning('Status code must be three digits'), stacklevel=3) if len(status) < 4 or status[3] != ' ': warn(WSGIWarning( 'Invalid value for status %r. Valid status strings are three digits, a space and a status explanation' ), stacklevel=3) status_code = int(status_code) if status_code < 100: warn(WSGIWarning('status code < 100 detected'), stacklevel=3) if type(headers) is not list: warn(WSGIWarning('header list is not a list'), stacklevel=3) for item in headers: if type(item) is not tuple or len(item) != 2: warn(WSGIWarning('Headers must tuple 2-item tuples'), stacklevel=3) name, value = item if type(name) is not str or type(value) is not str: warn(WSGIWarning('header items must be strings'), stacklevel=3) if name.lower() == 'status': warn(WSGIWarning( 'The status header is not supported due to conflicts with the CGI spec.' ), stacklevel=3) if exc_info is not None and not isinstance(exc_info, tuple): warn(WSGIWarning('invalid value for exc_info'), stacklevel=3) headers = Headers(headers) self.check_headers(headers) return (status_code, headers)
def setUp(self): """Before each test, set up a blank database""" self.db_fd, server.app.config['DATABASE'] = tempfile.mkstemp() server.app.config['TESTING'] = True self.app = server.app.test_client() add_sample_users() self.headers = Headers( [['AUTHORIZATION', 'BASIC ' + 'deusto:password'.encode('base64')]])
def __init__(self, environ, populate_request=True, shallow=False): ResponseBase.__init__(self) RequestBase.__init__(self, environ, populate_request, shallow) self.href = Href(self.script_root or '/', self.charset) self.abs_href = Href(self.url_root, self.charset) self.headers = Headers([('Content-Type', 'text/html')]) self.response = [] self.status_code = 200
def __init__(self, resp, content): #: a :class:`~werkzeug.Headers` object with the response headers #: the application sent. self.headers = Headers(resp) #: the raw, unencoded content from the server self.raw_data = content #: the parsed content from the server self.data = parse_response(resp, content, strict=True)
def __get_request_data(app, request, session): """Get request data. """ try: parameters = request.json or {} except: parameters = {"INVALID_JSON": request.data} form = request.form.to_dict(flat=False) for key, value in form.iteritems(): if len(value) == 1: parameters[key] = value[0] else: parameters[key] = value files = request.files.to_dict(flat=False) for key, value in files.iteritems(): if len(value) == 1: parameters[key] = value[0].filename else: parameters[key] = [file.filename for file in value] if request.cookies: cookies = Exceptional.__filter(app, request.cookies, "EXCEPTIONAL_COOKIE_FILTER") headers = Headers(request.headers) # Get a mutable dictionary. cookie = SimpleCookie() for key, value in cookies.iteritems(): cookie[key] = value headers["Cookie"] = cookie.output(header='', sep=';').strip() else: headers = request.headers return { "session": Exceptional.__filter(app, session, "EXCEPTIONAL_SESSION_FILTER"), "remote_ip": request.remote_addr, "parameters": Exceptional.__filter(app, parameters, "EXCEPTIONAL_PARAMETER_FILTER"), "action": request.endpoint.split('.', 1)[-1] if request.endpoint else None, "url": request.url, "request_method": request.method, "controller": request.blueprint if hasattr(request, "blueprint") else request.module, "headers": Exceptional.__filter(app, headers, "EXCEPTIONAL_HEADER_FILTER") }
def test_trace_id_propagated_when_receiving_one_in_header(pytestconfig): capmanager = pytestconfig.pluginmanager.getplugin('capturemanager') with app.test_request_context('/', headers=Headers([('X-Trace-ID', 'upstream-trace-id')])): app.preprocess_request() client.application.logger.info('Foo') record = parse_log_output(capmanager) assert record['traceid'] == 'upstream-trace-id'
def send_pdf(): h = Headers() h.add('Content-type', 'application/pdf', charset='utf8') h.add('Content-disposition', 'attachment', filename='martin_fierro.pdf') with open( os.path.join(os.path.dirname(__file__), 'static', 'martin_fierro.pdf'), 'r') as f: data = f.read() return Response(data, headers=h)
def test_repeated_requests_returns_cached_value(self): # Start with a clean cache cache = gzip_cache() cache.clear() # Create test file filename = 'payment/assets/dist/gzip-test.css' file_contents = "* { content: 'Test. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip.'; }" # noqa: E501 with open(filename, 'w+') as test_file: test_file.write(file_contents) compress_instance = Compress() with mock.patch.object( Compress, 'compress', wraps=compress_instance.compress) as mock_compress: # Do a first request to get the gzipped response response = self.client.get('/ui/gzip-test.css', headers=Headers([('Accept-encoding', 'gzip')])) # Check that flask-compress was invoked self.assertEqual(mock_compress.call_count, 1) # Check the response reports itself as gzip self.assertEqual(response.content_encoding, 'gzip') response.close() # Do a second request to get the gzipped response response = self.client.get('/ui/gzip-test.css', headers=Headers([('Accept-encoding', 'gzip')])) # Check that flask-compress was *not* invoked again self.assertEqual(mock_compress.call_count, 1) # Check the response reports itself as gzip self.assertEqual(response.content_encoding, 'gzip') response.close() os.remove(filename)
def no_cache_js(): h = Headers() h.add('Content-type', 'application/javascript') response = Response(open( os.path.join(os.path.dirname(__file__), 'static', 'mootools.js'), 'r'), headers=h) etag = hashlib.sha1(str(random.randint(0, 100000))).hexdigest() response.set_etag(etag) return response
def _open(self, url, method='GET', data=None, refer=True, content_type=None): before_browser_activity.send(self) open_started = time() if data: data = urlencode(data) url = urljoin(self._base_url, url) if method == 'GET': if '?' in url: url, query_string = url.split('?', 1) else: query_string = None if data: query_string = data if query_string: url = url + '?' + query_string request = urllib2.Request(url) elif method == 'POST': request = urllib2.Request(url, data) else: raise Exception('Unsupported method: %s' % method) if self._referrer and refer: request.add_header('Referer', self._referrer) logger.info('%s(%s)', url, method) request_started = time() response = self._opener.open(request) request_ended = time() self.status_code = response.getcode() self.headers = Headers( (head.strip().split(': ',1) for head in response.info().headers) ) self._referrer = request.get_full_url() self.location = response.geturl() self._response = response self.response = ''.join(list(response)) self._sync_document() 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, app_iter, status, headers): self.headers = Headers(headers) if isinstance(status, (int, long)): self.status_code = status # sets .status as well else: self.status = status if isinstance(app_iter, basestring): self.response = app_iter else: self.response = ''.join(app_iter) if 'Content-Length' not in self.headers: self.headers['Content-Length'] = len(self.response)
def test_basic_auth(self): from base64 import b64encode class BasicModel(models.Model): fields = [ models.StringPkField(name="user", required=True), models.StringField(name="password", required=True) ] ressources = [{"user": "******", "password": "******"}] authentication = BasicAuthentication( PythonListDataStore(ressources, ApiModel)) class ApiAppAuth(ApiApp): controller = { "list_verbs": ["GET"], "unique_verbs": ["GET"], "options": { "authentication": authentication, "authorization": Authorization } } client = Client(WSGIDispatcher([ApiAppAuth]), response_wrapper=BaseResponse) credentials = b64encode("login:pass") headers = Headers([('Authorization: Basic', credentials)]) resp = client.get("/address/1/", headers=headers) self.assertEqual(resp.status_code, 200) credentials = b64encode("login:hackme") headers = Headers([('Authorization: Basic', credentials)]) resp = client.get("/address/1/", headers=headers) self.assertEqual(resp.status_code, 401) resp = client.get("/address/1/") self.assertEqual(resp.status_code, 401)
def admin_download_benchmark(database, category, user_dir, filename): directory = os.path.join(config.UPLOAD_FOLDER, database) import mimetypes headers = Headers() headers.add('Content-Type', mimetypes.guess_type(filename)) headers.add('Content-Disposition', 'attachment', filename=secure_filename(filename)) return Response(response=open( os.path.join(directory, category, user_dir, filename), 'rb'), headers=headers)
def make_response(response_data, status_code=200, headers=None): if request.headers.get("X-Response-Skip-Null"): # swagger does not currently support null values; remove these conditionally response_data = remove_null_values(response_data) headers = headers or {} if "Content-Type" not in headers: # Specify JSON as the response content type by default headers["Content-Type"] = "application/json" response = jsonify(response_data) response.headers = Headers(headers) response.status_code = status_code return response
def send_zip(zipfilename, filename_path_list): #s = "<body><h1>HELLO</h1></body>" #response = iter(list(s)) response = zip_iter(filename_path_list) headers = Headers() attachment_filename = zipfilename headers.add('Content-Disposition', 'attachment', filename=attachment_filename) mimetype = 'application/zip' return current_app.response_class(response=response, mimetype=mimetype, headers=headers, direct_passthrough=True)
def create_response(code=0, message="Success", pretty=False, **kwargs): """Creates a Response object appropriated with the given arguments""" kwargs['code'] = code kwargs['message'] = message kwargs['request_params'] = request.args headers = Headers() headers.add('Access-Control-Allow-Origin', '*') if pretty: return Response(json.dumps(kwargs, indent=2), mimetype='application/json', headers=headers) else: return Response(json.dumps(kwargs), mimetype='application/json', headers=headers)
def test_exc_info_in_log_entries_when_passed(pytestconfig): capmanager = pytestconfig.pluginmanager.getplugin('capturemanager') with app.test_request_context('/', headers=Headers([('X-Trace-ID', 'upstream-trace-id')])): app.preprocess_request() try: raise Exception('Hello') except Exception as e: client.application.logger.info('Foo', exc_info=e) record = parse_log_output(capmanager) assert 'Traceback (most recent call last)' in ' '.join(record['exception']) assert 'Exception: Hello' in ' '.join(record['exception'])
def _output(content, serve=True): """Output the content in the datastore as a HTTP Response""" headers = Headers() if content.content_type: headers['Content-Type'] = content.content_type last_modified = content.last_modified.strftime(HTTP_DATE_FMT) headers.add('Last-Modified', last_modified) for header in content.headers: key, value = header.split(':', 1) headers[key] = value.strip() if serve: response = Response(content.body, content_type=content.content_type, headers=headers, status=content.status) else: response = Response(status=304) return response
def test_gzipped_response(self): # Create test file filename = 'title_ui/assets/dist/gzip-test.css' file_contents = "* { content: 'Test. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip. Padded out to trigger gzip.'; }" # noqa: E501 with open(filename, 'w+') as test_file: test_file.write(file_contents) response = self.client.get('/ui/gzip-test.css', headers=Headers([('Accept-encoding', 'gzip')])) # Check the response reports itself as gzip self.assertEqual(response.content_encoding, 'gzip') # And that we haven't just received the original contents self.assertNotEqual(response.data, file_contents) # Unzip it, check the contents is the same as the original self.assertEqual(gzip.decompress(response.data).decode('utf-8'), file_contents) response.close() os.remove(filename)
def json_response(self): serializer = Serializer() prepared_query = self.prepare_query() def generate(): i = prepared_query.count() yield '[\n' for obj in prepared_query: i -= 1 yield json.dumps( serializer.serialize_object(obj, prepared_query.query)) if i > 0: yield ',\n' yield '\n]' headers = Headers() headers.add('Content-Type', 'application/javascript') headers.add('Content-Disposition', 'attachment; filename=export.json') return Response(generate(), mimetype='text/javascript', headers=headers, direct_passthrough=True)
def download_file(vault_name): """ Download a file if the link is available... """ handler = get_handler() region = handler.region.name vault = Vault.query.filter_by(name=vault_name,region=region).first() if vault is None: abort(401) #Need to get the archive too... if 'archive_id' not in request.args: abort(401) archive = Archive.query.filter_by(archive_id=request.args['archive_id']).first() if archive is None: abort(401) if archive.filename!="NOT_GIVEN": fname=archive.filename else: fname=app.config["UNKNOWN_FILENAME"] #Are we serving from cache? #cache = archive.cached() #if cache==1: # print "Serving from cache." # return send_from_directory(os.path.join(app.config["LOCAL_CACHE"],region,vault.name),archive.archive_id,attachment_filename=fname,as_attachment=True) #Is there a finished job knocking about? job=archive.jobs.filter_by(action='download',completed=True,live=True,status_message="Succeeded").first() if job is None: abort(401) #OK, everything exists, go ahead... if False and cache==2: #Save to cache whilst serving f = open(os.path.join(app.config["LOCAL_CACHE"],region,vault.name,archive.archive_id),'wb') else: #Don't add to cache, just serve f = None h=Headers() h.add("Content-Disposition",'attachment;filename="'+fname+'"') return Response(stream_with_context(job.stream_output(file_handler=f)),headers=h)
def test_gzip_cache_key_format(self): with app.test_request_context('/foo?cachebuster=123'): response = mock.MagicMock(headers=Headers([('ETag', 'bar')])) key = gzip_cache_key(response) self.assertEqual(key, '/foobar')
def send_file(filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, add_etags=True, cache_timeout=60 * 60 * 12, conditional=False): """Sends the contents of a file to the client. This will use the most efficient method available and configured. By default it will try to use the WSGI server's file_wrapper support. Alternatively you can set the application's :attr:`~Flask.use_x_sendfile` attribute to ``True`` to directly emit an `X-Sendfile` header. This however requires support of the underlying webserver for `X-Sendfile`. By default it will try to guess the mimetype for you, but you can also explicitly provide one. For extra security you probably want to send certain files as attachment (HTML for instance). The mimetype guessing requires a `filename` or an `attachment_filename` to be provided. Please never pass filenames to this function from user sources without checking them first. Something like this is usually sufficient to avoid security problems:: if '..' in filename or filename.startswith('/'): abort(404) .. versionadded:: 0.2 .. versionadded:: 0.5 The `add_etags`, `cache_timeout` and `conditional` parameters were added. The default behaviour is now to attach etags. .. versionchanged:: 0.7 mimetype guessing and etag support for file objects was deprecated because it was unreliable. Pass a filename if you are able to, otherwise attach an etag yourself. This functionality will be removed in Flask 1.0 :param filename_or_fp: the filename of the file to send. This is relative to the :attr:`~Flask.root_path` if a relative path is specified. Alternatively a file object might be provided in which case `X-Sendfile` might not work and fall back to the traditional method. Make sure that the file pointer is positioned at the start of data to send before calling :func:`send_file`. :param mimetype: the mimetype of the file if provided, otherwise auto detection happens. :param as_attachment: set to `True` if you want to send this file with a ``Content-Disposition: attachment`` header. :param attachment_filename: the filename for the attachment if it differs from the file's filename. :param add_etags: set to `False` to disable attaching of etags. :param conditional: set to `True` to enable conditional responses. :param cache_timeout: the timeout in seconds for the headers. """ mtime = None if isinstance(filename_or_fp, basestring): filename = filename_or_fp file = None else: from warnings import warn file = filename_or_fp filename = getattr(file, 'name', None) # XXX: this behaviour is now deprecated because it was unreliable. # removed in Flask 1.0 if not attachment_filename and not mimetype \ and isinstance(filename, basestring): warn(DeprecationWarning('The filename support for file objects ' 'passed to send_file is now deprecated. Pass an ' 'attach_filename if you want mimetypes to be guessed.'), stacklevel=2) if add_etags: warn(DeprecationWarning('In future flask releases etags will no ' 'longer be generated for file objects passed to the send_file ' 'function because this behaviour was unreliable. Pass ' 'filenames instead if possible, otherwise attach an etag ' 'yourself based on another value'), stacklevel=2) if filename is not None: if not os.path.isabs(filename): filename = os.path.join(current_app.root_path, filename) if mimetype is None and (filename or attachment_filename): mimetype = mimetypes.guess_type(filename or attachment_filename)[0] if mimetype is None: mimetype = 'application/octet-stream' headers = Headers() if as_attachment: if attachment_filename is None: if filename is None: raise TypeError('filename unavailable, required for ' 'sending as attachment') attachment_filename = os.path.basename(filename) headers.add('Content-Disposition', 'attachment', filename=attachment_filename) if current_app.use_x_sendfile and filename: if file is not None: file.close() headers['X-Sendfile'] = filename data = None else: if file is None: file = open(filename, 'rb') mtime = os.path.getmtime(filename) data = wrap_file(request.environ, file) rv = current_app.response_class(data, mimetype=mimetype, headers=headers, direct_passthrough=True) # if we know the file modification date, we can store it as the # the time of the last modification. if mtime is not None: rv.last_modified = int(mtime) rv.cache_control.public = True if cache_timeout: rv.cache_control.max_age = cache_timeout rv.expires = int(time() + cache_timeout) if add_etags and filename is not None: rv.set_etag('flask-%s-%s-%s' % ( os.path.getmtime(filename), os.path.getsize(filename), adler32( filename.encode('utf8') if isinstance(filename, unicode) else filename ) & 0xffffffff )) if conditional: rv = rv.make_conditional(request) # make sure we don't send x-sendfile for servers that # ignore the 304 status code for x-sendfile. if rv.status_code == 304: rv.headers.pop('x-sendfile', None) return rv
def send_file(filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None): """Sends the contents of a file to the client. This will use the most efficient method available and configured. By default it will try to use the WSGI server's file_wrapper support. Alternatively you can set the application's :attr:`~Flask.use_x_sendfile` attribute to ``True`` to directly emit an `X-Sendfile` header. This however requires support of the underlying webserver for `X-Sendfile`. By default it will try to guess the mimetype for you, but you can also explicitly provide one. For extra security you probably want to sent certain files as attachment (HTML for instance). Please never pass filenames to this function from user sources without checking them first. Something like this is usually sufficient to avoid security problems:: if '..' in filename or filename.startswith('/'): abort(404) .. versionadded:: 0.2 :param filename_or_fp: the filename of the file to send. This is relative to the :attr:`~Flask.root_path` if a relative path is specified. Alternatively a file object might be provided in which case `X-Sendfile` might not work and fall back to the traditional method. :param mimetype: the mimetype of the file if provided, otherwise auto detection happens. :param as_attachment: set to `True` if you want to send this file with a ``Content-Disposition: attachment`` header. :param attachment_filename: the filename for the attachment if it differs from the file's filename. """ if isinstance(filename_or_fp, basestring): filename = filename_or_fp file = None else: file = filename_or_fp filename = getattr(file, 'name', None) if filename is not None: filename = os.path.join(current_app.root_path, filename) if mimetype is None and (filename or attachment_filename): mimetype = mimetypes.guess_type(filename or attachment_filename)[0] if mimetype is None: mimetype = 'application/octet-stream' headers = Headers() if as_attachment: if attachment_filename is None: if filename is None: raise TypeError('filename unavailable, required for ' 'sending as attachment') attachment_filename = os.path.basename(filename) headers.add('Content-Disposition', 'attachment', filename=attachment_filename) if current_app.use_x_sendfile and filename: if file is not None: file.close() headers['X-Sendfile'] = filename data = None else: if file is None: file = open(filename, 'rb') data = wrap_file(request.environ, file) return Response(data, mimetype=mimetype, headers=headers, direct_passthrough=True)
def send_file(filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None, add_etags=True, cache_timeout=60 * 60 * 12, conditional=False): """Sends the contents of a file to the client. This will use the most efficient method available and configured. By default it will try to use the WSGI server's file_wrapper support. Alternatively you can set the application's :attr:`~Flask.use_x_sendfile` attribute to ``True`` to directly emit an `X-Sendfile` header. This however requires support of the underlying webserver for `X-Sendfile`. By default it will try to guess the mimetype for you, but you can also explicitly provide one. For extra security you probably want to sent certain files as attachment (HTML for instance). Please never pass filenames to this function from user sources without checking them first. Something like this is usually sufficient to avoid security problems:: if '..' in filename or filename.startswith('/'): abort(404) .. versionadded:: 0.2 .. versionadded:: 0.5 The `add_etags`, `cache_timeout` and `conditional` parameters were added. The default behaviour is now to attach etags. :param filename_or_fp: the filename of the file to send. This is relative to the :attr:`~Flask.root_path` if a relative path is specified. Alternatively a file object might be provided in which case `X-Sendfile` might not work and fall back to the traditional method. :param mimetype: the mimetype of the file if provided, otherwise auto detection happens. :param as_attachment: set to `True` if you want to send this file with a ``Content-Disposition: attachment`` header. :param attachment_filename: the filename for the attachment if it differs from the file's filename. :param add_etags: set to `False` to disable attaching of etags. :param conditional: set to `True` to enable conditional responses. :param cache_timeout: the timeout in seconds for the headers. """ mtime = None if isinstance(filename_or_fp, basestring): filename = filename_or_fp file = None else: file = filename_or_fp filename = getattr(file, 'name', None) if filename is not None: if not os.path.isabs(filename): filename = os.path.join(current_app.root_path, filename) if mimetype is None and (filename or attachment_filename): mimetype = mimetypes.guess_type(filename or attachment_filename)[0] if mimetype is None: mimetype = 'application/octet-stream' headers = Headers() if as_attachment: if attachment_filename is None: if filename is None: raise TypeError('filename unavailable, required for ' 'sending as attachment') attachment_filename = os.path.basename(filename) headers.add('Content-Disposition', 'attachment', filename=attachment_filename) if current_app.use_x_sendfile and filename: if file is not None: file.close() headers['X-Sendfile'] = filename data = None else: if file is None: file = open(filename, 'rb') mtime = os.path.getmtime(filename) data = wrap_file(request.environ, file) rv = current_app.response_class(data, mimetype=mimetype, headers=headers, direct_passthrough=True) # if we know the file modification date, we can store it as the # current time to better support conditional requests. Werkzeug # as of 0.6.1 will override this value however in the conditional # response with the current time. This will be fixed in Werkzeug # with a new release, however many WSGI servers will still emit # a separate date header. if mtime is not None: rv.date = int(mtime) rv.cache_control.public = True if cache_timeout: rv.cache_control.max_age = cache_timeout rv.expires = int(time() + cache_timeout) if add_etags and filename is not None: rv.set_etag('flask-%s-%s-%s' % (os.path.getmtime(filename), os.path.getsize(filename), adler32(filename) & 0xffffffff)) if conditional: rv = rv.make_conditional(request) # make sure we don't send x-sendfile for servers that # ignore the 304 status code for x-sendfile. if rv.status_code == 304: rv.headers.pop('x-sendfile', None) return rv
def configuration_runs(database, experiment_id): db = models.get_database(database) or abort(404) experiment = db.session.query( db.Experiment).get(experiment_id) or abort(404) if not experiment.configuration_scenario: abort(404) solver_configs = [ sc for sc in experiment.solver_configurations if sc.solver_binary == experiment.configuration_scenario.solver_binary ] solver_config_ids = [sc.idSolverConfig for sc in solver_configs] configurable_parameters = [ p.parameter for p in experiment.configuration_scenario.parameters if p.configurable and p.parameter.name not in ('instance', 'seed') ] configurable_parameters_ids = [ p.idParameter for p in configurable_parameters ] parameter_instances = db.session.query(db.ParameterInstance).options( joinedload('parameter')).filter( db.ParameterInstance.SolverConfig_idSolverConfig.in_( solver_config_ids)).all() instances_by_id = dict( (i.idInstance, i) for i in experiment.get_instances(db)) instance_properties = [ p for p in db.session.query(db.Property) if p.is_instance_property() ] parameter_values = dict() for pv in parameter_instances: if pv.Parameters_idParameter not in configurable_parameters_ids: continue if pv.SolverConfig_idSolverConfig not in parameter_values: parameter_values[pv.SolverConfig_idSolverConfig] = dict() parameter_values[pv.SolverConfig_idSolverConfig][ pv.Parameters_idParameter] = pv.value results, _, _ = experiment.get_result_matrix( db, experiment.solver_configurations, experiment.get_instances(db), cost=experiment.defaultCost) csv_response = StringIO.StringIO() csv_writer = csv.writer(csv_response) csv_writer.writerow([p.name for p in configurable_parameters] + [p.name for p in instance_properties] + ['par1', 'censored']) for idInstance in results: for idSolverConfig in results[idInstance]: for run in results[idInstance][idSolverConfig]: csv_writer.writerow( [parameter_values[idSolverConfig].get(p.idParameter, '') for p in configurable_parameters] + \ [instances_by_id[idInstance].get_property_value(p.idProperty, db) for p in instance_properties] + \ [run.penalized_time1, 1 if run.censored else 0]) csv_response.seek(0) headers = Headers() headers.add('Content-Type', 'text/csv') headers.add('Content-Disposition', 'attachment', filename=secure_filename(experiment.name) + "_configuration_runs.csv") return Response(response=csv_response.read(), headers=headers)