本文整理汇总了Python中bottle.response.set_header方法的典型用法代码示例。如果您正苦于以下问题:Python response.set_header方法的具体用法?Python response.set_header怎么用?Python response.set_header使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bottle.response
的用法示例。
在下文中一共展示了response.set_header方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_config
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import set_header [as 别名]
def get_config():
"""Returns JavaScript code to set client-side configuration values
:status 200: no error
:status 400: invalid referer
:>json object config: the configuration values
"""
response.set_header('Content-Type', 'application/javascript')
for key, value in [
("notesbase", config.WEB_NOTES_BASE),
("dflt_limit", config.WEB_LIMIT),
("warn_dots_count", config.WEB_WARN_DOTS_COUNT),
("publicsrv", config.WEB_PUBLIC_SRV),
("uploadok", config.WEB_UPLOAD_OK),
("flow_time_precision", config.FLOW_TIME_PRECISION),
("version", VERSION),
]:
yield "config.%s = %s;\n" % (key, json.dumps(value))
#
# /nmap/
#
示例2: proxy_trough_helper
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import set_header [as 别名]
def proxy_trough_helper(url):
print ('PROXY-GET: {0}'.format(url))
proxy_response = requests.get(url)
if proxy_response.status_code == 200:
if proxy_response.headers['Last-Modified']:
response.set_header('Last-Modified', proxy_response.headers['Last-Modified'])
if proxy_response.headers['Content-Type']:
response.set_header('Content-Type', proxy_response.headers['Content-Type'])
if proxy_response.headers['Expires']:
response.set_header('Expires', proxy_response.headers['Expires'])
return proxy_response
else:
return HTTPResponse(status=proxy_response.status_code,
body=template(error_tpl,
headline='Error {0}'.format(proxy_response.status_code),
error='error during proxy call'))
#
# BOTTLE APP
#
示例3: getTotalSoftwares
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import set_header [as 别名]
def getTotalSoftwares():
response.set_header("Access-Control-Allow-Origin", "*")
db = mariadb.connect(user=Settings.MONITOR_DB['user'], password=Settings.MONITOR_DB['password'], database=Settings.MONITOR_DB['database'])
softwares = collections.OrderedDict()
maxDays = request.GET.get('maxDays', '31').strip()
maxDays = int(maxDays) - 1
query = """SELECT name, SUM(hits) AS total, MAX(dateStats) AS maxDate
FROM softwares
GROUP BY name
HAVING maxDate >= DATE_SUB(NOW(), INTERVAL %s DAY)
ORDER BY total DESC"""
results = db.cursor()
results.execute(query, (maxDays, ))
for row in results:
softwares[row[0].encode('utf8')] = str(row[1])
db.close()
return simplejson.dumps(softwares)
示例4: getTotalSchemas
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import set_header [as 别名]
def getTotalSchemas():
response.set_header("Access-Control-Allow-Origin", "*")
db = mariadb.connect(user=Settings.MONITOR_DB['user'], password=Settings.MONITOR_DB['password'], database=Settings.MONITOR_DB['database'])
schemas = collections.OrderedDict()
query = """SELECT `name`, SUM(`hits`) AS `total`
FROM `schemas`
GROUP BY `name`
ORDER BY `total` DESC"""
results = db.cursor()
results.execute(query)
for row in results:
schemas[str(row[0])] = row[1]
db.close()
return simplejson.dumps(schemas)
示例5: test_server
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import set_header [as 别名]
def test_server(key=None):
response.set_header("Access-Control-Allow-Origin","*")
if key is not None and not (checkAPIkey(key)):
response.status = 403
return "Wrong API key"
elif db_rulestate:
response.status = 204
return
else:
response.status = 205
return
# 204 Database server is up and operational
# 205 Database server is up, but DB is not fully built or is inconsistent
# 403 Database server is up, but provided API key is not valid
示例6: get_files
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import set_header [as 别名]
def get_files(task_id):
if not task_id.isdigit():
return HTTPError(code=404, output="The specified ID is invalid")
files_path = os.path.join(CUCKOO_ROOT, "storage", "analyses", task_id, "files")
zip_file = os.path.join(CUCKOO_ROOT, "storage", "analyses", task_id, "files.zip")
with zipfile.ZipFile(zip_file, "w", compression=zipfile.ZIP_DEFLATED) as archive:
root_len = len(os.path.abspath(files_path))
for root, dirs, files in os.walk(files_path):
archive_root = os.path.abspath(root)[root_len:]
for f in files:
fullpath = os.path.join(root, f)
archive_name = os.path.join(archive_root, f)
archive.write(fullpath, archive_name, zipfile.ZIP_DEFLATED)
if not os.path.exists(files_path):
return HTTPError(code=404, output="Files not found")
response.content_type = "application/zip"
response.set_header("Content-Disposition", "attachment; filename=cuckoo_task_%s(not_encrypted).zip" % (task_id))
return open(zip_file, "rb").read()
示例7: nif_api
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import set_header [as 别名]
def nif_api(*args, **kwargs):
content_format = request.headers.get('Content') or 'application/x-turtle'
content_type_to_format = {
'application/x-turtle': 'turtle',
'text/turtle': 'turtle',
}
nif_body = request.body.read()
nif_doc = NIFCollection.loads(nif_body)
for context in nif_doc.contexts:
logger.debug(context.mention)
mentions = classifier.create_mentions(context.mention)
classifier.classify_mentions(mentions)
for mention in mentions:
mention.add_phrase_to_nif_context(context)
response.set_header('content-type', content_format)
return nif_doc.dumps()
示例8: set_cors_headers
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import set_header [as 别名]
def set_cors_headers():
"""
Set CORS headers
"""
if request.method == 'GET':
response.set_header(b'Access-Control-Allow-Origin', b'*')
return
if request.method == 'OPTIONS':
response.set_header(b'Access-Control-Allow-Methods',
b'GET, PUT, HEAD, DELETE, OPTIONS')
response.set_header(b'Access-Control-Allow-Headers',
b'authorization')
client_origin = request.get_header(b'Origin', b'*')
# for PUT and DELETE operations, echo back the given Origin header.
response.set_header(b'Access-Control-Allow-Origin', client_origin)
示例9: image_proxy_movies
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import set_header [as 别名]
def image_proxy_movies(url):
authorize()
apikey = settings.radarr.apikey
try:
url_image = (url_radarr_short() + '/' + url + '?apikey=' + apikey).replace('/fanart.jpg', '/banner.jpg')
image_buffer = BytesIO(
requests.get(url_radarr() + '/api' + url_image.split(url_radarr())[1], timeout=15, verify=False).content)
except:
url_image = url_radarr_short() + '/' + url + '?apikey=' + apikey
image_buffer = BytesIO(
requests.get(url_radarr() + '/api' + url_image.split(url_radarr())[1], timeout=15, verify=False).content)
else:
image_buffer.seek(0)
bytes = image_buffer.read()
response.set_header('Content-type', 'image/jpeg')
return bytes
示例10: topUp
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import set_header [as 别名]
def topUp(method="GET"):
return_url = request.query.return_url or None
if request.query.cancel == "cancel":
if return_url is None:
return "Cancelled. Please close this tab/window and return to PaperCut"
else:
response.set_header("Refresh", "5; url={}".format(return_url))
return "Cancelled. You will be returned to PaperCut in 5s"
user = request.query.user
amount = float(request.query.amount)
if not amount > 0.0: # Example of data validation -- not used because our form already does this one
return template('promptForDeposit',user=user, return_url=return_url, error_text="Invalid amount \"{}\" entered".format(amount))
proxy.api.adjustUserAccountBalance(
auth, user, amount, "Money added by the Simple Top Up Page")
if len(return_url) == 0:
return "Updated balance is now {}<br><br>Please close this tab/window and return to PaperCut".format(
proxy.api.getUserAccountBalance(auth,user))
# Add refresh with 5s timeout back to PaperCut MF/NG
response.set_header("Refresh", "5; url={}".format(return_url))
return "Updated balance is now {}<br><br>You will be returned to PaperCcut in 5s".format(
proxy.api.getUserAccountBalance(auth,user))
示例11: ajaxget
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import set_header [as 别名]
def ajaxget():
"""
this is an example of using ajax/json
to test it visit http://localhost:8080/ajaxGet"
"""
text = request.query.text or u"تجربة"
action = request.query.action or 'DoNothing'
order = request.query.order or '0'
options = {};
options['lastmark'] = request.query.lastmark or '1'
if sys.version_info[0] < 3:
text = text.decode('utf-8')
options['lastmark'] = options['lastmark'].decode('utf8')
#self.writelog(text,action);
#Handle contribute cases
if action=="Contribute":
return {'result':u"شكرا جزيلا على مساهمتك."}
resulttext = core.adaat.DoAction(text ,action, options)
#-----------
# prepare json
#-------------
response.set_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
response.set_header("Access-Control-Allow-Credentials", "true")
response.set_header( "Access-Control-Allow-Origin", "*")
response.set_header("Access-Control-Allow-Headers", "Content-Type, *")
response.set_header( "Content-Type", "application/json")
return json.dumps({'result':resulttext, 'order':order})
#------------------
# Static pages files
#------------------
示例12: check_referer
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import set_header [as 别名]
def check_referer(func):
""""Wrapper for route functions to implement a basic anti-CSRF check
based on the Referer: header.
It will abort (status code 400) if the referer is invalid.
"""
if config.WEB_ALLOWED_REFERERS is False:
return func
def _die(referer):
utils.LOGGER.critical("Invalid Referer header [%r]", referer)
response.set_header('Content-Type', 'application/javascript')
response.status = '400 Bad Request'
return webutils.js_alert(
"referer", "error",
"Invalid Referer header. Check your configuration."
)
@wraps(func)
def _newfunc(*args, **kargs):
referer = request.headers.get('Referer')
if not referer:
return _die(referer)
if config.WEB_ALLOWED_REFERERS is None:
base_url = '/'.join(request.url.split('/', 3)[:3]) + '/'
if referer.startswith(base_url):
return func(*args, **kargs)
elif referer in config.WEB_ALLOWED_REFERERS:
return func(*args, **kargs)
return _die(referer)
return _newfunc
#
# Configuration
#
示例13: get_nmap_base
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import set_header [as 别名]
def get_nmap_base(dbase):
query = webutils.query_from_params(request.params)
flt, sortby, unused, skip, limit = webutils.flt_from_query(dbase, query)
if limit is None:
limit = config.WEB_LIMIT
if config.WEB_MAXRESULTS is not None:
limit = min(limit, config.WEB_MAXRESULTS)
callback = request.params.get("callback")
# type of result
ipsasnumbers = request.params.get("ipsasnumbers")
if callback:
fmt = 'json'
else:
fmt = request.params.get("format") or 'json'
if fmt not in set(['txt', 'json', 'ndjson']):
fmt = 'txt'
datesasstrings = request.params.get("datesasstrings")
if fmt == 'txt':
response.set_header('Content-Type', 'text/plain')
elif fmt == 'ndjson':
response.set_header('Content-Type', 'application/x-ndjson')
else:
response.set_header('Content-Type', 'application/javascript')
if callback is None:
response.set_header('Content-Disposition',
'attachment; filename="IVRE-results.%s"' % fmt)
return FilterParams(flt, sortby, unused, skip, limit, callback,
ipsasnumbers, datesasstrings, fmt)
示例14: post_nmap
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import set_header [as 别名]
def post_nmap(subdb):
"""Add records to Nmap & View databases
:param str subdb: database to query (must be "scans" or "view")
:form categories: a coma-separated list of categories
:form source: the source of the scan results (mandatory)
:form result: scan results (as XML or JSON files)
:status 200: no error
:status 400: invalid referer, source or username missing
:>json int count: number of inserted results
"""
referer, source, categories, files = parse_form()
count = import_files(subdb, source, categories, files)
if request.params.get("output") == "html":
response.set_header('Refresh', '5;url=%s' % referer)
return """<html>
<head>
<title>IVRE Web UI</title>
</head>
<body style="padding-top: 2%%; padding-left: 2%%">
<h1>%d result%s uploaded</h1>
</body>
</html>""" % (count, 's' if count > 1 else '')
return {"count": count}
#
# /flow/
#
示例15: return_json
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import set_header [as 别名]
def return_json(object, response):
response.set_header('Content-Type', 'application/json')
return json.dumps(object)