diff --git a/flask.py b/flask.py index 68e25ade..08376993 100644 --- a/flask.py +++ b/flask.py @@ -11,10 +11,10 @@ """ import os import sys -import pkg_resources + from threading import local from contextlib import contextmanager -from jinja2 import Environment, PackageLoader +from jinja2 import Environment, PackageLoader, FileSystemLoader from werkzeug import Request as RequestBase, Response as ResponseBase, \ LocalStack, LocalProxy, create_environ, cached_property, \ SharedDataMiddleware @@ -27,6 +27,15 @@ from werkzeug.contrib.securecookie import SecureCookie from werkzeug import abort, redirect from jinja2 import Markup, escape +# use pkg_resource if that works, otherwise fall back to cwd. The +# current working directory is generally not reliable with the notable +# exception of google appengine. +try: + import pkg_resources + pkg_resources.resource_stream +except (ImportError, AttributeError): + pkg_resources = None + class Request(RequestBase): """The request object used by default in flask. Remembers the @@ -202,6 +211,10 @@ class Flask(object): #: it was set by the constructor. self.package_name = package_name + #: where is the app root located? + self.root_path = os.path.abspath(os.path.dirname( + sys.modules[self.package_name].__file__)) + #: a dictionary of all view functions registered. The keys will #: be function names which are also used to generate URLs and #: the values are the function objects themselves. @@ -242,8 +255,12 @@ class Flask(object): if self.static_path is not None: self.url_map.add(Rule(self.static_path + '/', build_only=True, endpoint='static')) + if pkg_resources is not None: + target = (self.package_name, 'static') + else: + target = os.path.join(self.root_path, 'static') self.wsgi_app = SharedDataMiddleware(self.wsgi_app, { - self.static_path: (self.package_name, 'static') + self.static_path: target }) #: the Jinja2 environment. It is created from the @@ -262,6 +279,8 @@ class Flask(object): `templates` folder. To add other loaders it's possible to override this method. """ + if pkg_resources is None: + return FileSystemLoader(os.path.join(self.root_path, 'templates')) return PackageLoader(self.package_name) def update_template_context(self, context): @@ -323,6 +342,8 @@ class Flask(object): :param resource: the name of the resource. To access resources within subfolders use forward slashes as separator. """ + if pkg_resources is None: + return open(os.path.join(self.root_path, resource), 'rb') return pkg_resources.resource_stream(self.package_name, resource) def open_session(self, request):