我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用web.header()。
def GET(): web.header('Content-Type', 'text/html') # connect to docker try: d_client = docker.from_env() except Exception as e: # pragma: no cover return (False, 'unable to connect to docker because: ' + str(e)) # start container to get network interfaces nics = "" try: nics = d_client.containers.run('cyberreboot/gonet', network_mode='host') except Exception as e: # pragma: no cover return (False, "Failure: " + str(e)) return (True, nics)
def GET(self, *args): dir, name = args[-2:] dir_path = 'templates/%s/' %dir ext = name.split(".")[-1] cType = { "css": "text/css", "png": "images/png", "jpg": "images/jpeg", "gif": "images/gif", "ico": "images/x-icon", "js" : "text/javascrip", } if name in os.listdir(dir_path): web.header("Content-Type", cType[ext]) file_path = '%s/%s' %(dir_path, name) return open(file_path, "rb").read() else: raise web.notfound()
def POST(self): form = myform() if not form.validates(): return render.formtest(form) else: # form.d.boe and form['boe'].value are equivalent ways of # extracting the validated arguments from the form. global question global answer global chat_history global after_question question = form['??'].value after_question = stopwords.eliminate_stop_words(question) answer = robot.chat(after_question) chat_history.append(question) chat_history.append(answer) if answer is "": raise web.seeother('/add') web.header('Content-Type','text/html; charset=utf-8', unique=True) # let the browser use the utf-8 encoding form['??'].set_value('') return render.answer(answer,chat_history, form) # return "Grrreat success! boe: %s, bax: %s, area: %s" % (form.d.boe, form['bax'].value, form['moe'].value)
def GET(self): # one ip can start one game at time ip = web.ctx.ip try: service = Game.manager.get_service_by_key(ip) except KeyError: # register game service Game.manager.register_service(ip) service = Game.manager.get_service_by_key(ip) # get players' names data = web.input() players_names = [data[str(x)] for x in range(len(data))] # init game service service.init_game(players_names) messages = [service.map_describe()] response = { 'current_player': json.loads(json.dumps(service.current_player,cls=PlayerEncoder)), 'messages': messages } web.header('Content-Type', 'application/json') return json.dumps(response)
def GET(self, uid): user = {} callback = web.input().get("jsonp") try: user = models.user(uid).load() # JS is bad at numbers user["id64"] = str(user["id64"]) except: pass web.header("Content-Type", jsonMimeType) jsonobj = json.dumps(user) if not callback: return jsonobj else: return callback + '(' + jsonobj + ');'
def GET(self, group): obj = {} try: memkey = "groupstats-" + str(group) obj = cache.get(memkey) if not obj: parser = group_member_page_parser(group) obj = {} obj["memberCount"] = parser.get_member_count() obj["memberListShort"] = parser.get_member_list_short() obj["logo"] = parser.get_logo() obj["name"] = parser.get_name() obj["abbreviation"] = parser.get_abbreviation() cache.set(memkey, obj, time = config.ini.getint("cache", "group-stats-expiry")) except: pass web.header("Content-Type", jsonMimeType) return json.dumps(obj)
def GET(self, app, sid): try: user, pack = models.load_inventory(sid, scope = app) items = pack["items"].values() sorter = views.sorting(items) items = sorter.sort(web.input().get("sort", sorter.byTime)) cap = config.ini.getint("rss", "inventory-max-items") if cap: items = items[:cap] web.header("Content-Type", "application/rss+xml") return _feed_renderer.inventory_feed(app, user, items) except (steam.user.ProfileError, steam.items.InventoryError, steam.api.HTTPError) as E: raise rssNotFound() except Exception as E: log.main.error(str(E)) raise rssNotFound()
def sendoutput(self, result): content = result.read() logger.debug(content) if result.status == 200: web.ctx.headers = result.getheaders() if len(content.strip()) > 0: d = self.parse_response(content) err = d.find('err') if err is not None: reason = '%s %s' % (err.attrib['code'], err.attrib['msg']) response = {'error': reason} web.ctx.status = str(400)+' '+reason else: response = {'id': d.findtext('statusid')} content = simplejson.dumps(response) filtered = self.filter(content) web.header('content-length', len(filtered)) return filtered else: web.ctx.headers = result.getheaders() web.ctx.status = str(result.status)+' '+result.reason return content
def search_simple_index(query, offset, count, draw): """ This function is responsible for hitting the solr endpoint and returning the results back. """ results = SOLR_SIMPLEINDEX.search(q=query, **{ 'start': int(offset), 'rows': int(count) }) print("Saw {0} result(s) for query {1}.".format(len(results), query)) formatted_hits = [] for hit in results.docs: formatted_hits.append( [hit['_news_title'], hit['_news_publisher'], CATEGORY[hit['_news_category'][0]], hit['_news_url']]) response = {'draw': draw, 'recordsFiltered': results.hits, 'data': formatted_hits} web.header('Content-Type', 'application/json') return json.dumps(response)
def search_entity_aware_index(query, offset, count, draw, qf): """ This function is responsible for hitting the solr endpoint and returning the results back. """ results = SOLR_ENTITYAWAREINDEX.search(q=query, **{ 'start': int(offset), 'rows': int(count), 'qf': qf }) print("Saw {0} result(s) for query {1}.".format(len(results), query)) formatted_hits = [] for hit in results.docs: formatted_hits.append( [hit['_news_title'], hit['_news_publisher'], CATEGORY[hit['_news_category'][0]], hit['_news_url']]) response = {'draw': draw, 'recordsFiltered': results.hits, 'data': formatted_hits} web.header('Content-Type', 'application/json') return json.dumps(response)
def search(query, offset, count, draw, solr_endpoint): """ This function is responsible for hitting the solr endpoint and returning the results back. """ results = solr_endpoint.search(q=query, **{ 'start': int(offset), 'rows': int(count) }) print("Saw {0} result(s) for query {1}.".format(len(results), query)) formatted_hits = [] for hit in results.docs: formatted_hits.append( [hit['_news_title'], hit['_news_publisher'], CATEGORY[hit['_news_category'][0]], hit['_news_url']]) response = {'draw': draw, 'recordsFiltered': results.hits, 'data': formatted_hits} web.header('Content-Type', 'application/json') return json.dumps(response)
def search_simple_index(query, offset, count, draw): """ This function is responsible for hitting the solr endpoint and returning the results back. """ results = SOLR_SIMPLEINDEX.search(q=query, **{ 'start': int(offset), 'rows': int(count), 'cache': 'false' }) print("Saw {0} result(s) for query {1}.".format(len(results), query)) formatted_hits = [] for hit in results.docs: formatted_hits.append( [hit['_news_title'], hit['_news_publisher'], CATEGORY[hit['_news_category'][0]], hit['_news_url']]) response = {'draw': draw, 'recordsFiltered': results.hits, 'data': formatted_hits} web.header('Content-Type', 'application/json') return json.dumps(response)
def POST(self, o_type): web.header('Access-Control-Allow-Origin', self.allow_origin) web.header('Access-Control-Allow-Headers', "Content-type") data = web.data() payload = {} try: payload = ast.literal_eval(data) if type(payload) != dict: payload = ast.literal_eval(json.loads(data)) except: return "malformed json body" client_session_id = uuid.uuid4().hex out = "" if o_type == 'a': out = self.INDEX_HTML%(client_session_id, payload) + \ self.INDEX_HTML_TYPE_A + \ self.INDEX_HTML_END elif o_type == 'b': out = self.INDEX_HTML%(client_session_id, payload) + \ self.INDEX_HTML_TYPE_B + \ self.INDEX_HTML_END return out
def GET(self): web.header('Access-Control-Allow-Origin', self.allow_origin) web.header("Content-Type","text/yaml") try: with open("swagger.yaml", 'r') as f: filedata = f.read() newdata = filedata.replace("mydomain", self.rest_url) with open("swagger.yaml", 'w') as f: f.write(newdata) f = open("swagger.yaml", 'r') except: try: with open("../vcontrol/swagger.yaml", 'r') as f: filedata = f.read() newdata = filedata.replace("mydomain", self.rest_url) with open("../vcontrol/swagger.yaml", 'w') as f: f.write(newdata) f = open("../vcontrol/swagger.yaml", 'r') except: # using python path, don't allow write-back pass return f.read()
def POST(self, machine): web.header('Access-Control-Allow-Origin', self.allow_origin) # TODO how does this work with swagger? x = web.input(myfile={}) filedir = '/tmp/templates/'+machine # change this to the directory you want to store the file in. try: if not os.path.exists(filedir): os.makedirs(filedir) if 'myfile' in x: # to check if the file-object is created filepath=x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones. filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension) fout = open(filedir +'/'+ filename,'w') # creates the file where the uploaded file should be stored fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file. fout.close() # closes the file, upload complete. # copy file to vent instance cmd = "docker-machine scp "+filedir+"/"+filename+" "+machine+":/var/lib/docker/data/templates/" output = subprocess.check_output(cmd, shell=True) # remove file from vcontrol-daemon output = subprocess.check_output("rm -f "+filedir+"/"+filename, shell=True) return "successfully deployed", filename, "to", str(machine) except Exception as e: return "failed to deploy to", str(machine), str(e) return "failed to deploy to", str(machine)
def GET(self, machine, o_type): web.header('Access-Control-Allow-Origin', self.allow_origin) # !! TODO handle data later # !! TODO test with swagger #if 'no_cache' in data: # if not data['no_cache']: # cmd += " --no-cache" client_session_id = uuid.uuid4().hex out = "" if o_type == 'a': out = self.INDEX_HTML%(machine, client_session_id) + \ self.INDEX_HTML_TYPE_A + \ self.INDEX_HTML_END elif o_type == 'b': out = self.INDEX_HTML%(machine, client_session_id) + \ self.INDEX_HTML_TYPE_B + \ self.INDEX_HTML_END return out
def POST(self, machine): web.header('Access-Control-Allow-Origin', self.allow_origin) data = web.data() payload = {} try: payload = ast.literal_eval(data) if type(payload) != dict: payload = ast.literal_eval(json.loads(data)) except: return "malformed json body" try: command = payload['command'] except: out = "you must specify a command" return out try: cmd = "/usr/local/bin/docker-machine ssh "+machine+" \""+command+"\"" out = subprocess.check_output(cmd, shell=True) except: out = "unable to execute generic command" return str(out)
def POST(self): web.header('Access-Control-Allow-Origin', self.allow_origin) web.header('Access-Control-Allow-Headers', "Content-type") # !! TODO does this work with swagger? data = web.data() payload = {} try: payload = ast.literal_eval(data) if type(payload) != dict: payload = ast.literal_eval(json.loads(data)) except Exception as e: return "malformed json body", str(e) try: filedir = '/tmp/templates/'+payload['machine'] if not os.path.exists(filedir): os.makedirs(filedir) cmd = "docker-machine scp "+payload['machine']+":/var/lib/docker/data/templates/"+payload['template']+" "+filedir output = subprocess.check_output(cmd, shell=True) f = open(filedir+"/"+payload['template'], 'rb') return f.read() except Exception as e: return "failed to download", str(e) return "failed to download", str(e)
def POST(self, machine): web.header('Access-Control-Allow-Origin', self.allow_origin) # TODO how does this work with swagger? x = web.input(myfile={}) filedir = '/tmp/files/'+machine # change this to the directory you want to store the file in. try: if not os.path.exists(filedir): os.makedirs(filedir) if 'myfile' in x: # to check if the file-object is created filepath=x.myfile.filename.replace('\\','/') # replaces the windows-style slashes with linux ones. filename=filepath.split('/')[-1] # splits the and chooses the last part (the filename with extension) fout = open(filedir +'/'+ filename,'w') # creates the file where the uploaded file should be stored fout.write(x.myfile.file.read()) # writes the uploaded file to the newly created file. fout.close() # closes the file, upload complete. # copy file to vent instance cmd = "docker-machine scp "+filedir+"/"+filename+" "+machine+":/files/" output = subprocess.check_output(cmd, shell=True) # remove file from vcontrol-daemon output = subprocess.check_output("rm -f "+filedir+"/"+filename, shell=True) return "successfully uploaded", filename, "to", str(machine) except Exception as e: return "failed to upload to", str(machine), str(e) return "failed to upload to", str(machine)
def GET(self, provider): try: web.header('Access-Control-Allow-Origin', self.allow_origin) except Exception as e: print(e.message) open_d = os.environ.get('VCONTROL_OPEN') providers_file_path = os.path.join(os.path.dirname(__file__), 'providers.txt') if web.ctx.env["HTTP_HOST"] == 'localhost:8080' or open_d == "true": f = open(providers_file_path,"r") lines = f.readlines() f.close() flag = 0 with open(providers_file_path, 'w') as f: for line in lines: if not line.startswith(provider+":"): f.write(line) else: flag = 1 if flag: return "removed " + provider else: return provider + " not found, couldn't remove" else: return "must be done from the localhost running vcontrol daemon"
def GET(self): """ GET HTTP Request """ try: web.header('Access-Control-Allow-Origin', self.allow_origin) except Exception as e: print(e.message) try: providers = {} providers_file_path = os.path.join(os.path.dirname(__file__), 'providers.txt') if os.path.isfile(providers_file_path): with open(providers_file_path, 'r') as f: for line in f: providers[line.split(":")[0]] = line.split(":")[1].strip() return providers except: return "unable to get providers"
def GET(): web.header('Content-Type', 'text/html') # connect to docker try: containers = docker.from_env() except Exception as e: # pragma: no cover return (False, 'unable to connect to docker because: ' + str(e)) # search for all docker containers and grab ncapture containers container_list = [] try: for c in containers.containers.list(all=True): # TODO: maybe find a way to not have to hard code image name if c.attrs["Config"]["Image"] == \ "cyberreboot/vent-ncapture:master": # the core container is not what we want if "core" not in c.attrs["Config"]["Labels"]\ ["vent.groups"]: lst = {} lst['id'] = c.attrs["Id"][:12] lst['status'] = c.attrs["State"]["Status"] lst['args'] = c.attrs['Args'] container_list.append(lst) except Exception as e: # pragma: no cover return (False, "Failure: " + str(e)) return (True, container_list)
def POST(): """ Send a POST request with a docker container ID and it will be stopped. Example input: {'id': "12345"}, {'id': ["123", "456"] """ web.header('Content-Type', 'application/json') # verify user input data = web.data() payload = {} try: payload = ast.literal_eval(data) except Exception as e: # pragma: no cover return (False, 'malformed payload : ' + str(e)) # verify payload has a container ID if 'id' not in payload: return (False, 'payload missing container id') # connect to docker and stop the given container c = None try: c = docker.from_env() except Exception as e: # pragma: no cover return (False, 'unable to connect to docker because: ' + str(e)) # stop containers chosen from CLI try: for container_id in payload['id']: c.containers.get(container_id).stop() except Exception as e: # pragma: no cover return (False, 'unable to stop list of containers because: ' + str(e)) return (True, 'container successfully stopped: ' + str(payload['id']))
def POST(): """ Send a POST request with a docker container ID and it will be deleted. Example input: {'id': "12345"}, {'id': ["123", "456"]} """ web.header('Content-Type', 'application/json') # verify user input data = web.data() payload = {} try: payload = ast.literal_eval(data) except Exception as e: # pragma: no cover return (False, 'malformed payload : ' + str(e)) # verify payload has a container ID if 'id' not in payload: return (False, 'payload missing container id') # connect to docker and stop the given container c = None try: c = docker.from_env() except Exception as e: # pragma: no cover return (False, 'unable to connect to docker because: ' + str(e)) # delete containers chosen from CLI try: for container_id in payload['id']: c.containers.get(container_id).remove() except Exception as e: # pragma: no cover return (False, 'unable to delete containers because: ' + str(e)) return (True, 'container successfully deleted: ' + str(payload['id']))
def POST(): """ Send a POST request with a docker container ID and it will be started. Example input: {'id': "12345"}, {'id': ["123", "456"]} """ web.header('Content-Type', 'application/json') # verify user input data = web.data() payload = {} try: payload = ast.literal_eval(data) except Exception as e: # pragma: no cover return (False, 'malformed payload : ' + str(e)) # verify payload has a container ID if 'id' not in payload: return (False, 'payload missing container id') # connect to docker and stop the given container c = None try: c = docker.from_env() except Exception as e: # pragma: no cover return (False, 'unable to connect to docker because: ' + str(e)) # start containers chosen from CLI try: for container_id in payload['id']: c.containers.get(container_id).start() except Exception as e: # pragma: no cover return (False, 'unable to start list of containers because: ' + str(e)) return (True, 'container successfully started: ' + str(payload['id']))
def set_json_response(): """ ????content-type?json :return: """ web.header('content-type', 'application/json;charset=utf-8', unique=True)
def getHeader(self): header = {} header['logoText'] = self.title modules = [] return header
def GET( self, x ): print 'in structure: '+x web.header('Content-Type', 'application/json') layout = portal_pages[x] return '{"layout":'+ layout.to_JSON() +'}'
def _make_response(self, content, headers, status): web.ctx.status = status for k, v in headers: web.header(k, v) return content
def GET(self): web.header('Content-Type', "application/json") return json.dumps({'status': 'ok'})
def POST(self): data = web.input() if not ("ident" in data and "csr" in data): raise web.BadRequest() crt = sign_csr(data.csr, data.ident) web.header('Content-Type', "application/json") return json.dumps({'certificate': crt})
def GET(self): web.header('Content-Type','application/json') topic = web.input(value=' ') try: output = run_model.model(requirement = [topic.value]) except: output = 'Invalid query' pass return output
def POST(self): global modelCache params = json.loads(web.data()) requestInput = web.input() id = requestInput["id"] # We will always return the active cells because they are cheap. returnSnapshots = [TM_SNAPS.ACT_CELLS] from pprint import pprint; pprint(params) tm = TM(**params) tmFacade = TmFacade(tm, ioClient, modelId=id) modelId = tmFacade.getId() modelCache[modelId]["tm"] = tmFacade modelCache[modelId]["classifier"] = SDRClassifierFactory.create(implementation="py") modelCache[modelId]["recordsSeen"] = 0 print "Created TM {}".format(modelId) payload = { "meta": { "id": modelId, "saving": returnSnapshots } } tmState = tmFacade.getState(*returnSnapshots) for key in tmState: payload[key] = tmState[key] web.header("Content-Type", "application/json") return json.dumps(payload)
def getFile(self,fileName): """Return file itself """ # TODO: set propper Content/type try: if fileName.find(".shp") or fileName.find(".tab"): (path,fn) = os.path.split(fileName) old_path = os.path.abspath(os.path.curdir) os.chdir(path) fn_noext = os.path.splitext(fn)[0] from zipfile import ZipFile from io import BytesIO filelike = BytesIO() zipout = ZipFile(filelike,"w") for f in os.listdir(os.path.curdir): if f.find(fn_noext) > -1: zipout.write(f) zipout.close() web.header('Content-Disposition','attachment; filename="%s.zip"'% fn_noext) os.chdir(old_path) fn_noext = os.path.splitext(fn)[0] return (200, filelike.getvalue()) else: return (200, open(fileName).read()) except Exception as e: message = "LayEd: getFile(): Unable to read from the file named '" + fileName + "'. Exception received: " + str(e) raise LaymanError(500, message)
def POST(self): form = formA() self.new_question = question if not form.validates(): return render.add(question, form) else: new_answer = form['Answer'].value web.header('Content-Type','text/html; charset=utf-8', unique=True) print self.new_question global after_question robot.addAnswer(after_question, new_answer) raise web.seeother('/')
def GET(self, url, rse, operation): """ GET redirect URL. HTTP Success: 200 OK HTTP Error: 401 Unauthorized 500 InternalError :returns: A URL refering to the file. """ # header('Access-Control-Allow-Origin', ctx.env.get('HTTP_ORIGIN')) # header('Access-Control-Allow-Headers', ctx.env.get('HTTP_ACCESS_CONTROL_REQUEST_HEADERS')) # header('Access-Control-Allow-Methods', '*') # header('Access-Control-Allow-Credentials', 'true') try: pos = url.index('/') url = ''.join([url[:pos], '/', url[pos:]]) if operation == 'connect': objectstore.connect(rse, url) else: result = objectstore.get_signed_urls([url], rse=rse, operation=operation) if isinstance(result[url], Exception): raise result[url] return result[url] except RucioException, e: raise generate_http_error(500, e.__class__.__name__, e.args[0]) except Exception, e: print traceback.format_exc() raise InternalError(e) raise OK()
def POST(self, rse, operation): """ Get URLs for files at a given RSE. HTTP Success: 200 OK HTTP Error: 401 Unauthorized 500 Internal Error """ header('Content-Type', 'application/json') json_data = data() try: parameters = parse_response(json_data) except ValueError: raise generate_http_error(400, 'ValueError', 'Cannot decode json parameter list') try: result = objectstore.get_signed_urls(parameters, rse=rse, operation=operation) for url in result: if isinstance(result[url], Exception): raise result[url] return render_json(**result) except RucioException, e: raise generate_http_error(500, e.__class__.__name__, e.args[0][0]) except Exception, e: print traceback.format_exc() raise InternalError(e)
def POST(self, rse): """ Get files metadata at a given RSE. HTTP Success: 200 OK HTTP Error: 401 Unauthorized 500 Internal Error """ header('Content-Type', 'application/json') json_data = data() try: parameters = parse_response(json_data) except ValueError: raise generate_http_error(400, 'ValueError', 'Cannot decode json parameter list') try: result = objectstore.get_metadata(parameters, rse=rse) for url in result: if isinstance(result[url], Exception): raise result[url] return render_json(**result) except RucioException, e: raise generate_http_error(500, e.__class__.__name__, e.args[0][0]) except Exception, e: print traceback.format_exc() raise InternalError(e)
def POST(self, rse): """ Get files metadata at a given RSE. HTTP Success: 200 OK HTTP Error: 401 Unauthorized 500 Internal Error """ header('Content-Type', 'application/json') json_data = data() try: parameters = parse_response(json_data) except ValueError: raise generate_http_error(400, 'ValueError', 'Cannot decode json parameter list') try: url = parameters['url'] new_url = parameters['new_url'] objectstore.rename(url, new_url, rse=rse) except RucioException, e: raise generate_http_error(500, e.__class__.__name__, e.args[0][0]) except Exception, e: print traceback.format_exc() raise InternalError(e) raise OK() # ---------------------- # Web service startup # ----------------------
def GET(self): web.header("Content-Type","text/html; charset=utf-8") render = web.template.render('static/') return render.index()
def GET(self): web.header('Content-Type', 'text/html') print self.page % self.form()
def POST(self): i = web.input() if '_' in i: del i['_'] #for k, v in i.iteritems(): setattr(self, k, v) self._inFunc = True self.work(**i) self._inFunc = False web.header('Content-Type', 'text/javascript') print 'receive('+simplejson.dumps(self.updated)+');'
def jsonApi( f ): ''' Decorator to basic exception handling on function. ''' @wraps( f ) def wrapped( *args, **kwargs ): web.header( 'Content-Type', 'application/json' ) r = f( *args, **kwargs ) try: return dumpJson( r ) except: return dumpJson( { 'error' : str( r ) } ) return wrapped
def msgpackApi( f ): ''' Decorator to basic exception handling on function. ''' @wraps( f ) def wrapped( *args, **kwargs ): web.header( 'Content-Type', 'application/msgpack' ) r = f( *args, **kwargs ) try: return msgpack.packb( r ) except: return msgpack.packb( { 'error' : str( r ) } ) return wrapped
def jsonData( data ): web.header( 'Content-Type', 'application/json' ) return dumpJson( data )
def msgpackData( data ): web.header( 'Content-Type', 'application/msgpack' ) return msgpack.packb( data )
def GET( self ): web.header( 'Content-Type', 'application/json' ) params = web.input( sid = None ) sensorInfo = getSiteFor( params.sid ) if sensorInfo is None: raise web.HTTPError( '404 Not Found: sensor not found' ) sensorInfo, site = sensorInfo after = int( time.time() - 5 ) eventCache = RingCache( maxEntries = 100, isAutoAdd = True ) while True: now = int( time.time() ) newest = 0 res = querySite( 'models', 'get_timeline', { 'id' : sensorInfo[ 'id' ], 'is_include_content' : True, 'after' : after }, defaultSiteProc, site, {} ) for r in res[ 'events' ]: if r[ 2 ] not in eventCache: yield dumpJson( sanitizeJson( r[ 3 ] ) ) eventTime = int( r[ 0 ] / 1000 ) if eventTime < now + 30 and eventTime > newest: newest = eventTime if 0 != newest: after = newest - 1 gevent.sleep( 2 )
def setDownloadFileName( name ): web.header( 'Content-Disposition', 'attachment;filename="%s"' % name )
def fileDownload( f ): ''' Decorator to basic exception handling on function. ''' @wraps( f ) def wrapped( *args, **kwargs ): web.header( 'Content-Type', 'application/octet-stream' ) return f( *args, **kwargs ) return wrapped #============================================================================== # PAGES #==============================================================================