helpers.py 39 KB

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