Python bottle.response.set_header() Examples

The following are 30 code examples of bottle.response.set_header(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module bottle.response , or try the search function .
Example #1
Source File: web.py    From CuckooSploit with GNU General Public License v3.0 7 votes vote down vote up
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() 
Example #2
Source File: main.py    From bazarr with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #3
Source File: app.py    From ivre with GNU General Public License v3.0 6 votes vote down vote up
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/
# 
Example #4
Source File: database.py    From maloja with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #5
Source File: service.py    From eavatar-me with Apache License 2.0 6 votes vote down vote up
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) 
Example #6
Source File: proxy.py    From github-pages-basic-auth-proxy with MIT License 6 votes vote down vote up
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
# 
Example #7
Source File: app.py    From opentapioca with Apache License 2.0 6 votes vote down vote up
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() 
Example #8
Source File: Monitor.py    From EDDN with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #9
Source File: Monitor.py    From EDDN with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #10
Source File: database.py    From maloja with GNU General Public License v3.0 5 votes vote down vote up
def post_scrobble(artist:Multi,**keys):
	artists = "/".join(artist)
	title = keys.get("title")
	album = keys.get("album")
	duration = keys.get("seconds")
	apikey = keys.get("key")
	client = checkAPIkey(apikey)
	if client == False: # empty string allowed!
		response.status = 403
		return ""

	try:
		time = int(keys.get("time"))
	except:
		time = int(datetime.datetime.now(tz=datetime.timezone.utc).timestamp())

	log("Incoming scrobble (native API): Client " + client + ", ARTISTS: " + str(artists) + ", TRACK: " + title,module="debug")
	(artists,title) = cla.fullclean(artists,title)

	## this is necessary for localhost testing
	#response.set_header("Access-Control-Allow-Origin","*")

	trackdict = createScrobble(artists,title,time,album,duration)

	sync()
	#always sync, one filesystem access every three minutes shouldn't matter



	return {"status":"success","track":trackdict}



# standard-compliant scrobbling methods 
Example #11
Source File: web.py    From CuckooSploit with GNU General Public License v3.0 5 votes vote down vote up
def get_pcap(task_id):
    if not task_id.isdigit():
        return HTTPError(code=404, output="The specified ID is invalid")

    pcap_path = os.path.join(CUCKOO_ROOT, "storage", "analyses", task_id, "dump.pcap")

    if not os.path.exists(pcap_path):
        return HTTPError(code=404, output="PCAP not found")

    response.content_type = "application/vnd.tcpdump.pcap"
    response.set_header("Content-Disposition", "attachment; filename=cuckoo_task_{0}.pcap".format(task_id))

    return open(pcap_path, "rb").read() 
Example #12
Source File: web.py    From CuckooSploit with GNU General Public License v3.0 5 votes vote down vote up
def downlaod_report(task_id):
    if not task_id.isdigit():
        return HTTPError(code=404, output="The specified ID is invalid")

    report_path = os.path.join(CUCKOO_ROOT, "storage", "analyses", task_id, "reports", "report.html")

    if not os.path.exists(report_path):
        return HTTPError(code=404, output="Report not found")

    response.content_type = "text/html"
    response.set_header("Content-Disposition", "attachment; filename=cuckoo_task_{0}.html".format(task_id))

    return open(report_path, "rb").read() 
Example #13
Source File: shockpot.py    From shockpot with GNU Lesser General Public License v2.1 5 votes vote down vote up
def func(**kwargs):
    template_config = dict([(name[9:], value) for name, value in app.config.items() if name.startswith("template.")])
    log_request(get_request_record())
    response.set_header('Server', app.config['headers.server'])
    return bottle.template(page_template, **template_config) 
Example #14
Source File: dockerhub_status_image_api.py    From dockerhub-build-status-image with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_svg():
    organization = request.query.get("organization", DEFAULT_ORGANIZATION)
    repository = request.query["repository"]
    tag = request.query.get("tag", DEFAULT_TAG)
    text = request.query.get("text", DEFAULT_TEXT)
    status = get_status(organization, repository, tag)
    response.content_type = "image/svg+xml"
    if status < 0:
        code = "error"
        color = "#c41"
    else:
        code = "ok"
        color = "#4c1"
    response.set_header('Cache-Control', 'public, max-age=3600')
    return SVG.format(color=color, text=text, status=code) 
Example #15
Source File: app.py    From script.tubecast with MIT License 5 votes vote down vote up
def _state_listener(self):
        response.set_header('Content-Type', 'application/xml')
        response.set_header('Access-Control-Allow-Method', 'GET, POST, DELETE, OPTIONS')
        response.set_header('Access-Control-Expose-Headers', 'Location')
        response.set_header('Cache-control', 'no-cache, must-revalidate, no-store')
        return templates.not_connected if not self.has_client else templates.connected 
Example #16
Source File: database.py    From maloja with GNU General Public License v3.0 5 votes vote down vote up
def server_info():


	response.set_header("Access-Control-Allow-Origin","*")
	response.set_header("Content-Type","application/json")

	return {
		"name":settings.get_settings("NAME"),
		"version":version,
		"versionstring":".".join(str(n) for n in version)
	}

## All database functions are separated - the external wrapper only reads the request keys, converts them into lists and renames them where necessary, and puts the end result in a dict if not already so it can be returned as json 
Example #17
Source File: server.py    From maloja with GNU General Public License v3.0 5 votes vote down vote up
def static(name,ext):
	assert ext in ["ico","jpeg","jpg","png"]
	response = static_file(ext + "/" + name + "." + ext,root=STATICFOLDER)
	response.set_header("Cache-Control", "public, max-age=3600")
	return response 
