helpers.py 33 KB

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