From c4f64c1c475badaeef009ad46846e32a8e5c9b66 Mon Sep 17 00:00:00 2001 From: Justin Quick Date: Fri, 2 Jul 2010 15:10:32 -0400 Subject: [PATCH] working import layout for module --- flask/__init__.py | 47 ++++++----------------------------------------- flask/app.py | 24 ++++++++++++++++++++++-- flask/conf.py | 4 ++++ flask/ctx.py | 5 +++++ flask/globals.py | 8 ++++++++ flask/helpers.py | 26 ++++++++++++++++++++++---- flask/module.py | 1 + flask/session.py | 3 +++ flask/wrappers.py | 7 +++++++ 9 files changed, 78 insertions(+), 47 deletions(-) create mode 100644 flask/globals.py diff --git a/flask/__init__.py b/flask/__init__.py index f7ae2551..e20f1206 100644 --- a/flask/__init__.py +++ b/flask/__init__.py @@ -9,50 +9,15 @@ :copyright: (c) 2010 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ -from __future__ import with_statement -import os -import sys -import mimetypes -from datetime import datetime, timedelta - -# this is a workaround for appengine. Do not remove this import -import werkzeug - -from itertools import chain -from threading import Lock -from jinja2 import Environment, PackageLoader, FileSystemLoader -from werkzeug import Request as RequestBase, Response as ResponseBase, \ - LocalStack, LocalProxy, create_environ, SharedDataMiddleware, \ - ImmutableDict, cached_property, wrap_file, Headers, \ - import_string -from werkzeug.routing import Map, Rule -from werkzeug.exceptions import HTTPException, InternalServerError -from werkzeug.contrib.securecookie import SecureCookie - - # utilities we import from Werkzeug and Jinja2 that are unused # in the module but are exported as public interface. 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 - -# a lock used for logger initialization -_logger_lock = Lock() - - - -# context locals -_request_ctx_stack = LocalStack() -current_app = LocalProxy(lambda: _request_ctx_stack.top.app) -request = LocalProxy(lambda: _request_ctx_stack.top.request) -session = LocalProxy(lambda: _request_ctx_stack.top.session) -g = LocalProxy(lambda: _request_ctx_stack.top.g) +from flask.app import Flask +from flask.helpers import url_for, jsonify, json_available, flash, send_file, \ + get_flashed_messages, render_template, render_template, render_template_string, \ + get_template_attribute +from flask.globals import current_app, g, request, session, _request_ctx_stack +from flask.module import Module diff --git a/flask/app.py b/flask/app.py index f3e1f73c..654a96f4 100644 --- a/flask/app.py +++ b/flask/app.py @@ -1,3 +1,23 @@ +from threading import Lock +from datetime import timedelta, datetime +from itertools import chain + +from jinja2 import Environment, PackageLoader, FileSystemLoader +from werkzeug import ImmutableDict, SharedDataMiddleware, create_environ +from werkzeug.routing import Map, Rule +from werkzeug.exceptions import HTTPException, InternalServerError + +from flask.helpers import _PackageBoundObject, url_for, get_flashed_messages, \ + _tojson_filter, get_pkg_resources +from flask.wrappers import Request, Response +from flask.conf import ConfigAttribute, Config +from flask.ctx import _default_template_ctx_processor, _RequestContext +from flask.globals import _request_ctx_stack, request +from flask.session import Session, _NullSession +from flask.module import _ModuleSetupState + +# a lock used for logger initialization +_logger_lock = Lock() class Flask(_PackageBoundObject): @@ -219,7 +239,7 @@ class Flask(_PackageBoundObject): if self.static_path is not None: self.add_url_rule(self.static_path + '/', build_only=True, endpoint='static') - if pkg_resources is not None: + if get_pkg_resources() is not None: target = (self.import_name, 'static') else: target = os.path.join(self.root_path, 'static') @@ -279,7 +299,7 @@ class Flask(_PackageBoundObject): `templates` folder. To add other loaders it's possible to override this method. """ - if pkg_resources is None: + if get_pkg_resources() is None: return FileSystemLoader(os.path.join(self.root_path, 'templates')) return PackageLoader(self.import_name) diff --git a/flask/conf.py b/flask/conf.py index e757212c..90414155 100644 --- a/flask/conf.py +++ b/flask/conf.py @@ -1,3 +1,7 @@ +import os +import sys + +from werkzeug import import_string class ConfigAttribute(object): diff --git a/flask/ctx.py b/flask/ctx.py index 88f61394..f3eab16a 100644 --- a/flask/ctx.py +++ b/flask/ctx.py @@ -1,3 +1,8 @@ +from werkzeug.exceptions import HTTPException + +from flask.wrappers import _RequestGlobals +from flask.globals import _request_ctx_stack +from flask.session import _NullSession class _RequestContext(object): diff --git a/flask/globals.py b/flask/globals.py new file mode 100644 index 00000000..11fdf0b3 --- /dev/null +++ b/flask/globals.py @@ -0,0 +1,8 @@ +from werkzeug import LocalStack, LocalProxy + +# context locals +_request_ctx_stack = LocalStack() +current_app = LocalProxy(lambda: _request_ctx_stack.top.app) +request = LocalProxy(lambda: _request_ctx_stack.top.request) +session = LocalProxy(lambda: _request_ctx_stack.top.session) +g = LocalProxy(lambda: _request_ctx_stack.top.g) \ No newline at end of file diff --git a/flask/helpers.py b/flask/helpers.py index 882cc544..58dd2094 100644 --- a/flask/helpers.py +++ b/flask/helpers.py @@ -1,3 +1,7 @@ +import os +import sys +import mimetypes + # try to load the best simplejson implementation available. If JSON # is not installed, we add a failing class. json_available = True @@ -9,6 +13,12 @@ except ImportError: except ImportError: json_available = False +from werkzeug import Headers, wrap_file + +from flask.globals import session, _request_ctx_stack, current_app, request +from flask.wrappers import Response + + def _assert_have_json(): """Helper function that fails if JSON is unavailable.""" if not json_available: @@ -57,6 +67,17 @@ def jsonify(*args, **kwargs): return current_app.response_class(json.dumps(dict(*args, **kwargs), indent=None if request.is_xhr else 2), mimetype='application/json') +def get_pkg_resources(): + """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): + return + return pkg_resources def url_for(endpoint, **values): @@ -164,7 +185,6 @@ def get_flashed_messages(with_categories=False): return flashes - def send_file(filename_or_fp, mimetype=None, as_attachment=False, attachment_filename=None): """Sends the contents of a file to the client. This will use the @@ -262,7 +282,6 @@ def render_template_string(source, **context): return current_app.jinja_env.from_string(source).render(context) - def _get_package_path(name): """Returns the path to a package or cwd if that cannot be found.""" try: @@ -271,7 +290,6 @@ def _get_package_path(name): return os.getcwd() - class _PackageBoundObject(object): def __init__(self, import_name): @@ -304,7 +322,7 @@ class _PackageBoundObject(object): :param resource: the name of the resource. To access resources within subfolders use forward slashes as separator. """ + pkg_resources = get_pkg_resources() if pkg_resources is None: return open(os.path.join(self.root_path, resource), 'rb') return pkg_resources.resource_stream(self.import_name, resource) - diff --git a/flask/module.py b/flask/module.py index 2d53f3a9..3d691316 100644 --- a/flask/module.py +++ b/flask/module.py @@ -1,3 +1,4 @@ +from flask.helpers import _PackageBoundObject class _ModuleSetupState(object): diff --git a/flask/session.py b/flask/session.py index 11951962..cd0d5d29 100644 --- a/flask/session.py +++ b/flask/session.py @@ -1,3 +1,6 @@ +from werkzeug.contrib.securecookie import SecureCookie + + class Session(SecureCookie): """Expands the session with support for switching between permanent and non-permanent sessions. diff --git a/flask/wrappers.py b/flask/wrappers.py index 933b28a8..091c708e 100644 --- a/flask/wrappers.py +++ b/flask/wrappers.py @@ -1,3 +1,9 @@ +from werkzeug import Request as RequestBase, Response as ResponseBase, \ + cached_property + +from helpers import json + + class Request(RequestBase): """The request object used by default in flask. Remembers the matched endpoint and view arguments. @@ -35,6 +41,7 @@ class Request(RequestBase): parsed JSON data. """ if __debug__: + from flask.helpers import _assert_have_json _assert_have_json() if self.mimetype == 'application/json': return json.loads(self.data)