• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python web.header函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: POST

    def POST(self):
        web.header('Content-Type', 'text/html')
        f = login_form()
        if not f.validates():
            raise web.seeother('/')

        authOptions = [am for am in web.config.auth.methods if am.can_handle_user(f.d.username)]
        if len(authOptions) == 0:
            raise web.internalerror("No appropriate login method available")

        for ao in authOptions:
            try:
                success, res = ao.login(f.d.username, f.d.password, web.config)
                if success == True:
                    web.config.session.loggedin = True
                    web.config.session.userid = res['userid']
                    web.config.session.userfullname = res['userfullname']
                    web.config.session.userrights = res['rights']
                    raise web.seeother("/")
            except RequireRegistrationException, info:
                web.config.session.showIdentifierRegistration = True
                web.config.session.userid = info.username
                web.config.session.userfullname = info.userfullname
                web.config.session.userrights = "none"
                raise web.seeother('/register')
开发者ID:apanly,项目名称:gitweb.py,代码行数:25,代码来源:login.py


示例17: GET

    def GET(self):

        # note view_wpad does not return a string
        data = str(view_wpad())
        web.header('Content-Type', 'application/x-ns-proxy-autoconfig')
        web.header('Content-Length',len(data))
        return data
开发者ID:rd37,项目名称:shoal,代码行数:7,代码来源:view.py


示例18: GET

 def GET(self):
     web.header('Access-Control-Allow-Origin', self.allow_origin)
     data = web.input()
     machine_array = []
     try:
         if 'fast' in data and data['fast'] == 'True':
             # !! TODO parse out the config.json file for the label
             # !! TODO use current users home directory instead of /root
             if os.path.isdir('/root/.docker/machine/machines'):
                 out = subprocess.check_output("ls -1 /root/.docker/machine/machines", shell=True)
                 out = str(out)
                 out = out.split("\n")
                 for machine in out[:-1]:
                     machine_array.append(machine)
             else:
                 out = ""
         else:
             out = subprocess.check_output("/usr/local/bin/docker-machine ls --filter label=vcontrol_managed=yes", shell=True)
             out = str(out)
             out = out.split("\n")
             for machine in out[1:-1]:
                 i = machine.split(" ")
                 machine_array.append(i[0])
     except:
         print(sys.exc_info())
     return str(machine_array)
开发者ID:CyberReboot,项目名称:vcontrol,代码行数:26,代码来源:list_all.py


示例19: GET

    def GET(self):
        i = web.input(key=None)
        changes = db.get_recent_changes(key=i.key, limit=50)
        site =  web.ctx.home

        def diff(key, revision):
            b = db.get_version(key, revision)

            rev_a = revision -1
            if rev_a is 0:
                a = web.ctx.site.new(key, {})
                a.revision = 0
            else: 
                a = db.get_version(key, revision=rev_a)
                
            diff = render.diff(a, b)

            #@@ dirty hack to extract diff table from diff
            import re
            rx = re.compile(r"^.*(<table.*<\/table>).*$", re.S)
            return rx.sub(r'\1', str(diff))
            
        web.header('Content-Type', 'application/rss+xml')

        for c in changes:
            c.diff = diff(c.key, c.revision)
            c.created = self._format_date(c.created)
        print render.feed(site, changes)
开发者ID:EdwardBetts,项目名称:infogami,代码行数:28,代码来源:code.py


示例20: POST

 def POST(self):
     creds = json.loads(web.data())
   
     username = None
     password = None 
     passwd_creds = creds.get('passwordCredentials', None)
     if passwd_creds != None:
         username = creds.get('passwordCredentials').get('username', None)
         password = creds.get('passwordCredentials').get('password', None)
     tenant_id = creds.get('tenantID', None)
     tenant_name = creds.get('tenantName', None)
     token_id = creds.get('tokenID', None)
     
     keystone = identity.auth(usr=username, passwd=password, token_id=token_id, tenant_id=tenant_id, tenant_name=tenant_name, url=_endpoint, api="NATIVE")
     token = identity.get_token(keystone, usr=username, passwd=password, api="NATIVE", tenant_id=tenant_id, tenant_name=tenant_name, token_id=token_id)
     
     if token == -1:
         return web.webUnauthorized()
     
     auth_token = {}
     auth_token['token'] = token.id
     
     body = json.dumps(auth_token)
     web.header("Content-Type", "application/json")
     
     return body
开发者ID:lixmgl,项目名称:Intern_OpenStack_Swift,代码行数:26,代码来源:identityWeb.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python web.htmlquote函数代码示例发布时间:2022-05-26
下一篇:
Python web.head函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap