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", "run_wsgi_app"]
30
from google.appengine.api import users
31
from google.appengine.ext import webapp
34
def login_required(handler_method):
35
"""A decorator to require that a user be logged in to access a handler.
37
To use it, decorate your get() method like this:
41
user = users.get_current_user(self)
42
self.response.out.write('Hello, ' + user.nickname())
44
We will redirect to a login page if the user is not logged in. We always
45
redirect to the request URI, and Google Accounts only redirects back as a GET
46
request, so this should not be used for POSTs.
48
def check_login(self, *args):
49
if self.request.method != 'GET':
50
raise webapp.Error('The check_login decorator can only be used for GET '
52
user = users.get_current_user()
54
self.redirect(users.create_login_url(self.request.uri))
57
handler_method(self, *args)
61
def run_wsgi_app(application):
62
"""Runs your WSGI-compliant application object in a CGI environment.
64
Compared to wsgiref.handlers.CGIHandler().run(application), this
65
function takes some shortcuts. Those are possible because the
66
app server makes stronger promises than the CGI standard.
68
env = dict(os.environ)
69
env["wsgi.input"] = sys.stdin
70
env["wsgi.errors"] = sys.stderr
71
env["wsgi.version"] = (1, 0)
72
env["wsgi.run_once"] = True
73
env["wsgi.url_scheme"] = wsgiref.util.guess_scheme(env)
74
env["wsgi.multithread"] = False
75
env["wsgi.multiprocess"] = False
76
result = application(env, _start_response)
77
if result is not None:
79
sys.stdout.write(data)
82
def _start_response(status, headers, exc_info=None):
83
"""A start_response() callable as specified by PEP 333"""
84
if exc_info is not None:
85
raise exc_info[0], exc_info[1], exc_info[2]
86
print "Status: %s" % status
87
for name, val in headers:
88
print "%s: %s" % (name, val)
90
return sys.stdout.write