本文整理汇总了Python中httplib.BAD_REQUEST属性的典型用法代码示例。如果您正苦于以下问题:Python httplib.BAD_REQUEST属性的具体用法?Python httplib.BAD_REQUEST怎么用?Python httplib.BAD_REQUEST使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类httplib
的用法示例。
在下文中一共展示了httplib.BAD_REQUEST属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_user
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BAD_REQUEST [as 别名]
def create_user():
if not settings.load()['config'].get('allow_account_creation', False):
return JSONResponse(status=httplib.FORBIDDEN)
""" This API route is used by the create new account template to add a new user into Mongo """
if isinstance(request.json, dict):
args = request.json
if args.get('username') and args.get('password'):
try:
user = users.create_user(args['username'], args['password'], args.get('email'), args.get('full_name'))
except users.PasswordPolicyError as error:
regex, rules = error.args
return JSONResponse({'violation': {'regex': regex, 'rules': rules}}, httplib.BAD_REQUEST)
if user is not None:
response = Response(status=httplib.CREATED)
response.set_cookie('user-token', user.generate_token(), max_age=datetime.timedelta(days=7))
return response
else:
return JSONResponse({'message': 'Username already exists!'}, status=httplib.BAD_REQUEST)
return JSONResponse({'message': 'Username, email and password are required'}, status=httplib.BAD_REQUEST)
示例2: automate_session_custom
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BAD_REQUEST [as 别名]
def automate_session_custom(session, user=None):
"""
:type session: cascade.session.Session
:type user: User
"""
session = Session.objects.with_id(session)
if not session:
return None, httplib.NOT_FOUND
if not isinstance(request.json, dict):
return None, httplib.BAD_REQUEST
query = DataModelQuery._from_son(request.json['query'])
job = CustomQueryJob.update_existing(session=session, event_query=query, user=user)
job.submit()
return None, httplib.OK
示例3: submit_analytic
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BAD_REQUEST [as 别名]
def submit_analytic(user=None):
if 'update_many' in request.args:
if isinstance(request.json, dict) and request.json.get('analytics') is not None:
count = 0
for content in request.json['analytics']:
_id = content.pop('_id', None)
analytic = Analytic.objects.with_id(_id)
if analytic is not None:
count += analytic.update(**content)
return Analytic.objects(), httplib.OK
return {}, httplib.BAD_REQUEST
# creating a new analytic
else:
if request.json.get('platform', 'CASCADE') == 'CASCADE':
analytic = CascadeAnalytic._from_son(request.json)
else:
analytic = ExternalAnalytic._from_son(request.json)
analytic.save()
return analytic.id, httplib.OK
示例4: make_query
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BAD_REQUEST [as 别名]
def make_query():
try:
query = parser.generate_query(request.json['query'])
event_type, action = DataModelQueryLayer.get_data_model(query)
return {'object': event_type.object_name, 'action': action, 'query': query}, httplib.OK
except InvalidFieldError:
return {'error': 'Invalid Data Model field in query'}, httplib.BAD_REQUEST
except InvalidActionError:
return {'error': 'Invalid Data Model action in query'}, httplib.BAD_REQUEST
except InvalidObjectError:
return {'error': 'Invalid Data Model object in query'}, httplib.BAD_REQUEST
except parser.ParserError:
return {'error': 'Unable to parse query'}, httplib.BAD_REQUEST
示例5: validation_error_try_to_accept
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BAD_REQUEST [as 别名]
def validation_error_try_to_accept(err, data, schema):
"""
Custom validation error handler which attempts alternative
validation
"""
if not isinstance(err, ValidationError):
abort(Response(err, status=HTTPStatus.BAD_REQUEST))
alernative_schema = dict(schema)
alernative_schema['properties']['running_time'].update({
'description': "Films's running time",
'type': 'integer',
'example': 169
})
try:
jsonschema.validate(data, alernative_schema)
except ValidationError as err:
abort(Response(str(err), status=400))
示例6: put_empty
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BAD_REQUEST [as 别名]
def put_empty(self, token):
"""Empty put is used to query upload progress.
The file must has not finished upload.
Args:
token: upload token returned by post_start_creation.
Returns:
last offset uploaded. -1 if none has been uploaded.
Raises:
ValueError: if token matches no in progress uploads.
"""
ns = namespace_manager.get_namespace()
try:
namespace_manager.set_namespace('')
gcs_file = _AE_GCSFileInfo_.get_by_key_name(token)
if not gcs_file:
raise ValueError('Invalid token', httplib.BAD_REQUEST)
return gcs_file.next_offset - 1
finally:
namespace_manager.set_namespace(ns)
示例7: post
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BAD_REQUEST [as 别名]
def post(self): # pylint:disable-msg=invalid-name
"""Handles HTTP POST requests."""
if not users.is_current_user_admin():
self.response.set_status(httplib.UNAUTHORIZED)
return
project_id = self.request.data['project_id']
if not project_id:
Abort(httplib.BAD_REQUEST, 'project_id required')
project = model.GetProject(project_id)
if not project:
Abort(httplib.NOT_FOUND,
'failed to retrieve project {}'.format(project_id))
repo_url = project.template_url
repo = model.GetRepo(repo_url)
model.CreateRepoAsync(owner=model.GetOrCreateUser(repo.owner),
repo_url=repo.key.id(),
html_url=repo.html_url,
name=repo.name,
description=repo.description,
show_files=repo.show_files,
read_only_files=repo.read_only_files,
read_only_demo_url=repo.read_only_demo_url)
示例8: get
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BAD_REQUEST [as 别名]
def get(self, rule_key):
logging.info('Rule handler get method called with key: %s', rule_key)
key = datastore_utils.GetKeyFromUrlsafe(rule_key)
if not key:
self.abort(
httplib.BAD_REQUEST,
explanation='Rule key %s could not be parsed' % rule_key)
rule = key.get()
if rule:
response = rule.to_dict()
response['target_id'] = rule.key.parent().id()
self.respond_json(response)
else:
self.abort(httplib.NOT_FOUND, explanation='Rule not found')
# The Webapp2 routes defined for these handlers.
示例9: testPost_BadRequest_InvalidRenewalError
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BAD_REQUEST [as 别名]
def testPost_BadRequest_InvalidRenewalError(self):
user = test_utils.CreateUser()
host = test_utils.CreateSantaHost(primary_user=user.nickname)
params = {
'duration': 'DAY',
'reason': constants.EXEMPTION_REASON.DEVELOPER_MACOS}
with self.LoggedInUser(user=user):
self.testapp.post(
self.ROUTE % host.key.id(), params=params, status=httplib.OK)
self.testapp.post(
self.ROUTE % host.key.id(), params=params, status=httplib.BAD_REQUEST)
exm = exemption_models.Exemption.Get(host.key.id())
self.assertEqual(constants.EXEMPTION_STATE.REQUESTED, exm.state)
self.assertBigQueryInsertion(constants.BIGQUERY_TABLE.EXEMPTION)
self.mock_process.assert_called_once()
示例10: post
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BAD_REQUEST [as 别名]
def post(self, key_name): # pylint: disable=g-bad-name
"""Post handler for a single API key."""
value = self.request.get('value', None)
if value is None:
self.abort(httplib.BAD_REQUEST, explanation='No value provided')
if key_name == 'virustotal':
singleton.VirusTotalApiAuth.SetInstance(api_key=value)
elif key_name == 'bit9':
singleton.Bit9ApiAuth.SetInstance(api_key=value)
else:
self.abort(httplib.BAD_REQUEST, explanation='Invalid key name')
# The Webapp2 routes defined for these handlers.
示例11: _GetVoteWeight
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BAD_REQUEST [as 别名]
def _GetVoteWeight(self, role):
if not role:
return self.user.vote_weight
role_weights = settings.VOTING_WEIGHTS
vote_weight = role_weights.get(role)
if vote_weight is None:
self.abort(
httplib.BAD_REQUEST,
explanation='Invalid role provided: %s' % role)
valid_access = role in self.user.roles or self.user.is_admin
if not valid_access:
self.abort(
httplib.FORBIDDEN,
explanation='User "%s" does not have role: %s' % (
self.user.nickname, role))
return vote_weight
示例12: get
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BAD_REQUEST [as 别名]
def get(self, platform, blockable_type):
normalized_platform = platform.lower()
normalized_blockable_type = blockable_type.lower()
# Set the target Model to query against based on the URL arguments.
platform_map = _MODEL_MAP.get(normalized_platform)
if not platform_map:
self.abort(
httplib.BAD_REQUEST, 'Unknown platform: %s' % normalized_platform)
elif normalized_blockable_type not in platform_map:
self.abort(
httplib.BAD_REQUEST,
'Unknown Blockable type: %s' % normalized_blockable_type)
blockable_class = platform_map.get(normalized_blockable_type)
if not blockable_class:
self.abort(
httplib.BAD_REQUEST,
'Unsupported platform-type pair: %s, %s' % (
normalized_platform, normalized_blockable_type))
BlockableQueryHandler.MODEL_CLASS = blockable_class
# With target Model class set, trigger the query execution.
self._Query()
示例13: post
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BAD_REQUEST [as 别名]
def post(self, blockable_id):
blockable_id = blockable_id.lower()
blockable = binary_models.Blockable.get_by_id(blockable_id)
if not blockable:
self.abort(httplib.NOT_FOUND, explanation='Blockable not found.')
elif blockable.GetPlatformName() != constants.PLATFORM.WINDOWS:
self.abort(httplib.BAD_REQUEST, explanation='Must be a Bit9 blockable')
elif not isinstance(blockable, binary_models.Binary):
self.abort(httplib.BAD_REQUEST, explanation='Must be a Binary')
force_installer = self.request.get('value', None)
if force_installer is None:
self.abort(httplib.BAD_REQUEST, explanation='No installer state provided')
new_policy = (
constants.RULE_POLICY.FORCE_INSTALLER
if force_installer.lower() == 'true'
else constants.RULE_POLICY.FORCE_NOT_INSTALLER)
new_installer_state = self._SetInstallerPolicy(blockable_id, new_policy)
self.respond_json(new_installer_state)
# The Webapp2 routes defined for these handlers.
示例14: user_databases
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BAD_REQUEST [as 别名]
def user_databases(user=None):
if request.method == 'GET':
user_layers = [{'name': user_db_info.database.name,
'username': user_db_info.username,
'_id': user_db_info.database.id} for user_db_info in user.databases]
return user_layers, httplib.OK
else:
if not isinstance(request.json, dict) or 'database' not in request.json or 'action' not in request.args:
return None, httplib.BAD_REQUEST
action = request.args['action']
database_info = DatabaseInfo.objects.with_id(request.json.pop('database'))
if database_info is None:
return None, httplib.BAD_REQUEST
if action == 'remove':
status = user.remove_layer(database_info.id)
return status, (httplib.OK if status else httplib.BAD_REQUEST)
elif action == 'add' and database_info.id:
user_db_info = database_info.add_user(**request.json)
# TODO! handle nicely
try:
user_db_info.login()
user.add_layer(user_db_info)
return True, httplib.OK
except utils.AuthenticationError:
return {'error': 'login'}, httplib.BAD_REQUEST
else:
return {}, httplib.BAD_REQUEST
示例15: all_sessions
# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import BAD_REQUEST [as 别名]
def all_sessions(user=None):
""" :type user: User """
if request.method == 'GET':
query = {}
if 'name' in request.args:
query['name'] = request.args['name']
sessions = Session.objects(**query).order_by('name')
return sessions, httplib.OK
elif request.method == 'POST':
if 'clone' in request.args:
original = Session.objects.with_id(request.args.get('clone'))
original_id = original.id
if original is None:
return {'error': 'source session could not be found'}, httplib.BAD_REQUEST
session = original
session.id = None
session.name = request.json['name']
session.save(validate=True)
# Clone over all of the data model events
DataModelEvent.objects(sessions=original_id).update(add_to_set__sessions=session.id)
for result in AnalyticResult.objects(session=original_id):
result.id = None
result.session = session
result.uuid = result.get_uuid()
result.save()
else:
info = request.json
if info.get('range') is not None and info.get('name') is not None:
time_range = DateRange.get_range(info['range'])
session = Session(range=time_range, name=info['name'])
session.save(validate=True)
return session.id, httplib.OK