本文整理汇总了Python中bottle.response.status方法的典型用法代码示例。如果您正苦于以下问题:Python response.status方法的具体用法?Python response.status怎么用?Python response.status使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类bottle.response
的用法示例。
在下文中一共展示了response.status方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_token
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import status [as 别名]
def get_token():
# Get JSON Payload
try:
payload = json.load(request.body)
username = payload["username"]
password = payload["password"]
pwhash = _get_password_hash(password)
except:
response.status = 400
return dict({"message":"No valid JSON found in post body or mandatory fields missing."})
user_list = rc.scan_iter("USER:*")
for user in user_list:
user_record = json.loads(rc.get(user))
if user_record["username"] == username and user_record["hash"] == pwhash:
user_token = _issue_token(user=username, id=user[5:], expiry=token_expiry_seconds)
if 'raw' in request.query:
return(user_token)
else:
return(dict(token_type="bearer", access_token=user_token))
response.status = 401
return(dict(info="could not authorize user"))
# Test Auth Token
示例2: backend_info
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import status [as 别名]
def backend_info():
api_auth = _authenticate()
# Only Admin can do this
if api_auth["admin"] != "True" or api_auth["authenticated"] == "False":
response.status = 401
return dict({"info":"Unauthorized."})
i = {}
i["redis_connection"] = {}
i["redis_connection"]["host"] = redis_host
i["redis_connection"]["port"] = redis_port
i["redis_dbsize"] = rc.dbsize()
i["redis_client_list"] = rc.client_list()
i["redis_info"] = rc.info()
return(i)
# Trigger Redis Save
示例3: get_user_details
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import status [as 别名]
def get_user_details(id):
api_auth = _authenticate()
# Only Admin can do this
if api_auth["admin"] != "True" or api_auth["authenticated"] == "False":
response.status = 401
return dict({"info":"Unauthorized."})
# Read from Redis
try:
user_record = json.loads(rc.get("USER:"+str(id)))
except:
response.status = 404
return dict({"info":"Not found."})
user_out = {}
user_out["username"] = user_record["username"]
user_out["quota"] = user_record["quota"]
return(dict(user_out))
# Set Quota for User
示例4: delete_user
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import status [as 别名]
def delete_user(id):
api_auth = _authenticate()
# Only Admin can do this
if api_auth["admin"] != "True" or api_auth["authenticated"] == "False":
response.status = 401
return dict({"info":"Unauthorized."})
# Do not allow deleting admin
if id == 0:
response.status = 400
return dict({"info":"Cannot delete admin user."})
# Does the user exist?
if rc.get("USER:"+str(id)) == None:
response.status = 404
return dict({"info":"Not found."})
# Delete user record
rc.delete("USER:"+str(id))
return(dict(info="user deleted"))
# List All Users
示例5: list_user
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import status [as 别名]
def list_user():
api_auth = _authenticate()
# Only Admin can do this
if api_auth["admin"] != "True" or api_auth["authenticated"] == "False":
response.status = 401
return dict({"info":"Unauthorized."})
output = []
user_list = rc.scan_iter("USER:*")
for user in user_list:
user_record = json.loads(rc.get(user))
user_out = {}
user_out["id"] = user[5:]
user_out["username"] = user_record["username"]
user_out["quota"] = user_record["quota"]
output.append(user_out)
return(dict(users=output))
# Change Admin Password
示例6: set_admin_password
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import status [as 别名]
def set_admin_password():
api_auth = _authenticate()
# Only Admin can do this
if api_auth["admin"] != "True" or api_auth["authenticated"] == "False":
response.status = 401
return dict({"info":"Unauthorized."})
try:
payload = json.load(request.body)
new_password = payload["password"]
except:
response.status = 400
return dict({"info":"No valid JSON found in post body or mandatory fields missing."})
# Read record for admin user
admin_record = json.loads(rc.get("USER:0"))
admin_record["hash"] = _get_password_hash(new_password)
rc.set("USER:0", json.dumps(admin_record, ensure_ascii=False))
return(dict(info="updated"))
# Read Key
示例7: get_config
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import status [as 别名]
def get_config():
"""Returns JavaScript code to set client-side configuration values
:status 200: no error
:status 400: invalid referer
:>json object config: the configuration values
"""
response.set_header('Content-Type', 'application/javascript')
for key, value in [
("notesbase", config.WEB_NOTES_BASE),
("dflt_limit", config.WEB_LIMIT),
("warn_dots_count", config.WEB_WARN_DOTS_COUNT),
("publicsrv", config.WEB_PUBLIC_SRV),
("uploadok", config.WEB_UPLOAD_OK),
("flow_time_precision", config.FLOW_TIME_PRECISION),
("version", VERSION),
]:
yield "config.%s = %s;\n" % (key, json.dumps(value))
#
# /nmap/
#
示例8: get_nmap_count
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import status [as 别名]
def get_nmap_count(subdb):
"""Get special values from Nmap & View databases
:param str subdb: database to query (must be "scans" or "view")
:query str q: query (including limit/skip and sort)
:query str callback: callback to use for JSONP results
:status 200: no error
:status 400: invalid referer
:>json int: count
"""
subdb = db.view if subdb == 'view' else db.nmap
flt_params = get_nmap_base(subdb)
count = subdb.count(flt_params.flt)
if flt_params.callback is None:
return "%d\n" % count
return "%s(%d);\n" % (flt_params.callback, count)
示例9: upload
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import status [as 别名]
def upload():
response.set_header("Access-Control-Allow-Origin", "*")
try:
# Body may or may not be compressed.
message_body = get_decompressed_message()
except zlib.error as exc:
# Some languages and libs do a crap job zlib compressing stuff. Provide
# at least some kind of feedback for them to try to get pointed in
# the correct direction.
response.status = 400
logger.error("gzip error with %s: %s" % (get_remote_address(), exc.message))
return exc.message
except MalformedUploadError as exc:
# They probably sent an encoded POST, but got the key/val wrong.
response.status = 400
logger.error("Error to %s: %s" % (get_remote_address(), exc.message))
return exc.message
statsCollector.tally("inbound")
return parse_and_error_handle(message_body)
示例10: error_default
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import status [as 别名]
def error_default(exception):
status = response.status
name = HTTP_CODES.get(status, 'Unknown').title()
url = request.path
"""If an exception is thrown, deal with it and present an error page."""
yield template('<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">' + \
'<html><head><title>Error {{status}}: {{msg}}</title>' + \
'</head><body><h1>Error {{status}}: {{msg}}</h1>' + \
'<p>Sorry, the requested URL {{url}} caused an error.</p>',
status=status,
msg=name,
url=url
)
if hasattr(exception, 'output'):
yield exception.output
yield '</body></html>'
示例11: __call__
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import status [as 别名]
def __call__(self, environ, start_response):
""" The bottle WSGI-interface. """
try:
request.bind(environ, self)
response.bind(self)
out = self.handle(request.path, request.method)
out = self._cast(out, request, response)
if response.status in (100, 101, 204, 304) or request.method == 'HEAD':
out = [] # rfc2616 section 4.3
status = '%d %s' % (response.status, HTTP_CODES[response.status])
start_response(status, response.headerlist)
return out
except (KeyboardInterrupt, SystemExit, MemoryError):
raise
except Exception, e:
if not self.catchall:
raise
err = '<h1>Critical error while processing request: %s</h1>' \
% environ.get('PATH_INFO', '/')
if DEBUG:
err += '<h2>Error:</h2>\n<pre>%s</pre>\n' % repr(e)
err += '<h2>Traceback:</h2>\n<pre>%s</pre>\n' % format_exc(10)
environ['wsgi.errors'].write(err) #TODO: wsgi.error should not get html
start_response('500 INTERNAL SERVER ERROR', [('Content-Type', 'text/html')])
return [tob(err)]
示例12: __call__
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import status [as 别名]
def __call__(self, environ, start_response):
""" The bottle WSGI-interface. """
try:
request.bind(environ, self)
response.bind(self)
out = self.handle(request.path, request.method)
out = self._cast(out, request, response)
if response.status in (100, 101, 204, 304) or request.method == 'HEAD':
out = [] # rfc2616 section 4.3
status = '%d %s' % (response.status, HTTP_CODES[response.status])
start_response(status, response.headerlist)
return out
except (KeyboardInterrupt, SystemExit, MemoryError):
raise
except Exception as e:
if not self.catchall:
raise
err = '<h1>Critical error while processing request: %s</h1>' \
% environ.get('PATH_INFO', '/')
if DEBUG:
err += '<h2>Error:</h2>\n<pre>%s</pre>\n' % repr(e)
err += '<h2>Traceback:</h2>\n<pre>%s</pre>\n' % format_exc(10)
environ['wsgi.errors'].write(err) #TODO: wsgi.error should not get html
start_response('500 INTERNAL SERVER ERROR', [('Content-Type', 'text/html')])
return [tob(err)]
示例13: jsonify
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import status [as 别名]
def jsonify(fn):
@ft.wraps(fn)
def inner(*a, **kw):
response.content_type = 'application/json'
try:
data = fn(*a, **kw)
except HTTPError as e:
response.status = e.status_code
data = {'errors': [e.body]}
except schema.Error as e:
response.status = 400
data = {'errors': e.errors, 'schema': e.schema}
except Exception as e:
log.exception(e)
response.status = 500
data = {'errors': [str(e)]}
return json.dumps(data or {}, indent=2, ensure_ascii=False)
return inner
示例14: login
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import status [as 别名]
def login():
data = schema.validate(request.json, {
'type': 'object',
'properties': {
'username': {'type': 'string'},
'password': {'type': 'string'},
'timezone': {'type': 'string', 'enum': all_timezones},
'theme': {'type': 'string', 'default': 'base'}
},
'required': ['username', 'password', 'timezone']
})
try:
local.connect(data['username'], data['password'])
except imap.Error as e:
response.status = 400
return {'errors': ['Authentication failed.'], 'details': str(e)}
del data['password']
request.session.update(data)
return {}
示例15: fetch_avatars
# 需要导入模块: from bottle import response [as 别名]
# 或者: from bottle.response import status [as 别名]
def fetch_avatars(hashes, size=20, default='identicon', b64=True):
def _avatar(hash):
if hash in cache:
return cache[hash]
res = urllib.request.urlopen(get_gravatar_url(hash, size, default))
result = hash, res.read() if res.status == 200 else None
cache[hash] = result
return result
if not hasattr(fetch_avatars, 'cache'):
fetch_avatars.cache = {}
key = (size, default)
fetch_avatars.cache.setdefault(key, {})
cache = fetch_avatars.cache[key]
pool = ThreadPool(20)
res = pool.map(_avatar, hashes)
return [(i[0], base64.b64encode(i[1]) if b64 else i[1]) for i in res if i]