本文整理汇总了Python中webob.exc.HTTPBadRequest类的典型用法代码示例。如果您正苦于以下问题:Python HTTPBadRequest类的具体用法?Python HTTPBadRequest怎么用?Python HTTPBadRequest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HTTPBadRequest类的17个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: GETorHEAD
def GETorHEAD(self, req, stats_type):
"""Handler for HTTP GET/HEAD requests."""
start_time = time.time()
partition, nodes = self.app.account_ring.get_nodes(self.account_name)
shuffle(nodes)
resp = self.GETorHEAD_base(req, _('Account'), partition, nodes,
req.path_info.rstrip('/'), len(nodes))
if resp.status_int == HTTP_NOT_FOUND and self.app.account_autocreate:
if len(self.account_name) > MAX_ACCOUNT_NAME_LENGTH:
resp = HTTPBadRequest(request=req)
resp.body = 'Account name length of %d longer than %d' % \
(len(self.account_name), MAX_ACCOUNT_NAME_LENGTH)
self.app.logger.timing_since(
'%s.timing' % (stats_type,), start_time)
return resp
headers = {'X-Timestamp': normalize_timestamp(time.time()),
'X-Trans-Id': self.trans_id,
'Connection': 'close'}
resp = self.make_requests(
Request.blank('/v1/' + self.account_name),
self.app.account_ring, partition, 'PUT',
'/' + self.account_name, [headers] * len(nodes))
if not is_success(resp.status_int):
self.app.logger.warning('Could not autocreate account %r' %
self.account_name)
return resp
resp = self.GETorHEAD_base(req, _('Account'), partition, nodes,
req.path_info.rstrip('/'), len(nodes))
self.app.logger.timing_since('%s.timing' % (stats_type,), start_time)
return resp
开发者ID:missall,项目名称:swift,代码行数:30,代码来源:account.py
示例2: PUT
def PUT(self, req):
"""HTTP PUT request handler."""
start_time = time.time()
if not self.app.allow_account_management:
self.app.logger.timing_since('PUT.timing', start_time)
return HTTPMethodNotAllowed(request=req)
error_response = check_metadata(req, 'account')
if error_response:
self.app.logger.increment('errors')
return error_response
if len(self.account_name) > MAX_ACCOUNT_NAME_LENGTH:
resp = HTTPBadRequest(request=req)
resp.body = 'Account name length of %d longer than %d' % \
(len(self.account_name), MAX_ACCOUNT_NAME_LENGTH)
self.app.logger.increment('errors')
return resp
account_partition, accounts = \
self.app.account_ring.get_nodes(self.account_name)
headers = {'X-Timestamp': normalize_timestamp(time.time()),
'x-trans-id': self.trans_id,
'Connection': 'close'}
self.transfer_headers(req.headers, headers)
if self.app.memcache:
self.app.memcache.delete('account%s' % req.path_info.rstrip('/'))
resp = self.make_requests(req, self.app.account_ring,
account_partition, 'PUT', req.path_info, [headers] * len(accounts))
self.app.logger.timing_since('PUT.timing', start_time)
return resp
开发者ID:missall,项目名称:swift,代码行数:28,代码来源:account.py
示例3: GETorHEAD
def GETorHEAD(self, req):
"""Handler for HTTP GET/HEAD requests."""
partition, nodes = self.app.account_ring.get_nodes(self.account_name)
shuffle(nodes)
resp = self.GETorHEAD_base(req, _("Account"), partition, nodes, req.path_info.rstrip("/"), len(nodes))
if resp.status_int == HTTP_NOT_FOUND and self.app.account_autocreate:
if len(self.account_name) > MAX_ACCOUNT_NAME_LENGTH:
resp = HTTPBadRequest(request=req)
resp.body = "Account name length of %d longer than %d" % (
len(self.account_name),
MAX_ACCOUNT_NAME_LENGTH,
)
return resp
headers = {
"X-Timestamp": normalize_timestamp(time.time()),
"X-Trans-Id": self.trans_id,
"Connection": "close",
}
resp = self.make_requests(
Request.blank("/v1/" + self.account_name),
self.app.account_ring,
partition,
"PUT",
"/" + self.account_name,
[headers] * len(nodes),
)
if not is_success(resp.status_int):
self.app.logger.warning("Could not autocreate account %r" % self.account_name)
return resp
resp = self.GETorHEAD_base(req, _("Account"), partition, nodes, req.path_info.rstrip("/"), len(nodes))
return resp
开发者ID:hortonworkstest,项目名称:Hadoop-and-Swift-integration,代码行数:31,代码来源:account.py
示例4: POST
def POST(self, req):
"""HTTP POST request handler."""
error_response = check_metadata(req, "account")
if error_response:
return error_response
account_partition, accounts = self.app.account_ring.get_nodes(self.account_name)
headers = {"X-Timestamp": normalize_timestamp(time.time()), "X-Trans-Id": self.trans_id, "Connection": "close"}
self.transfer_headers(req.headers, headers)
if self.app.memcache:
self.app.memcache.delete("account%s" % req.path_info.rstrip("/"))
resp = self.make_requests(
req, self.app.account_ring, account_partition, "POST", req.path_info, [headers] * len(accounts)
)
if resp.status_int == HTTP_NOT_FOUND and self.app.account_autocreate:
if len(self.account_name) > MAX_ACCOUNT_NAME_LENGTH:
resp = HTTPBadRequest(request=req)
resp.body = "Account name length of %d longer than %d" % (
len(self.account_name),
MAX_ACCOUNT_NAME_LENGTH,
)
return resp
resp = self.make_requests(
Request.blank("/v1/" + self.account_name),
self.app.account_ring,
account_partition,
"PUT",
"/" + self.account_name,
[headers] * len(accounts),
)
if not is_success(resp.status_int):
self.app.logger.warning("Could not autocreate account %r" % self.account_name)
return resp
return resp
开发者ID:hortonworkstest,项目名称:Hadoop-and-Swift-integration,代码行数:33,代码来源:account.py
示例5: POST
def POST(self, req):
"""HTTP POST request handler."""
start_time = time.time()
error_response = check_metadata(req, 'account')
if error_response:
self.app.logger.increment('errors')
return error_response
account_partition, accounts = \
self.app.account_ring.get_nodes(self.account_name)
headers = {'X-Timestamp': normalize_timestamp(time.time()),
'X-Trans-Id': self.trans_id,
'Connection': 'close'}
self.transfer_headers(req.headers, headers)
if self.app.memcache:
self.app.memcache.delete('account%s' % req.path_info.rstrip('/'))
resp = self.make_requests(req, self.app.account_ring,
account_partition, 'POST', req.path_info,
[headers] * len(accounts))
if resp.status_int == HTTP_NOT_FOUND and self.app.account_autocreate:
if len(self.account_name) > MAX_ACCOUNT_NAME_LENGTH:
resp = HTTPBadRequest(request=req)
resp.body = 'Account name length of %d longer than %d' % \
(len(self.account_name), MAX_ACCOUNT_NAME_LENGTH)
self.app.logger.increment('errors')
return resp
resp = self.make_requests(
Request.blank('/v1/' + self.account_name),
self.app.account_ring, account_partition, 'PUT',
'/' + self.account_name, [headers] * len(accounts))
if not is_success(resp.status_int):
self.app.logger.warning('Could not autocreate account %r' %
self.account_name)
return resp
self.app.logger.timing_since('POST.timing', start_time)
return resp
开发者ID:missall,项目名称:swift,代码行数:35,代码来源:account.py
示例6: __init__
def __init__(self, error_name):
HTTPBadRequest.__init__(self)
self.error_data = {
'reason': error_name,
'explanation': error_list[error_name],
}
self.explanation = error_list[error_name]
开发者ID:Cophy08,项目名称:reddit,代码行数:7,代码来源:errors.py
示例7: HEAD
def HEAD(self, request):
"""Handle HTTP HEAD requests for the Swift Object Server."""
try:
device, partition, account, container, obj = \
split_path(unquote(request.path), 5, 5, True)
except ValueError, err:
resp = HTTPBadRequest(request=request)
resp.content_type = 'text/plain'
resp.body = str(err)
return resp
开发者ID:Nupta,项目名称:swift,代码行数:10,代码来源:server.py
示例8: HEAD
def HEAD(self, request):
"""Handle HTTP HEAD requests for the Swift Object Server."""
start_time = time.time()
try:
device, partition, account, container, obj = split_path(unquote(request.path), 5, 5, True)
validate_device_partition(device, partition)
except ValueError, err:
self.logger.increment("HEAD.errors")
resp = HTTPBadRequest(request=request)
resp.content_type = "text/plain"
resp.body = str(err)
return resp
开发者ID:andrewgaul,项目名称:swift,代码行数:12,代码来源:server.py
示例9: PUT
def PUT(self, req):
"""HTTP PUT request handler."""
start_time = time.time()
error_response = \
self.clean_acls(req) or check_metadata(req, 'container')
if error_response:
self.app.logger.increment('errors')
return error_response
if len(self.container_name) > MAX_CONTAINER_NAME_LENGTH:
resp = HTTPBadRequest(request=req)
resp.body = 'Container name length of %d longer than %d' % \
(len(self.container_name), MAX_CONTAINER_NAME_LENGTH)
self.app.logger.increment('errors')
return resp
account_partition, accounts, container_count = \
self.account_info(self.account_name,
autocreate=self.app.account_autocreate)
if self.app.max_containers_per_account > 0 and \
container_count >= self.app.max_containers_per_account and \
self.account_name not in self.app.max_containers_whitelist:
resp = HTTPForbidden(request=req)
resp.body = 'Reached container limit of %s' % \
self.app.max_containers_per_account
return resp
if not accounts:
self.app.logger.timing_since('PUT.timing', start_time)
return HTTPNotFound(request=req)
container_partition, containers = self.app.container_ring.get_nodes(
self.account_name, self.container_name)
headers = []
for account in accounts:
nheaders = {'X-Timestamp': normalize_timestamp(time.time()),
'x-trans-id': self.trans_id,
'X-Account-Host': '%(ip)s:%(port)s' % account,
'X-Account-Partition': account_partition,
'X-Account-Device': account['device'],
'Connection': 'close'}
self.transfer_headers(req.headers, nheaders)
headers.append(nheaders)
if self.app.memcache:
cache_key = get_container_memcache_key(self.account_name,
self.container_name)
self.app.memcache.delete(cache_key)
resp = self.make_requests(req, self.app.container_ring,
container_partition, 'PUT', req.path_info, headers)
self.app.logger.timing_since('PUT.timing', start_time)
return resp
开发者ID:missall,项目名称:swift,代码行数:47,代码来源:container.py
示例10: GET_scopes
def GET_scopes(self, scope_str):
"""Retrieve descriptions of reddit's OAuth2 scopes.
If no scopes are given, information on all scopes are returned.
Invalid scope(s) will result in a 400 error with body that indicates
the invalid scope(s).
"""
scopes = OAuth2Scope(scope_str or self.THREE_SIXTY)
if scope_str and not scopes.is_valid():
invalid = [s for s in scopes.scopes if s not in scopes.scope_info]
error = {"error": "invalid_scopes", "invalid_scopes": invalid}
http_err = HTTPBadRequest()
http_err.error_data = error
abort(http_err)
return self.api_wrapper({k: v for k, v in scopes.details() if k})
开发者ID:pra85,项目名称:reddit,代码行数:17,代码来源:scopes.py
示例11: PUT
def PUT(self, req):
"""HTTP PUT request handler."""
if not self.app.allow_account_management:
return HTTPMethodNotAllowed(request=req)
error_response = check_metadata(req, "account")
if error_response:
return error_response
if len(self.account_name) > MAX_ACCOUNT_NAME_LENGTH:
resp = HTTPBadRequest(request=req)
resp.body = "Account name length of %d longer than %d" % (len(self.account_name), MAX_ACCOUNT_NAME_LENGTH)
return resp
account_partition, accounts = self.app.account_ring.get_nodes(self.account_name)
headers = {"X-Timestamp": normalize_timestamp(time.time()), "x-trans-id": self.trans_id, "Connection": "close"}
self.transfer_headers(req.headers, headers)
if self.app.memcache:
self.app.memcache.delete("account%s" % req.path_info.rstrip("/"))
resp = self.make_requests(
req, self.app.account_ring, account_partition, "PUT", req.path_info, [headers] * len(accounts)
)
return resp
开发者ID:hortonworkstest,项目名称:Hadoop-and-Swift-integration,代码行数:20,代码来源:account.py
示例12: handle_upgrade
def handle_upgrade(self):
"""Completes the upgrade request sent by the browser
Sends the headers required to set up to websocket connection back to
the browser and then hands off to :meth:`handle_websocket`.
See [websocket_protocol]_
:returns: :exc:`webob.exc.HTTPBadRequest` if handshake fails
"""
try:
handshake_reply = websocket_handshake(self.request.headers)
except HandShakeFailed:
_, val, _ = sys.exc_info()
response = HTTPBadRequest(headers=dict(Connection='Close'))
response.body = 'Upgrade negotiation failed:\n\t%s\n%s' % \
(val, self.request.headers)
return response
sock = self.environ['eventlet.input'].get_socket()
sock.sendall(handshake_reply)
return self.handle_websocket(WebSocket(self.sock, self.environ))
开发者ID:okoye,项目名称:stargate,代码行数:21,代码来源:view.py
示例13: handle_upgrade
def handle_upgrade(self):
"""Completes the upgrade request sent by the browser
Sends the headers required to set up to websocket connection back to
the browser and then hands off to :meth:`handle_websocket`. See:
http://en.wikipedia.org/wiki/Web_Sockets#WebSocket_Protocol_Handshake
"""
if not (self.environ.get('HTTP_CONNECTION') == 'Upgrade' and
self.environ.get('HTTP_UPGRADE') == 'WebSocket'):
response = HTTPBadRequest(headers=dict(Connection='Close'))
response.body = 'Bad:\n%s' % pformat(self.environ)
return response
sock = self.environ['eventlet.input'].get_socket()
handshake_reply = ("HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
"Upgrade: WebSocket\r\n"
"Connection: Upgrade\r\n"
"WebSocket-Origin: %s\r\n"
"WebSocket-Location: ws://%s%s\r\n\r\n" % (
self.request.host_url,
self.request.host, self.request.path_info))
sock.sendall(handshake_reply)
websocket = WebSocket(self.sock, self.environ)
return self.handle_websocket(websocket)
开发者ID:boothead,项目名称:multivisor,代码行数:23,代码来源:websocket.py
示例14: __init__
def __init__(self, error):
HTTPBadRequest.__init__(self)
self.error_data = {
'reason': error,
'explanation': error_list[error],
}
开发者ID:benmordecai,项目名称:reddit,代码行数:6,代码来源:errors.py
示例15: __init__
def __init__(self, error_name):
HTTPBadRequest.__init__(self)
self.error_data = {"reason": error_name, "explanation": error_list[error_name]}
开发者ID:RGood,项目名称:reddit,代码行数:3,代码来源:errors.py
示例16: __call__
def __call__(self, environ, start_response):
req = Request(environ)
env = Environment(loader=FileSystemLoader('.'))
amz_dict = {'workerId' : '', 'assignmentId' : '', 'hitId' : ''}
templ, part, listid, template, resp = [None for x in range(5)]
required_keys = ['workerId', 'assignmentId', 'hitId', 'part']
key_error_msg = 'Missing parameter: {0}. Required keys: {1}'
try:
amz_dict['workerId'] = req.params['workerId']
amz_dict['assignmentId'] = req.params['assignmentId']
amz_dict['hitId'] = req.params['hitId']
part = int(req.params['part'])
except KeyError as e:
resp = HTTPBadRequest(key_error_msg.format(e, required_keys))
return resp(environ, start_response)
if amz_dict['assignmentId'] == 'ASSIGNMENT_ID_NOT_AVAILABLE':
template = env.get_template('preview.html')
template = template.render(part = part)
else:
worker = check_worker_exists(amz_dict['workerId'])
if worker:
forbidden_msg = '<p style="font-weight: bold; font-size: x-large;">{0}</p>'
if part in (2,3):
try:
sess = SessionState.query.filter_by(worker=worker).one()
if part == 2:
if not sess.sess1complete:
resp = HTTPForbidden(forbidden_msg.format('You must do part 1 before part 2!'))
else:
sess.sess2complete = True
sess.sess2timestamp = datetime.now()
session.commit() # important! w/o this it won't save them
if part == 3:
if not sess.sess2complete:
resp = HTTPForbidden(body_template=forbidden_msg.format('You must do part 2 before part 3!'))
if not worker.trialgroup.now:
start_time = sess.sess2timestamp + timedelta(days=2)
if datetime.now() < start_time:
resp = HTTPForbidden(forbidden_msg('You must wait at least 2 days before doing part 3!'))
if not resp:
sess.sess3complete = True
sess.sess4timestamp = datetime.now()
session.commit() # important! w/o this it won't save them
except NoResultFound:
resp = HTTPForbidden(forbidden_msg.format('Attempting to do part {0} without having done part 1!'.format(part)))
else:
if part == 1:
worker = Worker(workerid = amz_dict['workerId'], trialgroup = random_lowest_list())
SessionState(sess1complete = True, worker = worker)
session.commit() # important! w/o this it won't save them
else:
# If part is anything but 1 and there's no worker defined,
# then something is horribly wrong
resp = HTTPForbidden(forbidden_msg.format('Attempting to do part {0} without having done part 1!'.format(part)))
if not resp:
sesslist = {1 : worker.trialgroup.sess1list,
2 : worker.trialgroup.sess2list,
3 : worker.trialgroup.sess3list}[part]
if part in (1,3):
template = env.get_template('flash_experiment.html')
else:
template = env.get_template('spr_experiment.html')
template = template.render(part = part, list = sesslist, now=worker.trialgroup.now, amz_dict = amz_dict)
if template and not resp:
resp = Response()
resp.content_type='application/xhtml+xml'
resp.unicode_body = template
return resp(environ, start_response)
开发者ID:hlplab,项目名称:pradpt1,代码行数:74,代码来源:pradpt1.py
示例17: __call__
def __call__(self, environ, start_response):
# SQLAlchemy boilerplate code to connect to db and connect models to db objects
engine = create_engine(engine_string)
Session = sessionmaker(bind=engine)
session = Session()
req = Request(environ)
if req.method != 'POST':
resp = HTTPBadRequest('This page can only be accesses via POST')
return resp(environ, start_response)
else:
firstname = req.POST['firstname']
lastname = req.POST['lastname']
subj = Subject(firstname=firstname, lastname=lastname)
to_add = {}
for k in ('amerind', 'afram', 'pacif', 'asian', 'white',
'unknown', 'ur_student', 'hearing_normal', 'more_expts'):
if req.POST.has_key(k):
to_add[k] = True
for k in ('sex', 'ethnicity', 'other_race', 'gradyear',
'hearing_problems', 'vision_normal', 'vision_other'):
if req.POST.has_key(k):
if req.POST[k] not in (None, '', u''):
to_add[k] = req.POST[k]
if req.POST.has_key('age'):
if req.POST['age'] not in (None, ''):
to_add['age'] = int(req.POST['age'])
if req.POST['entrydate'] not in (None, '', u''):
to_add['entrydate'] = parser.parse(req.POST['entrydate']).date()
else:
to_add['entrydate'] = date.today()
subj.from_dict(to_add)
try:
session.add(subj)
session.commit()
except IntegrityError as e:
resp = HTTPBadRequest(e)
return resp(environ, start_response)
if req.POST.has_key('phone'):
if req.POST['phone'] not in (None, '', u''):
p = Phone(subject = subj, number = req.POST['phone'])
session.add(p)
session.commit()
if req.POST.has_key('email'):
if req.POST['email'] not in (None, '', u''):
em = Email(subject = subj, address = req.POST['email'])
session.add(em)
session.commit()
from pprint import pformat
#output = pformat(subj.to_dict(deep={'phone': {}, 'email': {}}))
env = Environment(loader=FileSystemLoader(os.path.join(basepath,'templates')))
template = env.get_template('subject_list.html')
template = template.render(subjects = [subj.to_dict(deep={'phone': {}, 'email': {}}),])
resp = Response()
resp.content_type='text/html'
resp.unicode_body = template
#resp.content_type='text/plain'
#resp.body = output
return resp(environ, start_response)
开发者ID:awatts,项目名称:subject_demographics,代码行数:70,代码来源:subject_controller.py
注:本文中的webob.exc.HTTPBadRequest类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论