当前位置: 首页>>代码示例>>Python>>正文


Python web.header函数代码示例

本文整理汇总了Python中web.header函数的典型用法代码示例。如果您正苦于以下问题:Python header函数的具体用法?Python header怎么用?Python header使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了header函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: GET

    def GET(self, start):
        if not start:
            start = 0
        else:
            start = int(start)
        
        #TODO: add Image PDFs to this query
        solrUrl = 'http://se.us.archive.org:8983/solr/select?q=mediatype%3Atexts+AND+format%3A(LuraTech+PDF)&fl=identifier,title,creator,oai_updatedate,date,contributor,publisher,subject,language&sort=updatedate+desc&rows='+str(numRows)+'&start='+str(start*numRows)+'&wt=json'
        f = urllib.urlopen(solrUrl)        
        contents = f.read()
        f.close()
        obj = json.loads(contents)
        
        numFound = int(obj['response']['numFound'])

        titleFragment = 'books sorted by update date'        
        title = 'Internet Archive - %d to %d of %d %s.' % (start*numRows, min((start+1)*numRows, numFound), numFound, titleFragment)
        opds = createOpdsRoot(title, 'opds:new:%d' % (start), 
                        '/new/%d'%(start), getDateString())

        urlFragment = '/new/'
        createNavLinks(opds, titleFragment, urlFragment, start, numFound)
        
        for item in obj['response']['docs']:
            description = None
            
            if 'description' in item:
                description = item['description']

            createOpdsEntryBook(opds, item)

        #self.makePrevNextLinksDebug(opds, letter, start, numFound)
        
        web.header('Content-Type', pubInfo['mimetype'])
        return prettyPrintET(opds)
开发者ID:mangtronix,项目名称:bookserver,代码行数:35,代码来源:opds.py

示例2: GET

    def GET(self, account, name):
        """
        Return all rules of a given subscription id.

        HTTP Success:
            200 OK

        HTTP Error:
            401 Unauthorized
            404 Not Found

        :param scope: The scope name.
        """
        header('Content-Type', 'application/x-json-stream')
        state = None
        if ctx.query:
            params = parse_qs(ctx.query[1:])
            if 'state' in params:
                state = params['state'][0]
        try:
            subscriptions = [subscription['id'] for subscription in list_subscriptions(name=name, account=account)]
            if len(subscriptions) > 0:
                if state == 'OK':
                    state = RuleState.OK
                if state == 'Replicating':
                    state = RuleState.REPLICATING
                if state == 'Stuck':
                    state = RuleState.STUCK
                for rule in list_replication_rules({'subscription_id': subscriptions[0], 'state': state}):
                    yield dumps(rule, cls=APIEncoder) + '\n'
        except RuleNotFound, e:
            raise generate_http_error(404, 'RuleNotFound', e.args[0][0])
开发者ID:pombredanne,项目名称:rucio,代码行数:32,代码来源:subscription.py

示例3: GET

    def GET(self):
        i = web.input()
        buildString = ''
        selectedBuilds = db.select('builds', where='task_id="'
                                   + str(i.task_id) + '"')

        if selectedBuilds:
            for x in selectedBuilds:
                buildString = json.JSONEncoder().encode({
                    'task_id': i.task_id,
                    'repos': x.repos,
                    'branch': x.branch,
                    'version': x.version,
                    'author': x.author,
                    'latin': x.latin,
                    'demo_data': x.demo_data,
                    'styleguide_repo': x.styleguide_repo,
                    'styleguide_branch': x.styleguide_branch,
                    'sidecar_repo': x.sidecar_repo,
                    'sidecar_branch': x.sidecar_branch,
                    'package_list': x.package_list,
                    'upgrade_package': x.upgrade_package,
                    'expired_tag': x.expired_tag
                    })
            web.header('Content-type', 'application/json')
            return buildString
开发者ID:bbradley-sugarcrm,项目名称:BranchBuilder,代码行数:26,代码来源:Builder.py

示例4: POST

 def POST(self):
     input = web.input()
     web.header('Content-Type', 'application/json')
     return json.dumps({ # Do trivial operations:
         'txt' : input.mod.lower(),
         'dat' : "%.3f" % float(input.num)
         })
开发者ID:BruceEckel,项目名称:Power-of-Hybridization-Source-Code,代码行数:7,代码来源:server.py

示例5: auth_user

