Skip to content
Myr

Added support for send_file

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent 4156bd4 · Browse files · 4 files+161 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+161 added−2 removed

  • tests:+84 added−1 removed
  • other:+77 added−1 removed

4 files+161 added−2 removed

modified:docs/api.rst+2 added
211 unmodified lines
212 :param code: the HTTP error code.213214.. autofunction:: redirect215216.. autofunction:: send_file217218.. autofunction:: escape219220.. autoclass:: Markup221 :members: escape, unescape, striptags
50 unmodified lines
modified:tests/flask_tests.py+84 added-1 removed
15 unmodified lines
16import flask17import unittest18import tempfile19from datetime import datetime20from werkzeug import parse_date20from werkzeug import parse_date, parse_options_header21from cStringIO import StringIO222324example_path = os.path.join(os.path.dirname(__file__), '..', 'examples')25sys.path.append(os.path.join(example_path, 'flaskr'))
356 unmodified lines
382 rv = app.test_client().get('/')383 assert rv.data == 'dcba'384385386class SendfileTestCase(unittest.TestCase):387388 def test_send_file_regular(self):389 app = flask.Flask(__name__)390 with app.test_request_context():391 rv = flask.send_file('static/index.html')392 assert rv.direct_passthrough393 assert rv.mimetype == 'text/html'394 with app.open_resource('static/index.html') as f:395 assert rv.data == f.read()396397 def test_send_file_xsendfile(self):398 app = flask.Flask(__name__)399 app.use_x_sendfile = True400 with app.test_request_context():401 rv = flask.send_file('static/index.html')402 assert rv.direct_passthrough403 assert 'x-sendfile' in rv.headers404 assert rv.headers['x-sendfile'] == \405 os.path.join(app.root_path, 'static/index.html')406 assert rv.mimetype == 'text/html'407408 def test_send_file_object(self):409 app = flask.Flask(__name__)410 with app.test_request_context():411 f = open(os.path.join(app.root_path, 'static/index.html'))412 rv = flask.send_file(f)413 with app.open_resource('static/index.html') as f:414 assert rv.data == f.read()415 assert rv.mimetype == 'text/html'416417 app.use_x_sendfile = True418 with app.test_request_context():419 f = open(os.path.join(app.root_path, 'static/index.html'))420 rv = flask.send_file(f)421 assert rv.mimetype == 'text/html'422 assert 'x-sendfile' in rv.headers423 assert rv.headers['x-sendfile'] == \424 os.path.join(app.root_path, 'static/index.html')425426 app.use_x_sendfile = False427 with app.test_request_context():428 f = StringIO('Test')429 rv = flask.send_file(f)430 assert rv.data == 'Test'431 assert rv.mimetype == 'application/octet-stream'432 f = StringIO('Test')433 rv = flask.send_file(f, mimetype='text/plain')434 assert rv.data == 'Test'435 assert rv.mimetype == 'text/plain'436437 app.use_x_sendfile = True438 with app.test_request_context():439 f = StringIO('Test')440 rv = flask.send_file(f)441 assert 'x-sendfile' not in rv.headers442443 def test_attachment(self):444 app = flask.Flask(__name__)445 with app.test_request_context():446 f = open(os.path.join(app.root_path, 'static/index.html'))447 rv = flask.send_file(f, as_attachment=True)448 value, options = parse_options_header(rv.headers['Content-Disposition'])449 assert value == 'attachment'450451 with app.test_request_context():452 assert options['filename'] == 'index.html'453 rv = flask.send_file('static/index.html', as_attachment=True)454 value, options = parse_options_header(rv.headers['Content-Disposition'])455 assert value == 'attachment'456 assert options['filename'] == 'index.html'457458 with app.test_request_context():459 rv = flask.send_file(StringIO('Test'), as_attachment=True,460 attachment_filename='index.txt')461 assert rv.mimetype == 'text/plain'462 value, options = parse_options_header(rv.headers['Content-Disposition'])463 assert value == 'attachment'464 assert options['filename'] == 'index.txt'465466467def suite():468 from minitwit_tests import MiniTwitTestCase469 from flaskr_tests import FlaskrTestCase470 suite = unittest.TestSuite()471 suite.addTest(unittest.makeSuite(ContextTestCase))472 suite.addTest(unittest.makeSuite(BasicFunctionalityTestCase))473 suite.addTest(unittest.makeSuite(TemplatingTestCase))474 suite.addTest(unittest.makeSuite(SendfileTestCase))475 if flask.json_available:476 suite.addTest(unittest.makeSuite(JSONTestCase))477 suite.addTest(unittest.makeSuite(MiniTwitTestCase))478 suite.addTest(unittest.makeSuite(FlaskrTestCase))
5 unmodified lines
modified:CHANGES+1 added
13 unmodified lines
14- :meth:`~flask.Flask.add_url_rule` can now also register a15 view function.16- server listens on 127.0.0.1 by default now to fix issues with chrome.17- added external URL support.18- added support for :func:`~flask.send_file`1920Version 0.121-----------22
1 unmodified line
modified:flask.py+74 added-1 removed
10 unmodified lines
11"""12from __future__ import with_statement13import os14import sys15import mimetypes16from datetime import datetime, timedelta1718from jinja2 import Environment, PackageLoader, FileSystemLoader19from werkzeug import Request as RequestBase, Response as ResponseBase, \20 LocalStack, LocalProxy, create_environ, SharedDataMiddleware, \20 ImmutableDict, cached_property21 ImmutableDict, cached_property, wrap_file, Headers22from werkzeug.routing import Map, Rule23from werkzeug.exceptions import HTTPException24from werkzeug.contrib.securecookie import SecureCookie25
209 unmodified lines
235 return current_app.response_class(json.dumps(dict(*args, **kwargs),236 indent=None if request.is_xhr else 2), mimetype='application/json')237238239def send_file(filename_or_fp, mimetype=None, as_attachment=False,240 attachment_filename=None):241 """Sends the contents of a file to the client. This will use the242 most efficient method available and configured. By default it will243 try to use the WSGI server's file_wrapper support. Alternatively244 you can set the application's :attr:`~Flask.use_x_sendfile` attribute245 to ``True`` to directly emit an `X-Sendfile` header. This however246 requires support of the underlying webserver for `X-Sendfile`.247248 By default it will try to guess the mimetype for you, but you can249 also explicitly provide one. For extra security you probably want250 to sent certain files as attachment (HTML for instance).251252 .. versionadded:: 0.2253254 :param filename_or_fp: the filename of the file to send. This is255 relative to the :attr:`~Flask.root_path` if a256 relative path is specified.257 Alternatively a file object might be provided258 in which case `X-Sendfile` might not work and259 fall back to the traditional method.260 :param mimetype: the mimetype of the file if provided, otherwise261 auto detection happens.262 :param as_attachment: set to `True` if you want to send this file with263 a ``Content-Disposition: attachment`` header.264 :param attachment_filename: the filename for the attachment if it265 differs from the file's filename.266 """267 if isinstance(filename_or_fp, basestring):268 filename = filename_or_fp269 file = None270 else:271 file = filename_or_fp272 filename = getattr(file, 'name', None)273 if filename is not None:274 filename = os.path.join(current_app.root_path, filename)275 if mimetype is None and (filename or attachment_filename):276 mimetype = mimetypes.guess_type(filename or attachment_filename)[0]277 if mimetype is None:278 mimetype = 'application/octet-stream'279280 headers = Headers()281 if as_attachment:282 if attachment_filename is None:283 if filename is None:284 raise TypeError('filename unavailable, required for '285 'sending as attachment')286 attachment_filename = os.path.basename(filename)287 headers.add('Content-Disposition', 'attachment',288 filename=attachment_filename)289290 if current_app.use_x_sendfile and filename:291 if file is not None:292 file.close()293 headers['X-Sendfile'] = filename294 data = None295 else:296 if file is None:297 file = open(filename, 'rb')298 data = wrap_file(request.environ, file)299300 return Response(data, mimetype=mimetype, headers=headers,301 direct_passthrough=True)302303304def render_template(template_name, **context):305 """Renders a template from the template folder with the given306 context.307
101 unmodified lines
409 #: date of a permanent session. The default is 31 days which makes a410 #: permanent session survive for roughly one month.411 permanent_session_lifetime = timedelta(days=31)412413 #: Enable this if you want to use the X-Sendfile feature. Keep in414 #: mind that the server has to support this. This only affects files415 #: sent with the :func:`send_file` method.416 #:417 #: .. versionadded:: 0.2418 use_x_sendfile = False419420 #: options that are passed directly to the Jinja2 environment421 jinja_options = ImmutableDict(422 autoescape=True,423 extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_']
502 unmodified lines