Example #18
Source File: bson_bottle_plugin.py    From bii-server with MIT License 5 votes vote down vote up
def _set_bson_content_type_headers(self, response):
        response.set_header('Content-Type', 'application/bson') 
Example #19
Source File: snap.py    From pypot with GNU General Public License v3.0 5 votes vote down vote up
def apply(self, fn, context):
        def _enable_cors(*args, **kwargs):
            response.set_header('Access-Control-Allow-Origin', self.origin)
            response.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            response.set_header('Access-Control-Allow-Headers', 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token')

            if request.method != 'OPTIONS':
                # actual request; reply with the actual response
                return fn(*args, **kwargs)

        return _enable_cors 
Example #20
Source File: snap.py    From pypot with GNU General Public License v3.0 5 votes vote down vote up
def apply(self, fn, context):
        def _ext(*args, **kwargs):
            response.set_header('Cache-control', 'no-store')
            return fn(*args, **kwargs)

        return _ext 
Example #21
Source File: server.py    From maloja with GNU General Public License v3.0 5 votes vote down vote up
def static(name,ext):
	assert ext in ["txt","ico","jpeg","jpg","png","less","js"]
	response = static_file(ext + "/" + name + "." + ext,root=STATICFOLDER)
	response.set_header("Cache-Control", "public, max-age=3600")
	return response 
Example #22
Source File: dial.py    From script.tubecast with MIT License 5 votes vote down vote up
def service_desc():
    ''' route for DIAL service discovery '''
    response.set_header('Access-Control-Allow-Method',
                        'GET, POST, DELETE, OPTIONS')
    response.set_header('Access-Control-Expose-Headers', 'Location')
    response.set_header('Application-URL',
                        'http://{}/apps'.format(request.get_header('host')))
    response.set_header('Content-Type', 'application/xml')
    return build_template(__device__).render(
        friendlyName=Kodicast.friendlyName,
        uuid=Kodicast.uuid,
        path="http://%s" % request.get_header('host')
    ) 
Example #23
Source File: maincontroller.py    From conifer with Apache License 2.0 5 votes vote down vote up
def _check_refer_redirect(self):
        referer = request.headers.get('Referer')
        if not referer:
            return

        if self.access.sesh.is_new():
            return

        if request.urlparts.path.startswith('/' + self.access.session_user.name):
            return

        if 'http' in request.urlparts.path or '///' in request.urlparts.path:
            return

        host = request.headers.get('Host')
        if host not in referer:
            return

        inx = referer[1:].find('http')
        if not inx:
            inx = referer[1:].find('///')
            if inx > 0:
                inx + 1

        if inx < 0:
            return

        url = referer[inx + 1:]
        host = referer[:inx + 1]

        orig_url = request.urlparts.path
        if request.urlparts.query:
            orig_url += '?' + request.urlparts.query

        full_url = host + urljoin(url, orig_url)

        response.status = 307
        response.set_header('Location', full_url)
        return True 
Example #24
Source File: webapp.py    From modernpython with MIT License 5 votes vote down vote up
def fetch_static(filename):
    response.set_header('Cache-Control', 'max-age=600')
    return static_file(filename, root='static') 
Example #25
Source File: main.py    From bazarr with GNU General Public License v3.0 5 votes vote down vote up
def image_proxy(url):
    authorize()
    apikey = settings.sonarr.apikey
    url_image = url_sonarr_short() + '/' + url + '?apikey=' + apikey
    try:
        image_buffer = BytesIO(
            requests.get(url_sonarr() + '/api' + url_image.split(url_sonarr())[1], timeout=15, verify=False).content)
    except:
        return None
    else:
        image_buffer.seek(0)
        bytes = image_buffer.read()
        response.set_header('Content-type', 'image/jpeg')
        return bytes 
Example #26
Source File: base.py    From mining with MIT License 5 votes vote down vote up
def base():
    response.set_header('charset', 'utf-8')
    response.content_type = 'application/json' 
Example #27
Source File: server.py    From maloja with GNU General Public License v3.0 5 votes vote down vote up
def static_image(pth):
	if globalconf.USE_THUMBOR:
		return static_file(pthjoin("images",pth),root=DATAFOLDER)

	type = pth.split(".")[-1]
	small_pth = pth + "-small"
	if os.path.exists(datadir("images",small_pth)):
		response = static_file(pthjoin("images",small_pth),root=DATAFOLDER)
	else:
		try:
			from wand.image import Image
			img = Image(filename=datadir("images",pth))
			x,y = img.size[0], img.size[1]
			smaller = min(x,y)
			if smaller > 300:
				ratio = 300/smaller
				img.resize(int(ratio*x),int(ratio*y))
				img.save(filename=datadir("images",small_pth))
				response = static_file(pthjoin("images",small_pth),root=DATAFOLDER)
			else:
				response = static_file(pthjoin("images",pth),root=DATAFOLDER)
		except:
			response = static_file(pthjoin("images",pth),root=DATAFOLDER)

	#response = static_file("images/" + pth,root="")
	response.set_header("Cache-Control", "public, max-age=86400")
	response.set_header("Content-Type", "image/" + type)
	return response 
Example #28
Source File: mishkal-bootle.py    From mishkal with GNU General Public License v3.0 5 votes vote down vote up
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
#------------------ 
Example #29
Source File: app.py    From ivre with GNU General Public License v3.0 5 votes vote down vote up
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
# 
Example #30
Source File: app.py    From ivre with GNU General Public License v3.0 5 votes vote down vote up
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)