def auth_user(global_config, desired_path='/home'):
    auth = web.ctx.env.get('HTTP_AUTHORIZATION')
    authreq = False
    
    if auth is None:
        authreq = True
    else:
        auth = re.sub('^Basic ','',auth)
        username,password = base64.decodestring(auth).split(':')
        
        if logged_out_users.has_key(username):
            del logged_out_users[username]
        else:
            session = DbSession.open_db_session(global_config['users_db_name'] + global_config['this_season'])
            user = UsersDataModel.getUser(session, username)
            session.remove()
            if user:
                if user.state == 'Disabled':
                    raise web.seeother('/accountdisabled')
                #if (username,password) in allowed:
                if user.check_password(password) == True:
                    raise web.seeother(desired_path)
        authreq = True
    if authreq:
        web.header('WWW-Authenticate','Basic realm="FRC1073 ScoutingAppCentral"')
        web.ctx.status = '401 Unauthorized'
        return
开发者ID:FRCTeam1073-TheForceTeam,项目名称:ScoutingAppCentral,代码行数:27,代码来源:WebLogin.py

示例6: GET

    def GET(self):
        folder_pages_full_path = config_agent.get_full_path("paths", "pages_path")
        path = os.path.join(folder_pages_full_path, "robots.txt")
        content = commons.shutils.cat(path)

        web.header("Content-Type", "text/plain")
        return content
开发者ID:zivhoo,项目名称:zbox_wiki,代码行数:7,代码来源:main.py

示例7: GET

	def GET(self):
		json_par = 0
		points = 0
		i = web.input(json_par=None, points=None)

		#print(i.lon1)
		#print(i.lat2)
		
		"""
			Here comes a map page request (without a route)
		"""

		if (i.json_par is None and i.points is None):
			web.header('Content-Type', 'text/html')
			return render.map()
		
		if not (i.points is None):			
			data = build_list2(libc.get_access_size())
			return json.dumps({ "array": data })	
		"""
			Processing the route right here
		"""
		#myPoints = {'arr': }
        #web.header('Content-Type', 'application/json')
        #data = [30, 60, 31, 61, 32, 59]
		ll = json.loads(i.json_par)
		#print ll["lon1"]
		#print ll["lat1"]
		#print ll["lon2"]
		#print ll["lat2"]
		libc.mysearch(ll["lon1"], ll["lat1"], ll["lon2"], ll["lat2"])		
		data = build_list(libc.get_size())
		libc.free_mem()
		return json.dumps({ "array": data })
开发者ID:griver,项目名称:Shortest-paths-on-road-graphs,代码行数:34,代码来源:server.py

示例8: GET

	def GET(self):
		#theme可选项:light|dark
		theme=web.input().get("theme","light")
		#output可选项:html|json
		output=web.input().get("output","html")
		#类型的可选项:model|automate
		t=web.input().get("type","model")
		import os
		l=os.listdir(cwd('static','files'))
		ext=".json"
		if t=="automate":
			ext=".txt"
		l= filter(lambda x:x.endswith(ext),l)
		import base64,urllib2
		#base64解码
		l= map(lambda x: to_unicode(base64.b64decode(x[:-len(ext)])),l)
		#为了能在html和json中显示
		l= map(lambda x: (x,urllib2.quote(x.encode("utf-8"))),l)
		if output=='html':
			static=cwd("static")
			render=web.template.render(cwd('templates'),globals=locals())
			return render.list()
		elif output=='json':
			import json
			web.header('Content-Type', 'application/json')
			return json.dumps(l)
开发者ID:vindurriel,项目名称:nest,代码行数:26,代码来源:model.py

示例9: GET

 def GET(self):
     web.header('Content-Type', mime['html'])
     return ('<ul>'
             '<li><a href="/lastfm.xml">last.fm example</a></li>'
             '<li><a href="/group.xml">tributaries-project "group" xml</a></li>'
             '<li><a href="/group.json">tributaries-project "group" json</a></li>'
             '</ul>')
开发者ID:plredmond,项目名称:rest_py,代码行数:7,代码来源:host.py

示例10: GET

 def GET(self):
     #json objc w/ automatic and threshold
     web.header('Access-Control-Allow-Origin', '*')
     web.header('Access-Control-Allow-Credentials', 'true')
     global automatic
     global threshold
     return json_p({'automatic':automatic, 'threshold':threshold, 'success':True})
开发者ID:MrTomWhite,项目名称:HomeBase,代码行数:7,代码来源:lamp-webpy.py

