本文整理汇总了Python中werkzeug.Response.status_code方法的典型用法代码示例。如果您正苦于以下问题:Python Response.status_code方法的具体用法?Python Response.status_code怎么用?Python Response.status_code使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类werkzeug.Response
的用法示例。
在下文中一共展示了Response.status_code方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __call__
# 需要导入模块: from werkzeug import Response [as 别名]
# 或者: from werkzeug.Response import status_code [as 别名]
def __call__(self, env, start_response):
Config = ConfigParser()
Config.read(configfile)
params = {"host": "", "user": "", "database": "", "port": ""}
for param in params:
if not Config.has_option("BlobStore", param):
print "Malformed configuration file: mission option %s in section %s" % (param, "BlobStore")
sys.exit(1)
params[param] = Config.get("BlobStore", param)
req = Request(env)
resp = Response(status=200, content_type="text/plain")
#engine = create_engine("mysql+mysqldb://%s:%[email protected]%s:%s/%s?charset=utf8&use_unicode=0" %
# (params["user"], secret.BlobSecret, params["host"], params["port"], params["database"]), pool_recycle=3600)
Base = declarative_base(bind=engine)
local.Session = []
local.FileEntry = []
Session.append(sessionmaker(bind=engine))
FileEntry.append(makeFileEntry(Base))
if req.path.startswith('/fx'):
if req.method == "GET":
resp.status_code, filename, resp.content_type, resp.response = self.__download(req)
if resp.content_type == "application/octet-stream":
resp.headers["Content-Disposition"] = "attachment; filename=%s" % filename
return resp(env, start_response)
elif req.method == "POST":
resp.content_type="text/plain"
resp.response = self.__upload(req)
return resp(env, start_response)
else:
resp.status_code = 404
resp.content_type="text/plain"
resp.response = ""
return resp(env, start_response)
示例2: humanify
# 需要导入模块: from werkzeug import Response [as 别名]
# 或者: from werkzeug.Response import status_code [as 别名]
def humanify(obj, status_code=200):
""" Gets an obj and possibly a status code and returns a flask Resonse
with a jsonified obj, not suitable for humans
>>> humanify({"a": 1})
<Response 8 bytes [200 OK]>
>>> humanify({"a": 1}, 404)
<Response 8 bytes [404 NOT FOUND]>
>>> humanify({"a": 1}).get_data()
'{"a": 1}'
>>> humanify([1,2,3]).get_data()
'[1, 2, 3]'
"""
# TODO: refactor the name to `response`
# jsonify function doesn't work with lists
if type(obj) == list:
data = json.dumps(obj, default=json_util.default)
elif type(obj) == pymongo.cursor.Cursor:
rv = []
for doc in obj:
doc['_id'] = str(doc['_id'])
rv.append(dumps(doc))
data = '[' + ',\n'.join(rv) + ']' + '\n'
else:
data = dumps(obj,
default=json_util.default,
cls=MongoJsonEncoder)
resp = Response(data, mimetype='application/json')
resp.status_code = status_code
return resp
示例3: __call__
# 需要导入模块: from werkzeug import Response [as 别名]
# 或者: from werkzeug.Response import status_code [as 别名]
def __call__(self, env, start_response):
req = Request(env)
Config = ConfigParser()
Config.read(configfile)
params = {"host": "", "user": "", "database": "", "port": ""}
for param in params:
if not Config.has_option("MySQL", param):
print "Malformed configuration file: mission option %s in section MySQL" % (param)
sys.exit(1)
params[param] = Config.get("MySQL", param)
#engine = create_engine("mysql+mysqldb://%s:%[email protected]%s:%s/%s?charset=utf8&use_unicode=0" %
# (params["user"], secret.MySQL, params["host"], params["port"], params["database"]), pool_recycle=3600)
Base = declarative_base(bind=engine)
local.Session = []
local.User = []
local.MethodEmail = []
local.Session.append(sessionmaker(bind=engine))
local.User.append(makeUser(Base))
local.MethodEmail.append(makeMethodEmail(Base))
resp = Response(status=200)
if req.path == '/register':
resp.content_type = "text/html"
resp.response = self.__register(req)
return resp(env, start_response)
elif req.path == '/regemail1':
resp.content_type = "text/html"
resp.response = self.__addEmailAuth1(req)
return resp(env, start_response)
elif req.path == '/regemail2':
resp.content_type = "text/html"
resp.response = self.__addEmailAuth2(req)
return resp(env, start_response)
elif req.path == '/regemail3':
resp.content_type = "text/html"
resp.response = self.__addEmailAuth3(req)
return resp(env, start_response)
elif req.path == '/regemailkill':
resp.content_type = "text/html"
resp.response = self.__removeEmailAuth(req)
return resp(env, start_response)
elif req.path == '/regemaillist':
resp.content_type = "text/plain"
resp.response = self.__listEmailAuth(req)
return resp(env, start_response)
elif req.path == '/auth' and req.values.has_key("email") and req.values.has_key("password"):
resp.content_type = "text/plain"
resp.response = [self.__authenticateByEmail(req)]
return resp(env, start_response)
elif req.path == '/auth' and req.values.has_key("uid"):
resp.content_type = "text/plain"
uid = self.__uid(req)
if uid == None:
uid = ""
resp.response = [uid]
return resp(env, start_response)
else:
resp.status_code = 404
resp.response = [""]
return resp(env, start_response)
示例4: __call__
# 需要导入模块: from werkzeug import Response [as 别名]
# 或者: from werkzeug.Response import status_code [as 别名]
def __call__(self, env, start_response):
req = Request(env)
Config = ConfigParser()
Config.read(configfile)
params = {"host": "", "user": "", "database": "", "port": ""}
for param in params:
if not Config.has_option("MySQL", param):
print "Malformed configuration file: mission option %s in section MySQL" % (param)
sys.exit(1)
params[param] = Config.get("MySQL", param)
#print params
#engine = create_engine("mysql+mysqldb://%s:%[email protected]%s:%s/%s?charset=utf8&use_unicode=0" %
# (params["user"], secret.MySQL, params["host"], params["port"], params["database"]), pool_recycle=3600)
Base = declarative_base(bind=engine)
local.Session = []
local.Package = []
local.Session.append(sessionmaker(bind=engine))
local.Package.append(makePackage(Base))
resp = Response(status=200, content_type="text/plain")
if req.path == '/pkg/upload':
resp.content_type="text/html"
resp.response = self.__upload(req)
return resp(env, start_response)
elif req.path == '/pkg/sdk':
resp.content_disposition="application/force-download"
resp.content_type="application/python"
resp.headers.add("Content-Disposition", "attachment; filename=appcfg.py")
f = open("appcfg.py").read().replace("__REPO_UPLOAD__", '"%s"' % (req.host_url + 'pkg/upload'))
resp.headers.add("Content-Length", str(len(f)))
resp.response = [f]
return resp(env, start_response)
elif req.path.startswith('/pkg'):
resp.status_code, resp.content_encoding, resp.response = self.__download(req)
return resp(env, start_response)
else:
resp.status_code = 404
resp.response = [""]
return resp(env, start_response)
示例5: application
# 需要导入模块: from werkzeug import Response [as 别名]
# 或者: from werkzeug.Response import status_code [as 别名]
def application(request):
try:
# Parse the JSON in the request
try:
data = loads(request.stream.read())
except ValueError:
raise BadRequest()
# Grab the function to execute
try:
method = getattr(backend, data['method'])
except (KeyError, IndexError):
raise BadRequest()
if method is None:
raise NotFound()
# Get the args and kwargs
args = data.get('args', [])
kwargs = data.get('kwargs', {})
kwargs = dict(((k.encode('utf-8'), v) for k, v in kwargs.iteritems()))
# Attempt to call the method with the params, or catch the
# exception and pass that back to the client
try:
response = Response(dumps({
'id': data.get('id'),
'result': method(*args, **kwargs),
'error': None,
}))
except (KeyboardInterrupt, SystemExit):
raise
except Exception, e:
print e
response = Response(dumps({
'id': data.get('id'),
'result': None,
'error': ''.join(traceback.format_exception(*sys.exc_info())),
}))
# Finish up and return the response
response.headers['Content-Type'] = 'application/json'
response.headers['Content-Length'] = len(response.data)
response.status_code = 200
return response
示例6: __call__
# 需要导入模块: from werkzeug import Response [as 别名]
# 或者: from werkzeug.Response import status_code [as 别名]
def __call__(self, env, start_response):
local.application = self
req = Request(env)
resp = Response(status=200)
start_response('200 OK', [('Content-Type', 'text/plain')])
if req.path == '/start':
# Have all arguments been passed?
if not (req.values.has_key("protocol") and req.values.has_key("ncli") and req.values.has_key("nsrv") and req.values.has_key("rep")):
resp.status_code = 500
resp.response = ["One of the mandatory arguments has been omitted [protocol, ncli, nsrv, rep]"]
return resp(env, start_response)
# Does protocol have a valid value?
protocol = req.values["protocol"]
if protocol not in protocols:
resp.status_code = 500
resp.response = ["Protocol specified is not implemented; must be one of [ftp, http, udt, gridftp, torrent]"]
return resp(env, start_response)
# Do these arguments have valid numeric values?
try:
ncli, nsrv, rep = int(req.values["ncli"]), int(req.values["nsrv"]), int(req.values["rep"])
except:
resp.status_code = 500
resp.response = ["Unable to parse a mandatory numeric argument"]
return resp(env, start_response)
# Do the numeric arguments make sense?
if ncli < 1 or nsrv < 1 or rep < 1:
resp.status_code = 500
resp.response = ["Go screw yourself"]
return resp(env, start_response)
if ncli > len(clients):
resp.status_code = 500
resp.response = ["We don't have that many clients available. Current maximum is %d" % len(clients)]
return resp(env, start_response)
if nsrv > len(servers):
resp.status_code = 500
resp.response = ["We don't have that many servers available. Current maximum is %d" % len(servers)]
return resp(env, start_response)
# Has the previous experiment been finished already? For that, its nclients*replication must be equal to the number of associated measurements
res = my.query("select max(id) from experiment")
last_exp_id = res.rows[0][0]
if last_exp_id:
res = my.query("select replication, ncli from experiment where id=%s", (last_exp_id,))
rep_prev, ncli_prev = res.rows[0][0], res.rows[0][1]
res = my.query("select count(*) from measurement where experiment_id=%s", (last_exp_id,))
cnt = res.rows[0][0]
if cnt < rep_prev*ncli_prev:
resp.status_code = 500
resp.response = ["Unable to comply, experiment in progress"]
return resp(env, start_response)
f = NamedTemporaryFile(delete=False)
f.write(generatehaproxycfg(nsrv))
f.close()
local.ssh = paramiko.SSHClient()
local.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
local.ssh.connect(proxy, username='root', key_filename='/home/rumith/.ssh/awskeys.pem')
local.scp = scp.SCPClient(local.ssh.get_transport())
local.scp.put(f.name, "/etc/haproxy/haproxy.cfg")
if protocol == "http":
stdin, stdout, stderr = local.ssh.exec_command('pkill haproxy; haproxy -f /etc/haproxy/haproxy.cfg')
local.ssh.close()
os.unlink(f.name)
expcount, experiment_id = my.query("insert into experiment (started, protocol, ncli, nsrv, replication) values ((select now()), %s, %s, %s, %s)", (protocol, ncli, nsrv, rep))
# Copy the required protocol download programs to the clients used and start them
for i in range(ncli):
local.ssh = paramiko.SSHClient()
local.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
local.ssh.connect(clients[i], username='rumith', key_filename='/home/rumith/.ssh/id_rsa')
local.scp = scp.SCPClient(local.ssh.get_transport())
local.scp.put("protocol-%s.sh" % protocol, "/home/protobench")
if protocol == "http":
stdin, stdout, stderr = local.ssh.exec_command('cd /home/protobench && ./protocol-%s.sh %s %s 1 > /dev/null 2>&1 &' % (protocol, proxy, experiment_id))
local.ssh.close()
resp.response = ["Experiment %d x %d [%s] successfully started; replication %d" % (nsrv, ncli, protocol, rep) ]
return resp(env, start_response)
elif req.path == '/done':
# Did the client pass all the required arguments?
if not (req.values.has_key("expid") and req.values.has_key("runid") and req.values.has_key("bw")):
resp.status_code = 500
resp.response = ["One of the mandatory arguments has been omitted [expid, runid, bw]"]
return resp(env, start_response)
# Do they have legal values?
try:
expid, runid, bandwidth = int(req.values["expid"]), int(req.values["runid"]), int(req.values["bw"])
except:
resp.status_code = 500
resp.response = ["Unable to parse mandatory arguments"]
return resp(env, start_response)
#.........这里部分代码省略.........