def index(self, username=None):
if cherrypy.session.get('auth', False):
raise cherrypy.HTTPRedirect('/update')
else:
return {'username': username}
python类HTTPRedirect()的实例源码
def update(self):
if not cherrypy.session.get('auth', False):
raise cherrypy.HTTPRedirect('/')
else:
return vars(cherrypy.session['user'])
def logout(self):
cherrypy.lib.sessions.expire()
raise cherrypy.HTTPRedirect('/')
def index(self):
""" The main page
"""
product_id = Config.get_config(Config.FIELD_PRODUCT_ID)
client_id = Config.get_config(Config.FIELD_CLIENT_ID)
scope_data = json.dumps(
{"alexa:all": {
"productID": product_id,
"productInstanceAttributes": {
"deviceSerialNumber": "001"}
}}
)
callback = cherrypy.url() + "code"
payload = {
"client_id": client_id,
"scope": "alexa:all",
"scope_data": scope_data,
"response_type": "code",
"redirect_uri": callback
}
req = requests.Request(
'GET', AlexaService.AMAZON_BASE_URL, params=payload
)
raise cherrypy.HTTPRedirect(req.prepare().url)
def conv_response(resp):
if not isinstance(resp, Response):
return as_bytes(resp)
cookie = cherrypy.response.cookie
for header, value in resp.headers:
if header == 'Set-Cookie':
cookie_obj = SimpleCookie(value)
for name in cookie_obj:
morsel = cookie_obj[name]
cookie[name] = morsel.value
for key in ['expires', 'path', 'comment', 'domain', 'max-age',
'secure', 'version']:
if morsel[key]:
cookie[name][key] = morsel[key]
_stat = int(resp._status.split(' ')[0])
# if self.mako_lookup and self.mako_template:
# argv["message"] = message
# mte = self.mako_lookup.get_template(self.mako_template)
# return [mte.render(**argv)]
if _stat < 300:
cherrypy.response.status = _stat
for key, val in resp.headers:
cherrypy.response.headers[key] = val
return as_bytes(resp.message)
elif 300 <= _stat < 400:
raise cherrypy.HTTPRedirect(resp.message, status=_stat)
else:
raise cherrypy.HTTPError(_stat, message=resp.message)
def protect(self, bypass_in_demo_mode=False):
"""Returns user if he's logged in, otherwise redirects to login page"""
# Check current logged in user
user = self.current_user()
# If allowed, return None when demo mode
if user is not None or (bypass_in_demo_mode and self.core.config.get("demo_mode")):
return user
if user is None:
raise cherrypy.HTTPRedirect("/settings/login")
def login(self, **kwargs):
"""Login web page, available at /settings/login"""
if "user" in kwargs and "pass" in kwargs:
if self.core.accounts.login_user(kwargs["user"], kwargs["pass"]) is not None:
raise cherrypy.HTTPRedirect("/settings")
else:
return self.render("/settings/login.html", error=self.core.lang.get("error_wrong_username_or_password"))
return self.render("/settings/login.html")
def check_auth(*args, **kwargs):
"""A tool that looks in config for 'auth.require'. If found and it
is not None, a login is required and the entry is evaluated as a list of
conditions that the user must fulfill"""
conditions = cherrypy.request.config.get('auth.require', None)
if conditions is not None:
username = cherrypy.session.get(SESSION_KEY)
if username:
cherrypy.request.login = username
for condition in conditions:
# A condition is just a callable that returns true or false
if not condition():
raise cherrypy.HTTPRedirect("/auth/login")
else:
raise cherrypy.HTTPRedirect("/auth/login")
def login(self, username=None, password=None, from_page="/"):
if username is None or password is None:
return self.get_loginform("", from_page=from_page)
error_msg = check_credentials(username, password)
if error_msg:
return self.get_loginform(username, error_msg, from_page)
else:
cherrypy.session[SESSION_KEY] = cherrypy.request.login = username
self.on_login(username)
raise cherrypy.HTTPRedirect(from_page or "/")
def logout(self, from_page="/"):
sess = cherrypy.session
username = sess.get(SESSION_KEY, None)
sess[SESSION_KEY] = None
if username:
cherrypy.request.login = None
self.on_logout(username)
raise cherrypy.HTTPRedirect(from_page or "/")
#from auth import AuthController, require, member_of, name_is
def check_auth(*args, **kwargs):
"""A tool that looks in config for 'auth.require'. If found and it
is not None, a login is required and the entry is evaluated as a list of
conditions that the user must fulfill"""
conditions = cherrypy.request.config.get('auth.require', None)
if conditions is not None:
username = cherrypy.session.get(SESSION_KEY)
if username:
cherrypy.request.login = username
for condition in conditions:
# A condition is just a callable that returns true or false
if not condition():
raise cherrypy.HTTPRedirect("/auth/login")
else:
raise cherrypy.HTTPRedirect("/auth/login")
def login(self, username=None, password=None, from_page="/"):
if username is None or password is None:
return self.get_loginform("", from_page=from_page)
error_msg = check_credentials(username, password)
if error_msg:
return self.get_loginform(username, error_msg, from_page)
else:
cherrypy.session[SESSION_KEY] = cherrypy.request.login = username
self.on_login(username)
raise cherrypy.HTTPRedirect(from_page or "/")
def pause(self, namespace):
logging.statistics.get(namespace, {})['Enabled'] = False
raise cherrypy.HTTPRedirect('./')
def resume(self, namespace):
logging.statistics.get(namespace, {})['Enabled'] = True
raise cherrypy.HTTPRedirect('./')
def validate_since():
"""Validate the current Last-Modified against If-Modified-Since headers.
If no code has set the Last-Modified response header, then no validation
will be performed.
"""
response = cherrypy.serving.response
lastmod = response.headers.get('Last-Modified')
if lastmod:
status, reason, msg = _httputil.valid_status(response.status)
request = cherrypy.serving.request
since = request.headers.get('If-Unmodified-Since')
if since and since != lastmod:
if (status >= 200 and status <= 299) or status == 412:
raise cherrypy.HTTPError(412)
since = request.headers.get('If-Modified-Since')
if since and since == lastmod:
if (status >= 200 and status <= 299) or status == 304:
if request.method in ('GET', 'HEAD'):
raise cherrypy.HTTPRedirect([], 304)
else:
raise cherrypy.HTTPError(412)
# Tool code #
def do_logout(self, from_page='..', **kwargs):
"""Logout. May raise redirect, or return True if request handled."""
sess = cherrypy.session
username = sess.get(self.session_key)
sess[self.session_key] = None
if username:
cherrypy.serving.request.login = None
self.on_logout(username)
raise cherrypy.HTTPRedirect(from_page)
def redirect(self, url):
raise cherrypy.HTTPRedirect(url)
def handle_error(self):
"""Handle the last unanticipated exception. (Core)"""
try:
self.hooks.run('before_error_response')
if self.error_response:
self.error_response()
self.hooks.run('after_error_response')
cherrypy.serving.response.finalize()
except cherrypy.HTTPRedirect:
inst = sys.exc_info()[1]
inst.set_response()
cherrypy.serving.response.finalize()
# ------------------------- Properties ------------------------- #
def index(self):
raise cherrypy.HTTPRedirect("/search")
def logged_in(f: callable, *args, **kwargs):
if cmd_args.no_anonymous_access:
if not cherrypy.session.get('logged_in'):
url = cherrypy.url() # http://0.0.0.0:8080/dbs
splits = url.split('/') # ['https:', '', '0.0.0.0:8080', 'dbs']
if len(splits) > 3 and splits[3] in ['dbs', 'metrics', 'logs']:
raise cherrypy.HTTPRedirect('/login' + ('?returl=/' + '/'.join(splits[3:])))
else:
raise cherrypy.HTTPRedirect('/login')
return f(*args, **kwargs)