def scandeletemulti(self, ids, confirm=None):
dbh = SpiderFootDb(self.config)
names = list()
for id in ids.split(','):
res = dbh.scanInstanceGet(id)
names.append(res[0])
if res is None:
return self.error("Scan ID not found (" + id + ").")
if res[5] in [ "RUNNING", "STARTING", "STARTED" ]:
return self.error("You cannot delete running scans.")
if confirm is not None:
for id in ids.split(','):
dbh.scanInstanceDelete(id)
raise cherrypy.HTTPRedirect("/")
else:
templ = Template(filename='dyn/scandelete.tmpl', lookup=self.lookup)
return templ.render(id=None, name=None, ids=ids.split(','), names=names,
pageid="SCANLIST", docroot=self.docroot)
python类HTTPRedirect()的实例源码
def display_log(self, root, issuer="", profile="", testid=""):
"""
:param root:
:param issuer:
:param profile:
:param testid:
:return:
"""
logger.info(
"display_log root: '{root}' issuer: '{iss}', profile: '{prof}' "
"testid: '{tid}'".format(
root=root, iss=issuer, prof=profile, tid=testid))
if testid:
path = os.path.join(root, issuer, profile, testid).replace(":",
"%3A")
raise cherrypy.HTTPRedirect(path)
else:
if issuer:
return self._display(root, issuer, profile)
else:
return b'No saved logs'
def index(self):
scope="alexa_all"
sd = json.dumps({
"alexa:all": {
"productID": ProductID,
"productInstanceAttributes": {
"deviceSerialNumber": "001"
}
}
})
url = "https://www.amazon.com/ap/oa"
callback = cherrypy.url() + "code"
payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
req = requests.Request('GET', url, params=payload)
p = req.prepare()
raise cherrypy.HTTPRedirect(p.url)
def index(self):
sd = json.dumps({
"alexa:all": {
"productID": config['alexa']['Device_Type_ID'],
"productInstanceAttributes": {
"deviceSerialNumber": hashlib.sha256(str(uuid.getnode()).encode()).hexdigest()
}
}
})
url = "https://www.amazon.com/ap/oa"
callback = cherrypy.url() + "code"
payload = {
"client_id": config['alexa']['Client_ID'],
"scope": "alexa:all",
"scope_data": sd,
"response_type": "code",
"redirect_uri": callback
}
req = requests.Request('GET', url, params=payload)
prepared_req = req.prepare()
raise cherrypy.HTTPRedirect(prepared_req.url)
def scandeletemulti(self, ids, confirm=None):
dbh = SpiderFootDb(self.config)
names = list()
for id in ids.split(','):
res = dbh.scanInstanceGet(id)
names.append(res[0])
if res is None:
return self.error("Scan ID not found (" + id + ").")
if res[5] in [ "RUNNING", "STARTING", "STARTED" ]:
return self.error("You cannot delete running scans.")
if confirm is not None:
for id in ids.split(','):
dbh.scanInstanceDelete(id)
raise cherrypy.HTTPRedirect("/")
else:
templ = Template(filename='dyn/scandelete.tmpl', lookup=self.lookup)
return templ.render(id=None, name=None, ids=ids.split(','), names=names,
pageid="SCANLIST", docroot=self.docroot)
def index(self):
scope="alexa_all"
sd = json.dumps({
"alexa:all": {
"productID": ProductID,
"productInstanceAttributes": {
"deviceSerialNumber": "001"
}
}
})
url = "https://www.amazon.com/ap/oa"
callback = cherrypy.url() + "code"
payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
req = requests.Request('GET', url, params=payload)
p = req.prepare()
raise cherrypy.HTTPRedirect(p.url)
def index(self):
scope="alexa_all"
sd = json.dumps({
"alexa:all": {
"productID": ProductID,
"productInstanceAttributes": {
"deviceSerialNumber": "001"
}
}
})
url = "https://www.amazon.com/ap/oa"
callback = cherrypy.url() + "code"
payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
req = requests.Request('GET', url, params=payload)
p = req.prepare()
raise cherrypy.HTTPRedirect(p.url)
def index(self):
scope="alexa_all"
sd = json.dumps({
"alexa:all": {
"productID": ProductID,
"productInstanceAttributes": {
"deviceSerialNumber": "001"
}
}
})
url = "https://www.amazon.com/ap/oa"
callback = cherrypy.url() + "code"
payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
req = requests.Request('GET', url, params=payload)
p = req.prepare()
raise cherrypy.HTTPRedirect(p.url)
def index(self):
scope="alexa_all"
sd = json.dumps({
"alexa:all": {
"productID": ProductID,
"productInstanceAttributes": {
"deviceSerialNumber": "001"
}
}
})
url = "https://www.amazon.com/ap/oa"
# Establish AMZN callback URL
callback = cherrypy.url() + "code"
payload = { "client_id" : Client_ID,
"scope" : "alexa:all",
"scope_data" : sd,
"response_type" : "code",
"redirect_uri" : callback }
req = requests.Request('GET', url, params=payload)
p = req.prepare()
raise cherrypy.HTTPRedirect(p.url)
def index(self):
scope="alexa_all"
sd = json.dumps({
"alexa:all": {
"productID": ProductID,
"productInstanceAttributes": {
"deviceSerialNumber": "001"
}
}
})
url = "https://www.amazon.com/ap/oa"
callback = cherrypy.url() + "code"
payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
req = requests.Request('GET', url, params=payload)
p = req.prepare()
raise cherrypy.HTTPRedirect(p.url)
def index(self, uid='', iss=''):
link = ''
if iss:
link = iss
elif uid:
try:
link = self.rph.find_srv_discovery_url(
resource="acct:{}".format(uid))
except requests.ConnectionError:
raise cherrypy.HTTPError(
message="Webfinger lookup failed, connection error")
else:
fname = os.path.join(self.html_home, 'opbyuid.html')
return as_bytes(open(fname, 'r').read())
if link:
resp_headers = self.rph.begin(link)
raise cherrypy.HTTPRedirect(resp_headers['Location'])
def index(self):
scope = "alexa_all"
sd = json.dumps({
"alexa:all": {
"productID": ProductID,
"productInstanceAttributes": {
"deviceSerialNumber": "001"
}
}
})
url = "https://www.amazon.com/ap/oa"
callback = cherrypy.url() + "code"
payload = {"client_id": Client_ID, "scope": "alexa:all",
"scope_data": sd, "response_type": "code", "redirect_uri": callback}
req = requests.Request('GET', url, params=payload)
p = req.prepare()
raise cherrypy.HTTPRedirect(p.url)
def index(self):
scope="alexa_all"
sd = json.dumps({
"alexa:all": {
"productID": ProductID,
"productInstanceAttributes": {
"deviceSerialNumber": "001"
}
}
})
url = "https://www.amazon.com/ap/oa"
callback = cherrypy.url() + "code"
payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
req = requests.Request('GET', url, params=payload)
p = req.prepare()
raise cherrypy.HTTPRedirect(p.url)
def do_login(self, username, password, from_page='..', **kwargs):
"""Login. May raise redirect, or return True if request handled."""
response = cherrypy.serving.response
error_msg = self.check_username_and_password(username, password)
if error_msg:
body = self.login_screen(from_page, username, error_msg)
response.body = body
if 'Content-Length' in response.headers:
# Delete Content-Length header so finalize() recalcs it.
del response.headers['Content-Length']
return True
else:
cherrypy.serving.request.login = username
cherrypy.session[self.session_key] = username
self.on_login(username)
raise cherrypy.HTTPRedirect(from_page or '/')
def trailing_slash(missing=True, extra=False, status=None, debug=False):
"""Redirect if path_info has (missing|extra) trailing slash."""
request = cherrypy.serving.request
pi = request.path_info
if debug:
cherrypy.log('is_index: %r, missing: %r, extra: %r, path_info: %r' %
(request.is_index, missing, extra, pi),
'TOOLS.TRAILING_SLASH')
if request.is_index is True:
if missing:
if not pi.endswith('/'):
new_url = cherrypy.url(pi + '/', request.query_string)
raise cherrypy.HTTPRedirect(new_url, status=status or 301)
elif request.is_index is False:
if extra:
# If pi == '/', don't redirect to ''!
if pi.endswith('/') and pi != '/':
new_url = cherrypy.url(pi[:-1], request.query_string)
raise cherrypy.HTTPRedirect(new_url, status=status or 301)
def run(self, point):
"""Execute all registered Hooks (callbacks) for the given point."""
exc = None
hooks = self[point]
hooks.sort()
for hook in hooks:
# Some hooks are guaranteed to run even if others at
# the same hookpoint fail. We will still log the failure,
# but proceed on to the next hook. The only way
# to stop all processing from one of these hooks is
# to raise SystemExit and stop the whole server.
if exc is None or hook.failsafe:
try:
hook()
except (KeyboardInterrupt, SystemExit):
raise
except (cherrypy.HTTPError, cherrypy.HTTPRedirect,
cherrypy.InternalRedirect):
exc = sys.exc_info()[1]
except:
exc = sys.exc_info()[1]
cherrypy.log(traceback=True, severity=40)
if exc:
raise exc
def index(self):
scope="alexa_all"
sd = json.dumps({
"alexa:all": {
"productID": ProductID,
"productInstanceAttributes": {
"deviceSerialNumber": "001"
}
}
})
url = "https://www.amazon.com/ap/oa"
callback = cherrypy.url() + "code"
payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
req = requests.Request('GET', url, params=payload)
p = req.prepare()
raise cherrypy.HTTPRedirect(p.url)
def index(self):
scope = "alexa_all"
sd = json.dumps({
"alexa:all": {
"productID": ProductID,
"productInstanceAttributes": {
"deviceSerialNumber": "001"
}
}
})
url = "https://www.amazon.com/ap/oa"
callback = cherrypy.url() + "authresponse"
payload = {"client_id": Client_ID, "scope": "alexa:all", "scope_data": sd, "response_type": "code",
"redirect_uri": callback}
req = requests.Request('GET', url, params=payload)
p = req.prepare()
raise cherrypy.HTTPRedirect(p.url)
def login(self, **params):
print(params)
message = ''
submit = params.get('submit', False)
user = params.get('user', '')
password = params.get('password', '')
returl = params.get('returl')
if not cmd_args.no_anonymous_access:
raise cherrypy.HTTPRedirect('/index')
if submit:
if user and password:
if user == cmd_args.admin_user and password == cmd_args.admin_password:
# default, in-memory sessions
cherrypy.session['logged_in'] = True
cherrypy.session['login_time'] = time.time()
raise cherrypy.HTTPRedirect(returl if returl else '/index')
else:
message = 'Wrong username and/or password!'
else:
message = 'Username and password needed!'
tmpl = env.get_template('login.html')
return tmpl.render(message=message, user=user, returl=returl)
def index(self):
scope="alexa_all"
sd = json.dumps({
"alexa:all": {
"productID": ProductID,
"productInstanceAttributes": {
"deviceSerialNumber": "001"
}
}
})
url = "https://www.amazon.com/ap/oa"
callback = cherrypy.url() + "code"
payload = {"client_id" : Client_ID, "scope" : "alexa:all", "scope_data" : sd, "response_type" : "code", "redirect_uri" : callback }
req = requests.Request('GET', url, params=payload)
p = req.prepare()
raise cherrypy.HTTPRedirect(p.url)
def index(self):
sd = json.dumps({
"alexa:all": {
"productID": PRODUCT_ID,
"productInstanceAttributes": {
"deviceSerialNumber": uuid.getnode()
}
}
})
url = "https://www.amazon.com/ap/oa"
callback = cherrypy.url() + "authresponse"
payload = {
"client_id": CLIENT_ID,
"scope": "alexa:all",
"scope_data": sd,
"response_type": "code",
"redirect_uri": callback
}
req = requests.Request('GET', url, params=payload)
p = req.prepare()
raise cherrypy.HTTPRedirect(p.url)
def do_login(self, username, password, from_page='..', **kwargs):
"""Login. May raise redirect, or return True if request handled."""
response = cherrypy.serving.response
error_msg = self.check_username_and_password(username, password)
if error_msg:
body = self.login_screen(from_page, username, error_msg)
response.body = body
if "Content-Length" in response.headers:
# Delete Content-Length header so finalize() recalcs it.
del response.headers["Content-Length"]
return True
else:
cherrypy.serving.request.login = username
cherrypy.session[self.session_key] = username
self.on_login(username)
raise cherrypy.HTTPRedirect(from_page or "/")
def trailing_slash(missing=True, extra=False, status=None, debug=False):
"""Redirect if path_info has (missing|extra) trailing slash."""
request = cherrypy.serving.request
pi = request.path_info
if debug:
cherrypy.log('is_index: %r, missing: %r, extra: %r, path_info: %r' %
(request.is_index, missing, extra, pi),
'TOOLS.TRAILING_SLASH')
if request.is_index is True:
if missing:
if not pi.endswith('/'):
new_url = cherrypy.url(pi + '/', request.query_string)
raise cherrypy.HTTPRedirect(new_url, status=status or 301)
elif request.is_index is False:
if extra:
# If pi == '/', don't redirect to ''!
if pi.endswith('/') and pi != '/':
new_url = cherrypy.url(pi[:-1], request.query_string)
raise cherrypy.HTTPRedirect(new_url, status=status or 301)
def run(self, point):
"""Execute all registered Hooks (callbacks) for the given point."""
exc = None
hooks = self[point]
hooks.sort()
for hook in hooks:
# Some hooks are guaranteed to run even if others at
# the same hookpoint fail. We will still log the failure,
# but proceed on to the next hook. The only way
# to stop all processing from one of these hooks is
# to raise SystemExit and stop the whole server.
if exc is None or hook.failsafe:
try:
hook()
except (KeyboardInterrupt, SystemExit):
raise
except (cherrypy.HTTPError, cherrypy.HTTPRedirect,
cherrypy.InternalRedirect):
exc = sys.exc_info()[1]
except:
exc = sys.exc_info()[1]
cherrypy.log(traceback=True, severity=40)
if exc:
raise exc
def setup_server():
class Root:
@cherrypy.expose
def resource(self):
return "Oh wah ta goo Siam."
@cherrypy.expose
def fail(self, code):
code = int(code)
if 300 <= code <= 399:
raise cherrypy.HTTPRedirect([], code)
else:
raise cherrypy.HTTPError(code)
@cherrypy.expose
# In Python 3, tools.encode is on by default
@cherrypy.config(**{'tools.encode.on': True})
def unicoded(self):
return ntou('I am a \u1ee4nicode string.', 'escape')
conf = {'/': {'tools.etags.on': True,
'tools.etags.autotags': True,
}}
cherrypy.tree.mount(Root(), config=conf)
def scandeletemulti(self, ids, confirm=None):
dbh = SpiderFootDb(self.config)
names = list()
for id in ids.split(','):
res = dbh.scanInstanceGet(id)
names.append(res[0])
if res is None:
return self.error("Scan ID not found (" + id + ").")
if res[5] in [ "RUNNING", "STARTING", "STARTED" ]:
return self.error("You cannot delete running scans.")
if confirm is not None:
for id in ids.split(','):
dbh.scanInstanceDelete(id)
raise cherrypy.HTTPRedirect("/")
else:
templ = Template(filename='dyn/scandelete.tmpl', lookup=self.lookup)
return templ.render(id=None, name=None, ids=ids.split(','), names=names,
pageid="SCANLIST", docroot=self.docroot)
def manifest(self, *tokens):
"""Manifest requests coming from the BUI need to be redirected
back through the RewriteRules defined in the Apache
configuration in order to be served directly.
pkg(1) will never hit this code, as those requests don't get
handled by this webapp.
"""
self.setup(cherrypy.request)
rel_uri = cherrypy.request.path_info
# we need to recover the escaped portions of the URI
redir = rel_uri.lstrip("/").split("/")
pub_mf = "/".join(redir[0:4])
pkg_name = "/".join(redir[4:])
# encode the URI so our RewriteRules can process them
pkg_name = quote(pkg_name)
pkg_name = pkg_name.replace("/", "%2F")
pkg_name = pkg_name.replace("%40", "@", 1)
# build a URI that we can redirect to
redir = "{0}/{1}".format(pub_mf, pkg_name)
redir = "/{0}".format(redir.lstrip("/"))
raise cherrypy.HTTPRedirect(redir)
def cont(self, **kwargs):
path = kwargs['path']
index = int(kwargs['index'])
index += 1
self.store_result()
try:
return self.run_flow(path, index=index)
except cherrypy.HTTPRedirect:
raise
except Exception as err:
exception_trace("", err, logger)
self.store_result()
return self.inut.err_response("run", err)
def scandelete(self, id, confirm=None):
dbh = SpiderFootDb(self.config)
res = dbh.scanInstanceGet(id)
if res is None:
return self.error("Scan ID not found.")
if confirm is not None:
dbh.scanInstanceDelete(id)
raise cherrypy.HTTPRedirect("/")
else:
templ = Template(filename='dyn/scandelete.tmpl', lookup=self.lookup)
return templ.render(id=id, name=res[0], names=list(), ids=list(),
pageid="SCANLIST", docroot=self.docroot)
def scandelete(self, id, confirm=None):
dbh = SpiderFootDb(self.config)
res = dbh.scanInstanceGet(id)
if res is None:
return self.error("Scan ID not found.")
if confirm is not None:
dbh.scanInstanceDelete(id)
raise cherrypy.HTTPRedirect("/")
else:
templ = Template(filename='dyn/scandelete.tmpl', lookup=self.lookup)
return templ.render(id=id, name=res[0], names=list(), ids=list(),
pageid="SCANLIST", docroot=self.docroot)