本文整理汇总了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)
示例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])
示例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
示例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)
})
示例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
示例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
示例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 })
示例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)
示例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>')
示例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})
示例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'
示例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])
示例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})
示例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)
示例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)