helpers.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. # -*- coding: utf-8 -*-
  2. """
  3. flask.helpers
  4. ~~~~~~~~~~~~~
  5. Implements various helpers.
  6. :copyright: (c) 2015 by Armin Ronacher.
  7. :license: BSD, see LICENSE for more details.
  8. """
  9. import os
  10. import sys
  11. import pkgutil
  12. import posixpath
  13. import mimetypes
  14. from time import time
  15. from zlib import adler32
  16. from threading import RLock
  17. from werkzeug.routing import BuildError
  18. from functools import update_wrapper
  19. try:
  20. from werkzeug.urls import url_quote
  21. except ImportError:
  22. from urlparse import quote as url_quote
  23. from werkzeug.datastructures import Headers
  24. from werkzeug.exceptions import BadRequest, NotFound
  25. # this was moved in 0.7
  26. try:
  27. from werkzeug.wsgi import wrap_file
  28. except ImportError:
  29. from werkzeug.utils import wrap_file
  30. from jinja2 import FileSystemLoader
  31. from .signals import message_flashed
  32. from .globals import session, _request_ctx_stack, _app_ctx_stack, \
  33. current_app, request
  34. from ._compat import string_types, text_type
  35. # sentinel
  36. _missing = object()
  37. # what separators does this operating system provide that are not a slash?
  38. # this is used by the send_from_directory function to ensure that nobody is
  39. # able to access files from outside the filesystem.
  40. _os_alt_seps = list(sep for sep in [os.path.sep, os.path.altsep]
  41. if sep not in (None, '/'))
  42. def get_debug_flag(default=None):
  43. val = os.environ.get('FLASK_DEBUG')
  44. if not val:
  45. return default
  46. return val not in ('0', 'false', 'no')
  47. def _endpoint_from_view_func(view_func):
  48. """Internal helper that returns the default endpoint for a given
  49. function. This always is the function name.
  50. """
  51. assert view_func is not None, 'expected view func if endpoint ' \
  52. 'is not provided.'
  53. return view_func.__name__
  54. def stream_with_context(generator_or_function):
  55. """Request contexts disappear when the response is started on the server.
  56. This is done for efficiency reasons and to make it less likely to encounter
  57. memory leaks with badly written WSGI middlewares. The downside is that if
  58. you are using streamed responses, the generator cannot access request bound
  59. information any more.
  60. This function however can help you keep the context around for longer::
  61. from flask import stream_with_context, request, Response
  62. @app.route('/stream')
  63. def streamed_response():
  64. @stream_with_context
  65. def generate():
  66. yield 'Hello '
  67. yield request.args['name']
  68. yield '!'
  69. return Response(generate())
  70. Alternatively it can also be used around a specific generator::
  71. from flask import stream_with_context, request, Response
  72. @app.route('/stream')
  73. def streamed_response():
  74. def generate():
  75. yield 'Hello '
  76. yield request.args['name']
  77. yield '!'
  78. return Response(stream_with_context(generate()))
  79. .. versionadded:: 0.9
  80. """
  81. try:
  82. gen = iter(generator_or_function)
  83. except TypeError:
  84. def decorator(*args, **kwargs):
  85. gen = generator_or_function(*args, **kwargs)
  86. return stream_with_context(gen)
  87. return update_wrapper(decorator, generator_or_function)
  88. def generator():
  89. ctx = _request_ctx_stack.top
  90. if ctx is None:
  91. raise RuntimeError('Attempted to stream with context but '
  92. 'there was no context in the first place to keep around.')
  93. with ctx:
  94. # Dummy sentinel. Has to be inside the context block or we're
  95. # not actually keeping the context around.
  96. yield None
  97. # The try/finally is here so that if someone passes a WSGI level
  98. # iterator in we're still running the cleanup logic. Generators
  99. # don't need that because they are closed on their destruction
  100. # automatically.
  101. try:
  102. for item in gen:
  103. yield item
  104. finally:
  105. if hasattr(gen, 'close'):
  106. gen.close()
  107. # The trick is to start the generator. Then the code execution runs until
  108. # the first dummy None is yielded at which point the context was already
  109. # pushed. This item is discarded. Then when the iteration continues the
  110. # real generator is executed.
  111. wrapped_g = generator()
  112. next(wrapped_g)
  113. return wrapped_g
  114. def make_response(*args):
  115. """Sometimes it is necessary to set additional headers in a view. Because
  116. views do not have to return response objects but can return a value that
  117. is converted into a response object by Flask itself, it becomes tricky to
  118. add headers to it. This function can be called instead of using a return
  119. and you will get a response object which you can use to attach headers.
  120. If view looked like this and you want to add a new header::
  121. def index():
  122. return render_template('index.html', foo=42)
  123. You can now do something like this::
  124. def index():
  125. response = make_response(render_template('index.html', foo=42))
  126. response.headers['X-Parachutes'] = 'parachutes are cool'
  127. return response
  128. This function accepts the very same arguments you can return from a
  129. view function. This for example creates a response with a 404 error
  130. code::
  131. response = make_response(render_template('not_found.html'), 404)
  132. The other use case of this function is to force the return value of a
  133. view function into a response which is helpful with view
  134. decorators::
  135. response = make_response(view_function())
  136. response.headers['X-Parachutes'] = 'parachutes are cool'
  137. Internally this function does the following things:
  138. - if no arguments are passed, it creates a new response argument
  139. - if one argument is passed, :meth:`flask.Flask.make_response`
  140. is invoked with it.
  141. - if more than one argument is passed, the arguments are passed
  142. to the :meth:`flask.Flask.make_response` function as tuple.
  143. .. versionadded:: 0.6
  144. """
  145. if not args:
  146. return current_app.response_class()
  147. if len(args) == 1:
  148. args = args[0]
  149. return current_app.make_response(args)
  150. def url_for(endpoint, **values):
  151. """Generates a URL to the given endpoint with the method provided.
  152. Variable arguments that are unknown to the target endpoint are appended
  153. to the generated URL as query arguments. If the value of a query argument
  154. is ``None``, the whole pair is skipped. In case blueprints are active
  155. you can shortcut references to the same blueprint by prefixing the
  156. local endpoint with a dot (``.``).
  157. This will reference the index function local to the current blueprint::
  158. url_for('.index')
  159. For more information, head over to the :ref:`Quickstart <url-building>`.
  160. To integrate applications, :class:`Flask` has a hook to intercept URL build
  161. errors through :attr:`Flask.url_build_error_handlers`. The `url_for`
  162. function results in a :exc:`~werkzeug.routing.BuildError` when the current
  163. app does not have a URL for the given endpoint and values. When it does, the
  164. :data:`~flask.current_app` calls its :attr:`~Flask.url_build_error_handlers` if
  165. it is not ``None``, which can return a string to use as the result of
  166. `url_for` (instead of `url_for`'s default to raise the
  167. :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.
  168. An example::
  169. def external_url_handler(error, endpoint, values):
  170. "Looks up an external URL when `url_for` cannot build a URL."
  171. # This is an example of hooking the build_error_handler.
  172. # Here, lookup_url is some utility function you've built
  173. # which looks up the endpoint in some external URL registry.
  174. url = lookup_url(endpoint, **values)
  175. if url is None:
  176. # External lookup did not have a URL.
  177. # Re-raise the BuildError, in context of original traceback.
  178. exc_type, exc_value, tb = sys.exc_info()
  179. if exc_value is error:
  180. raise exc_type, exc_value, tb
  181. else:
  182. raise error
  183. # url_for will use this result, instead of raising BuildError.
  184. return url
  185. app.url_build_error_handlers.append(external_url_handler)
  186. Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and
  187. `endpoint` and `values` are the arguments passed into `url_for`. Note
  188. that this is for building URLs outside the current application, and not for
  189. handling 404 NotFound errors.
  190. .. versionadded:: 0.10
  191. The `_scheme` parameter was added.
  192. .. versionadded:: 0.9
  193. The `_anchor` and `_method` parameters were added.
  194. .. versionadded:: 0.9
  195. Calls :meth:`Flask.handle_build_error` on
  196. :exc:`~werkzeug.routing.BuildError`.
  197. :param endpoint: the endpoint of the URL (name of the function)
  198. :param values: the variable arguments of the URL rule
  199. :param _external: if set to ``True``, an absolute URL is generated. Server
  200. address can be changed via ``SERVER_NAME`` configuration variable which
  201. defaults to `localhost`.
  202. :param _scheme: a string specifying the desired URL scheme. The `_external`
  203. parameter must be set to ``True`` or a :exc:`ValueError` is raised. The default
  204. behavior uses the same scheme as the current request, or
  205. ``PREFERRED_URL_SCHEME`` from the :ref:`app configuration <config>` if no
  206. request context is available. As of Werkzeug 0.10, this also can be set
  207. to an empty string to build protocol-relative URLs.
  208. :param _anchor: if provided this is added as anchor to the URL.
  209. :param _method: if provided this explicitly specifies an HTTP method.
  210. """
  211. appctx = _app_ctx_stack.top
  212. reqctx = _request_ctx_stack.top
  213. if appctx is None:
  214. raise RuntimeError('Attempted to generate a URL without the '
  215. 'application context being pushed. This has to be '
  216. 'executed when application context is available.')
  217. # If request specific information is available we have some extra
  218. # features that support "relative" URLs.
  219. if reqctx is not None:
  220. url_adapter = reqctx.url_adapter
  221. blueprint_name = request.blueprint
  222. if not reqctx.request._is_old_module:
  223. if endpoint[:1] == '.':
  224. if blueprint_name is not None:
  225. endpoint = blueprint_name + endpoint
  226. else:
  227. endpoint = endpoint[1:]
  228. else:
  229. # TODO: get rid of this deprecated functionality in 1.0
  230. if '.' not in endpoint:
  231. if blueprint_name is not None:
  232. endpoint = blueprint_name + '.' + endpoint
  233. elif endpoint.startswith('.'):
  234. endpoint = endpoint[1:]
  235. external = values.pop('_external', False)
  236. # Otherwise go with the url adapter from the appctx and make
  237. # the URLs external by default.
  238. else:
  239. url_adapter = appctx.url_adapter
  240. if url_adapter is None:
  241. raise RuntimeError('Application was not able to create a URL '
  242. 'adapter for request independent URL generation. '
  243. 'You might be able to fix this by setting '
  244. 'the SERVER_NAME config variable.')
  245. external = values.pop('_external', True)
  246. anchor = values.pop('_anchor', None)
  247. method = values.pop('_method', None)
  248. scheme = values.pop('_scheme', None)
  249. appctx.app.inject_url_defaults(endpoint, values)
  250. # This is not the best way to deal with this but currently the
  251. # underlying Werkzeug router does not support overriding the scheme on
  252. # a per build call basis.
  253. old_scheme = None
  254. if scheme is not None:
  255. if not external:
  256. raise ValueError('When specifying _scheme, _external must be True')
  257. old_scheme = url_adapter.url_scheme
  258. url_adapter.url_scheme = scheme
  259. try:
  260. try:
  261. rv = url_adapter.build(endpoint, values, method=method,
  262. force_external=external)
  263. finally:
  264. if old_scheme is not None:
  265. url_adapter.url_scheme = old_scheme
  266. except BuildError as error:
  267. # We need to inject the values again so that the app callback can
  268. # deal with that sort of stuff.
  269. values['_external'] = external
  270. values['_anchor'] = anchor
  271. values['_method'] = method
  272. return appctx.app.handle_url_build_error(error, endpoint, values)
  273. if anchor is not None:
  274. rv += '#' + url_quote(anchor)
  275. return rv
  276. def get_template_attribute(template_name, attribute):
  277. """Loads a macro (or variable) a template exports. This can be used to
  278. invoke a macro from within Python code. If you for example have a
  279. template named :file:`_cider.html` with the following contents:
  280. .. sourcecode:: html+jinja
  281. {% macro hello(name) %}Hello {{ name }}!{% endmacro %}
  282. You can access this from Python code like this::
  283. hello = get_template_attribute('_cider.html', 'hello')
  284. return hello('World')
  285. .. versionadded:: 0.2
  286. :param template_name: the name of the template
  287. :param attribute: the name of the variable of macro to access
  288. """
  289. return getattr(current_app.jinja_env.get_template(template_name).module,
  290. attribute)
  291. def flash(message, category='message'):
  292. """Flashes a message to the next request. In order to remove the
  293. flashed message from the session and to display it to the user,
  294. the template has to call :func:`get_flashed_messages`.
  295. .. versionchanged:: 0.3
  296. `category` parameter added.
  297. :param message: the message to be flashed.
  298. :param category: the category for the message. The following values
  299. are recommended: ``'message'`` for any kind of message,
  300. ``'error'`` for errors, ``'info'`` for information
  301. messages and ``'warning'`` for warnings. However any
  302. kind of string can be used as category.
  303. """
  304. # Original implementation:
  305. #
  306. # session.setdefault('_flashes', []).append((category, message))
  307. #
  308. # This assumed that changes made to mutable structures in the session are
  309. # are always in sync with the session object, which is not true for session
  310. # implementations that use external storage for keeping their keys/values.
  311. flashes = session.get('_flashes', [])
  312. flashes.append((category, message))
  313. session['_flashes'] = flashes
  314. message_flashed.send(current_app._get_current_object(),
  315. message=message, category=category)
  316. def get_flashed_messages(with_categories=False, category_filter=[]):
  317. """Pulls all flashed messages from the session and returns them.
  318. Further calls in the same request to the function will return
  319. the same messages. By default just the messages are returned,
  320. but when `with_categories` is set to ``True``, the return value will
  321. be a list of tuples in the form ``(category, message)`` instead.
  322. Filter the flashed messages to one or more categories by providing those
  323. categories in `category_filter`. This allows rendering categories in
  324. separate html blocks. The `with_categories` and `category_filter`
  325. arguments are distinct:
  326. * `with_categories` controls whether categories are returned with message
  327. text (``True`` gives a tuple, where ``False`` gives just the message text).
  328. * `category_filter` filters the messages down to only those matching the
  329. provided categories.
  330. See :ref:`message-flashing-pattern` for examples.
  331. .. versionchanged:: 0.3
  332. `with_categories` parameter added.
  333. .. versionchanged:: 0.9
  334. `category_filter` parameter added.
  335. :param with_categories: set to ``True`` to also receive categories.
  336. :param category_filter: whitelist of categories to limit return values
  337. """
  338. flashes = _request_ctx_stack.top.flashes
  339. if flashes is None:
  340. _request_ctx_stack.top.flashes = flashes = session.pop('_flashes') \
  341. if '_flashes' in session else []
  342. if category_filter:
  343. flashes = list(filter(lambda f: f[0] in category_filter, flashes))
  344. if not with_categories:
  345. return [x[1] for x in flashes]
  346. return flashes
  347. def send_file(filename_or_fp, mimetype=None, as_attachment=False,
  348. attachment_filename=None, add_etags=True,
  349. cache_timeout=None, conditional=False):
  350. """Sends the contents of a file to the client. This will use the
  351. most efficient method available and configured. By default it will
  352. try to use the WSGI server's file_wrapper support. Alternatively
  353. you can set the application's :attr:`~Flask.use_x_sendfile` attribute
  354. to ``True`` to directly emit an ``X-Sendfile`` header. This however
  355. requires support of the underlying webserver for ``X-Sendfile``.
  356. By default it will try to guess the mimetype for you, but you can
  357. also explicitly provide one. For extra security you probably want
  358. to send certain files as attachment (HTML for instance). The mimetype
  359. guessing requires a `filename` or an `attachment_filename` to be
  360. provided.
  361. Please never pass filenames to this function from user sources;
  362. you should use :func:`send_from_directory` instead.
  363. .. versionadded:: 0.2
  364. .. versionadded:: 0.5
  365. The `add_etags`, `cache_timeout` and `conditional` parameters were
  366. added. The default behavior is now to attach etags.
  367. .. versionchanged:: 0.7
  368. mimetype guessing and etag support for file objects was
  369. deprecated because it was unreliable. Pass a filename if you are
  370. able to, otherwise attach an etag yourself. This functionality
  371. will be removed in Flask 1.0
  372. .. versionchanged:: 0.9
  373. cache_timeout pulls its default from application config, when None.
  374. :param filename_or_fp: the filename of the file to send in `latin-1`.
  375. This is relative to the :attr:`~Flask.root_path`
  376. if a relative path is specified.
  377. Alternatively a file object might be provided in
  378. which case ``X-Sendfile`` might not work and fall
  379. back to the traditional method. Make sure that the
  380. file pointer is positioned at the start of data to
  381. send before calling :func:`send_file`.
  382. :param mimetype: the mimetype of the file if provided, otherwise
  383. auto detection happens.
  384. :param as_attachment: set to ``True`` if you want to send this file with
  385. a ``Content-Disposition: attachment`` header.
  386. :param attachment_filename: the filename for the attachment if it
  387. differs from the file's filename.
  388. :param add_etags: set to ``False`` to disable attaching of etags.
  389. :param conditional: set to ``True`` to enable conditional responses.
  390. :param cache_timeout: the timeout in seconds for the headers. When ``None``
  391. (default), this value is set by
  392. :meth:`~Flask.get_send_file_max_age` of
  393. :data:`~flask.current_app`.
  394. """
  395. mtime = None
  396. if isinstance(filename_or_fp, string_types):
  397. filename = filename_or_fp
  398. file = None
  399. else:
  400. from warnings import warn
  401. file = filename_or_fp
  402. filename = getattr(file, 'name', None)
  403. # XXX: this behavior is now deprecated because it was unreliable.
  404. # removed in Flask 1.0
  405. if not attachment_filename and not mimetype \
  406. and isinstance(filename, string_types):
  407. warn(DeprecationWarning('The filename support for file objects '
  408. 'passed to send_file is now deprecated. Pass an '
  409. 'attach_filename if you want mimetypes to be guessed.'),
  410. stacklevel=2)
  411. if add_etags:
  412. warn(DeprecationWarning('In future flask releases etags will no '
  413. 'longer be generated for file objects passed to the send_file '
  414. 'function because this behavior was unreliable. Pass '
  415. 'filenames instead if possible, otherwise attach an etag '
  416. 'yourself based on another value'), stacklevel=2)
  417. if filename is not None:
  418. if not os.path.isabs(filename):
  419. filename = os.path.join(current_app.root_path, filename)
  420. if mimetype is None and (filename or attachment_filename):
  421. mimetype = mimetypes.guess_type(filename or attachment_filename)[0]
  422. if mimetype is None:
  423. mimetype = 'application/octet-stream'
  424. headers = Headers()
  425. if as_attachment:
  426. if attachment_filename is None:
  427. if filename is None:
  428. raise TypeError('filename unavailable, required for '
  429. 'sending as attachment')
  430. attachment_filename = os.path.basename(filename)
  431. headers.add('Content-Disposition', 'attachment',
  432. filename=attachment_filename)
  433. if current_app.use_x_sendfile and filename:
  434. if file is not None:
  435. file.close()
  436. headers['X-Sendfile'] = filename
  437. headers['Content-Length'] = os.path.getsize(filename)
  438. data = None
  439. else:
  440. if file is None:
  441. file = open(filename, 'rb')
  442. mtime = os.path.getmtime(filename)
  443. headers['Content-Length'] = os.path.getsize(filename)
  444. data = wrap_file(request.environ, file)
  445. rv = current_app.response_class(data, mimetype=mimetype, headers=headers,
  446. direct_passthrough=True)
  447. # if we know the file modification date, we can store it as
  448. # the time of the last modification.
  449. if mtime is not None:
  450. rv.last_modified = int(mtime)
  451. rv.cache_control.public = True
  452. if cache_timeout is None:
  453. cache_timeout = current_app.get_send_file_max_age(filename)
  454. if cache_timeout is not None:
  455. rv.cache_control.max_age = cache_timeout
  456. rv.expires = int(time() + cache_timeout)
  457. if add_etags and filename is not None:
  458. try:
  459. rv.set_etag('%s-%s-%s' % (
  460. os.path.getmtime(filename),
  461. os.path.getsize(filename),
  462. adler32(
  463. filename.encode('utf-8') if isinstance(filename, text_type)
  464. else filename
  465. ) & 0xffffffff
  466. ))
  467. except OSError:
  468. warn('Access %s failed, maybe it does not exist, so ignore etags in '
  469. 'headers' % filename, stacklevel=2)
  470. if conditional:
  471. rv = rv.make_conditional(request)
  472. # make sure we don't send x-sendfile for servers that
  473. # ignore the 304 status code for x-sendfile.
  474. if rv.status_code == 304:
  475. rv.headers.pop('x-sendfile', None)
  476. return rv
  477. def safe_join(directory, filename):
  478. """Safely join `directory` and `filename`.
  479. Example usage::
  480. @app.route('/wiki/<path:filename>')
  481. def wiki_page(filename):
  482. filename = safe_join(app.config['WIKI_FOLDER'], filename)
  483. with open(filename, 'rb') as fd:
  484. content = fd.read() # Read and process the file content...
  485. :param directory: the base directory.
  486. :param filename: the untrusted filename relative to that directory.
  487. :raises: :class:`~werkzeug.exceptions.NotFound` if the resulting path
  488. would fall out of `directory`.
  489. """
  490. filename = posixpath.normpath(filename)
  491. for sep in _os_alt_seps:
  492. if sep in filename:
  493. raise NotFound()
  494. if os.path.isabs(filename) or \
  495. filename == '..' or \
  496. filename.startswith('../'):
  497. raise NotFound()
  498. return os.path.join(directory, filename)
  499. def send_from_directory(directory, filename, **options):
  500. """Send a file from a given directory with :func:`send_file`. This
  501. is a secure way to quickly expose static files from an upload folder
  502. or something similar.
  503. Example usage::
  504. @app.route('/uploads/<path:filename>')
  505. def download_file(filename):
  506. return send_from_directory(app.config['UPLOAD_FOLDER'],
  507. filename, as_attachment=True)
  508. .. admonition:: Sending files and Performance
  509. It is strongly recommended to activate either ``X-Sendfile`` support in
  510. your webserver or (if no authentication happens) to tell the webserver
  511. to serve files for the given path on its own without calling into the
  512. web application for improved performance.
  513. .. versionadded:: 0.5
  514. :param directory: the directory where all the files are stored.
  515. :param filename: the filename relative to that directory to
  516. download.
  517. :param options: optional keyword arguments that are directly
  518. forwarded to :func:`send_file`.
  519. """
  520. filename = safe_join(directory, filename)
  521. if not os.path.isabs(filename):
  522. filename = os.path.join(current_app.root_path, filename)
  523. try:
  524. if not os.path.isfile(filename):
  525. raise NotFound()
  526. except (TypeError, ValueError):
  527. raise BadRequest()
  528. options.setdefault('conditional', True)
  529. return send_file(filename, **options)
  530. def get_root_path(import_name):
  531. """Returns the path to a package or cwd if that cannot be found. This
  532. returns the path of a package or the folder that contains a module.
  533. Not to be confused with the package path returned by :func:`find_package`.
  534. """
  535. # Module already imported and has a file attribute. Use that first.
  536. mod = sys.modules.get(import_name)
  537. if mod is not None and hasattr(mod, '__file__'):
  538. return os.path.dirname(os.path.abspath(mod.__file__))
  539. # Next attempt: check the loader.
  540. loader = pkgutil.get_loader(import_name)
  541. # Loader does not exist or we're referring to an unloaded main module
  542. # or a main module without path (interactive sessions), go with the
  543. # current working directory.
  544. if loader is None or import_name == '__main__':
  545. return os.getcwd()
  546. # For .egg, zipimporter does not have get_filename until Python 2.7.
  547. # Some other loaders might exhibit the same behavior.
  548. if hasattr(loader, 'get_filename'):
  549. filepath = loader.get_filename(import_name)
  550. else:
  551. # Fall back to imports.
  552. __import__(import_name)
  553. mod = sys.modules[import_name]
  554. filepath = getattr(mod, '__file__', None)
  555. # If we don't have a filepath it might be because we are a
  556. # namespace package. In this case we pick the root path from the
  557. # first module that is contained in our package.
  558. if filepath is None:
  559. raise RuntimeError('No root path can be found for the provided '
  560. 'module "%s". This can happen because the '
  561. 'module came from an import hook that does '
  562. 'not provide file name information or because '
  563. 'it\'s a namespace package. In this case '
  564. 'the root path needs to be explicitly '
  565. 'provided.' % import_name)
  566. # filepath is import_name.py for a module, or __init__.py for a package.
  567. return os.path.dirname(os.path.abspath(filepath))
  568. def _matching_loader_thinks_module_is_package(loader, mod_name):
  569. """Given the loader that loaded a module and the module this function
  570. attempts to figure out if the given module is actually a package.
  571. """
  572. # If the loader can tell us if something is a package, we can
  573. # directly ask the loader.
  574. if hasattr(loader, 'is_package'):
  575. return loader.is_package(mod_name)
  576. # importlib's namespace loaders do not have this functionality but
  577. # all the modules it loads are packages, so we can take advantage of
  578. # this information.
  579. elif (loader.__class__.__module__ == '_frozen_importlib' and
  580. loader.__class__.__name__ == 'NamespaceLoader'):
  581. return True
  582. # Otherwise we need to fail with an error that explains what went
  583. # wrong.
  584. raise AttributeError(
  585. ('%s.is_package() method is missing but is required by Flask of '
  586. 'PEP 302 import hooks. If you do not use import hooks and '
  587. 'you encounter this error please file a bug against Flask.') %
  588. loader.__class__.__name__)
  589. def find_package(import_name):
  590. """Finds a package and returns the prefix (or None if the package is
  591. not installed) as well as the folder that contains the package or
  592. module as a tuple. The package path returned is the module that would
  593. have to be added to the pythonpath in order to make it possible to
  594. import the module. The prefix is the path below which a UNIX like
  595. folder structure exists (lib, share etc.).
  596. """
  597. root_mod_name = import_name.split('.')[0]
  598. loader = pkgutil.get_loader(root_mod_name)
  599. if loader is None or import_name == '__main__':
  600. # import name is not found, or interactive/main module
  601. package_path = os.getcwd()
  602. else:
  603. # For .egg, zipimporter does not have get_filename until Python 2.7.
  604. if hasattr(loader, 'get_filename'):
  605. filename = loader.get_filename(root_mod_name)
  606. elif hasattr(loader, 'archive'):
  607. # zipimporter's loader.archive points to the .egg or .zip
  608. # archive filename is dropped in call to dirname below.
  609. filename = loader.archive
  610. else:
  611. # At least one loader is missing both get_filename and archive:
  612. # Google App Engine's HardenedModulesHook
  613. #
  614. # Fall back to imports.
  615. __import__(import_name)
  616. filename = sys.modules[import_name].__file__
  617. package_path = os.path.abspath(os.path.dirname(filename))
  618. # In case the root module is a package we need to chop of the
  619. # rightmost part. This needs to go through a helper function
  620. # because of python 3.3 namespace packages.
  621. if _matching_loader_thinks_module_is_package(
  622. loader, root_mod_name):
  623. package_path = os.path.dirname(package_path)
  624. site_parent, site_folder = os.path.split(package_path)
  625. py_prefix = os.path.abspath(sys.prefix)
  626. if package_path.startswith(py_prefix):
  627. return py_prefix, package_path
  628. elif site_folder.lower() == 'site-packages':
  629. parent, folder = os.path.split(site_parent)
  630. # Windows like installations
  631. if folder.lower() == 'lib':
  632. base_dir = parent
  633. # UNIX like installations
  634. elif os.path.basename(parent).lower() == 'lib':
  635. base_dir = os.path.dirname(parent)
  636. else:
  637. base_dir = site_parent
  638. return base_dir, package_path
  639. return None, package_path
  640. class locked_cached_property(object):
  641. """A decorator that converts a function into a lazy property. The
  642. function wrapped is called the first time to retrieve the result
  643. and then that calculated result is used the next time you access
  644. the value. Works like the one in Werkzeug but has a lock for
  645. thread safety.
  646. """
  647. def __init__(self, func, name=None, doc=None):
  648. self.__name__ = name or func.__name__
  649. self.__module__ = func.__module__
  650. self.__doc__ = doc or func.__doc__
  651. self.func = func
  652. self.lock = RLock()
  653. def __get__(self, obj, type=None):
  654. if obj is None:
  655. return self
  656. with self.lock:
  657. value = obj.__dict__.get(self.__name__, _missing)
  658. if value is _missing:
  659. value = self.func(obj)
  660. obj.__dict__[self.__name__] = value
  661. return value
  662. class _PackageBoundObject(object):
  663. def __init__(self, import_name, template_folder=None, root_path=None):
  664. #: The name of the package or module. Do not change this once
  665. #: it was set by the constructor.
  666. self.import_name = import_name
  667. #: location of the templates. ``None`` if templates should not be
  668. #: exposed.
  669. self.template_folder = template_folder
  670. if root_path is None:
  671. root_path = get_root_path(self.import_name)
  672. #: Where is the app root located?
  673. self.root_path = root_path
  674. self._static_folder = None
  675. self._static_url_path = None
  676. def _get_static_folder(self):
  677. if self._static_folder is not None:
  678. return os.path.join(self.root_path, self._static_folder)
  679. def _set_static_folder(self, value):
  680. self._static_folder = value
  681. static_folder = property(_get_static_folder, _set_static_folder, doc='''
  682. The absolute path to the configured static folder.
  683. ''')
  684. del _get_static_folder, _set_static_folder
  685. def _get_static_url_path(self):
  686. if self._static_url_path is not None:
  687. return self._static_url_path
  688. if self.static_folder is not None:
  689. return '/' + os.path.basename(self.static_folder)
  690. def _set_static_url_path(self, value):
  691. self._static_url_path = value
  692. static_url_path = property(_get_static_url_path, _set_static_url_path)
  693. del _get_static_url_path, _set_static_url_path
  694. @property
  695. def has_static_folder(self):
  696. """This is ``True`` if the package bound object's container has a
  697. folder for static files.
  698. .. versionadded:: 0.5
  699. """
  700. return self.static_folder is not None
  701. @locked_cached_property
  702. def jinja_loader(self):
  703. """The Jinja loader for this package bound object.
  704. .. versionadded:: 0.5
  705. """
  706. if self.template_folder is not None:
  707. return FileSystemLoader(os.path.join(self.root_path,
  708. self.template_folder))
  709. def get_send_file_max_age(self, filename):
  710. """Provides default cache_timeout for the :func:`send_file` functions.
  711. By default, this function returns ``SEND_FILE_MAX_AGE_DEFAULT`` from
  712. the configuration of :data:`~flask.current_app`.
  713. Static file functions such as :func:`send_from_directory` use this
  714. function, and :func:`send_file` calls this function on
  715. :data:`~flask.current_app` when the given cache_timeout is ``None``. If a
  716. cache_timeout is given in :func:`send_file`, that timeout is used;
  717. otherwise, this method is called.
  718. This allows subclasses to change the behavior when sending files based
  719. on the filename. For example, to set the cache timeout for .js files
  720. to 60 seconds::
  721. class MyFlask(flask.Flask):
  722. def get_send_file_max_age(self, name):
  723. if name.lower().endswith('.js'):
  724. return 60
  725. return flask.Flask.get_send_file_max_age(self, name)
  726. .. versionadded:: 0.9
  727. """
  728. return total_seconds(current_app.send_file_max_age_default)
  729. def send_static_file(self, filename):
  730. """Function used internally to send static files from the static
  731. folder to the browser.
  732. .. versionadded:: 0.5
  733. """
  734. if not self.has_static_folder:
  735. raise RuntimeError('No static folder for this object')
  736. # Ensure get_send_file_max_age is called in all cases.
  737. # Here, we ensure get_send_file_max_age is called for Blueprints.
  738. cache_timeout = self.get_send_file_max_age(filename)
  739. return send_from_directory(self.static_folder, filename,
  740. cache_timeout=cache_timeout)
  741. def open_resource(self, resource, mode='rb'):
  742. """Opens a resource from the application's resource folder. To see
  743. how this works, consider the following folder structure::
  744. /myapplication.py
  745. /schema.sql
  746. /static
  747. /style.css
  748. /templates
  749. /layout.html
  750. /index.html
  751. If you want to open the :file:`schema.sql` file you would do the
  752. following::
  753. with app.open_resource('schema.sql') as f:
  754. contents = f.read()
  755. do_something_with(contents)
  756. :param resource: the name of the resource. To access resources within
  757. subfolders use forward slashes as separator.
  758. :param mode: resource file opening mode, default is 'rb'.
  759. """
  760. if mode not in ('r', 'rb'):
  761. raise ValueError('Resources can only be opened for reading')
  762. return open(os.path.join(self.root_path, resource), mode)
  763. def total_seconds(td):
  764. """Returns the total seconds from a timedelta object.
  765. :param timedelta td: the timedelta to be converted in seconds
  766. :returns: number of seconds
  767. :rtype: int
  768. """
  769. return td.days * 60 * 60 * 24 + td.seconds