Add google appengine to repo
[frozenviper.git] / google_appengine / google / appengine / ext / webapp / util.py
blob93e3608cc97f6746622208ebdab5381be215eac7
1 #!/usr/bin/env python
3 # Copyright 2007 Google Inc.
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
18 """Convience functions for the Webapp framework."""
24 __all__ = ['login_required',
25 'run_wsgi_app',
26 'add_wsgi_middleware',
27 'run_bare_wsgi_app',
30 import os
31 import sys
32 import wsgiref.util
34 from google.appengine.api import users
35 from google.appengine.api import lib_config
36 from google.appengine.ext import webapp
39 def login_required(handler_method):
40 """A decorator to require that a user be logged in to access a handler.
42 To use it, decorate your get() method like this:
44 @login_required
45 def get(self):
46 user = users.get_current_user(self)
47 self.response.out.write('Hello, ' + user.nickname())
49 We will redirect to a login page if the user is not logged in. We always
50 redirect to the request URI, and Google Accounts only redirects back as a GET
51 request, so this should not be used for POSTs.
52 """
53 def check_login(self, *args):
54 if self.request.method != 'GET':
55 raise webapp.Error('The check_login decorator can only be used for GET '
56 'requests')
57 user = users.get_current_user()
58 if not user:
59 self.redirect(users.create_login_url(self.request.uri))
60 return
61 else:
62 handler_method(self, *args)
63 return check_login
66 _config_handle = lib_config.register(
67 'webapp',
68 {'add_wsgi_middleware': lambda app: app})
71 def run_wsgi_app(application):
72 """Runs your WSGI-compliant application object in a CGI environment.
74 Compared to wsgiref.handlers.CGIHandler().run(application), this
75 function takes some shortcuts. Those are possible because the
76 app server makes stronger promises than the CGI standard.
78 Also, this function may wrap custom WSGI middleware around the
79 application. (You can use run_bare_wsgi_app() to run an application
80 without adding WSGI middleware, and add_wsgi_middleware() to wrap
81 the configured WSGI middleware around an application without running
82 it. This function is merely a convenient combination of the latter
83 two.)
85 To configure custom WSGI middleware, define a function
86 webapp_add_wsgi_middleware(app) to your appengine_config.py file in
87 your application root directory:
89 def webapp_add_wsgi_middleware(app):
90 app = MiddleWareClassOne(app)
91 app = MiddleWareClassTwo(app)
92 return app
94 You must import the middleware classes elsewhere in the file. If
95 the function is not found, no WSGI middleware is added.
96 """
97 run_bare_wsgi_app(add_wsgi_middleware(application))
100 def add_wsgi_middleware(application):
101 """Wrap WSGI middleware around a WSGI application object."""
102 return _config_handle.add_wsgi_middleware(application)
105 def run_bare_wsgi_app(application):
106 """Like run_wsgi_app() but doesn't add WSGI middleware."""
107 env = dict(os.environ)
108 env["wsgi.input"] = sys.stdin
109 env["wsgi.errors"] = sys.stderr
110 env["wsgi.version"] = (1, 0)
111 env["wsgi.run_once"] = True
112 env["wsgi.url_scheme"] = wsgiref.util.guess_scheme(env)
113 env["wsgi.multithread"] = False
114 env["wsgi.multiprocess"] = False
115 result = application(env, _start_response)
116 if result is not None:
117 for data in result:
118 sys.stdout.write(data)
121 def _start_response(status, headers, exc_info=None):
122 """A start_response() callable as specified by PEP 333"""
123 if exc_info is not None:
124 raise exc_info[0], exc_info[1], exc_info[2]
125 print "Status: %s" % status
126 for name, val in headers:
127 print "%s: %s" % (name, val)
128 print
129 return sys.stdout.write