示例11: POST

    def POST(self):
        # disable nginx buffering
        web.header('X-Accel-Buffering', 'no')

        i = web.input(fast=False)
        #get app config if not exist will create it
        servers = get_servers(i.app_name)
        if not servers:
            servers = ['deploy']
            save_app_option(i.app_name, 'deploy_servers', 'deploy')

        yield "%d:%s" % (logging.INFO, render_ok("Application allowed to deploy those servers"))
        yield "%d:%s" % (logging.INFO, render_ok(','.join(servers)))
        servers = escape_servers(servers)

        result = {}
        data = {'app_name': i.app_name, 'app_url': i.app_url}
        for server in servers:
            url = SUFFIX % server
            try:
                opener = FancyURLopener()
                f = opener.open(url, urlencode(data))
                line = ''  # to avoid NameError for line if f has no output at all.
                for line in iter(f.readline, ''):
                    logger.info(line)
                    yield line
                if not any(word in line for word in ['succeeded', 'failed']):
                    result[server] = 'Failed'
                else:
                    result[server] = 'Succeeded'
            except Exception, e:
                yield "%d:%s" % (logging.ERROR, render_err(str(e)))
                result[server] = 'Failed'
开发者ID:xiaomen,项目名称:deploy,代码行数:33,代码来源:deploy.py

示例12: GET

    def GET(self, scope, name):
        """ get locks for a given scope, name.

        HTTP Success:
            200 OK

        HTTP Error:
            404 Not Found
            500 InternalError

        :returns: JSON dict containing informations about the requested user.
        """
        header('Content-Type', 'application/x-json-stream')
        did_type = None
        if ctx.query:
            params = parse_qs(ctx.query[1:])
            if 'did_type' in params:
                did_type = params['did_type'][0]
        try:
            if did_type == 'dataset':
                for lock in get_dataset_locks(scope, name):
                    yield render_json(**lock) + '\n'
            else:
                raise InternalError('Wrong did_type specified')
        except RucioException, e:
            raise generate_http_error(500, e.__class__.__name__, e.args[0])
开发者ID:pombredanne,项目名称:rucio,代码行数:26,代码来源:lock.py

示例13: POST

	def POST(self):
		data = web.data()
		query_data=json.loads(data)
		start_time=query_data["start_time"]
		end_time=query_data["end_time"]
		parameter=query_data["parameter"]
		query="SELECT "+parameter+",timestamp FROM jplug_data WHERE timestamp BETWEEN "+str(start_time)+" AND "+str(end_time)
		retrieved_data=list(db.query(query))
		LEN=len(retrieved_data)
		x=[0]*LEN
		y=[0]*LEN
		X=[None]*LEN
		for i in range(0,LEN):
			x[i]=retrieved_data[i]["timestamp"]
			y[i]=retrieved_data[i][parameter]
			X[i]=datetime.datetime.fromtimestamp(x[i],pytz.timezone(TIMEZONE))
			#print retrieved_data["timestamp"]
		with lock:
			figure = plt.gcf() # get current figure
			plt.axes().relim()
			plt.title(parameter+" vs Time")
			plt.xlabel("Time")
			plt.ylabel(units[parameter])
			plt.axes().autoscale_view(True,True,True)
			figure.autofmt_xdate()
			plt.plot(X,y)
			filename=randomword(12)+".jpg"
			plt.savefig("/home/muc/Desktop/Deployment/jplug_view_data/static/images/"+filename, bbox_inches=0,dpi=100)
			plt.close()
			web.header('Content-Type', 'application/json')
			return json.dumps({"filename":filename})
开发者ID:brianjgeiger,项目名称:Home_Deployment,代码行数:31,代码来源:smart_meter_csv.py

示例14: GET

 def GET(self):
     s = ""
     sdb = sqldb()
     rec = sdb.cu.execute("""select * from msgs""")
     dbre = sdb.cu.fetchall()
     web.header("Content-Type", "text/html; charset=utf-8")
     return render.index(dbre)
开发者ID:liujianhei,项目名称:python,代码行数:7,代码来源:guestbook.py

示例15: GET

    def GET(self, sitename, offset):
        i = web.input(timestamp=None, limit=1000)
        
        if not config.writelog:
            raise web.notfound("")
        else:
            log = self.get_log(offset, i)
            limit = min(1000, common.safeint(i.limit, 1000))
            
            try:
                # read the first line
                line = log.readline(do_update=False)
                # first line can be incomplete if the offset is wrong. Assert valid.
                self.assert_valid_json(line)
                
                web.header('Content-Type', 'application/json')
                yield '{"data": [\n'
                yield line.strip()

                for i in range(1, limit):
                    line = log.readline(do_update=False)
                    if line:
                        yield ",\n" + line.strip()
                    else:
                        break
                yield '], \n'
                yield '"offset": ' + simplejson.dumps(log.tell()) + "\n}\n"
            except Exception, e:
                print 'ERROR:', str(e)
开发者ID:termim,项目名称:infogami,代码行数:29,代码来源:server.py


注:本文中的web.header函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。