本文整理汇总了Python中eve.utils.debug_error_message函数的典型用法代码示例。如果您正苦于以下问题:Python debug_error_message函数的具体用法?Python debug_error_message怎么用?Python debug_error_message使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了debug_error_message函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: payload
def payload():
""" Performs sanity checks or decoding depending on the Content-Type,
then returns the request payload as a dict. If request Content-Type is
unsupported, aborts with a 400 (Bad Request).
.. versionchanged:: 0.1.1
Payload returned as a standard python dict regardless of request content
type.
.. versionchanged:: 0.0.9
More informative error messages.
request.get_json() replaces the now deprecated request.json
.. versionchanged:: 0.0.7
Native Flask request.json preferred over json.loads.
.. versionadded: 0.0.5
"""
content_type = request.headers['Content-Type'].split(';')[0]
if content_type == 'application/json':
return request.get_json()
elif content_type == 'application/x-www-form-urlencoded':
return request.form.to_dict() if len(request.form) else \
abort(400, description=debug_error_message(
'No form-urlencoded data supplied'
))
else:
abort(400, description=debug_error_message(
'Unknown or no Content-Type header supplied'))
示例2: test_debug_error_message
def test_debug_error_message(self):
with self.app.test_request_context():
self.app.config['DEBUG'] = False
self.assertEqual(debug_error_message('An error message'), None)
self.app.config['DEBUG'] = True
self.assertEqual(debug_error_message('An error message'),
'An error message')
示例3: _resolve_embedded_documents
def _resolve_embedded_documents(resource, req, documents):
"""Loops through the documents, adding embedded representations
of any fields that are (1) defined eligible for embedding in the
DOMAIN and (2) requested to be embedded in the current `req`
Currently we only support a single layer of embedding,
i.e. /invoices/?embedded={"user":1}
*NOT* /invoices/?embedded={"user.friends":1}
:param resource: the resource name.
:param req: and instace of :class:`eve.utils.ParsedRequest`.
:param documents: list of documents returned by the query.
.. versonchanged:: 0.1.1
'collection' key has been renamed to 'resource' (data_relation).
.. versionadded:: 0.1.0
"""
if req.embedded:
# Parse the embedded clause, we are expecting
# something like: '{"user":1}'
try:
client_embedding = json.loads(req.embedded)
except ValueError:
abort(400, description=debug_error_message(
'Unable to parse `embedded` clause'
))
# Build the list of fields where embedding is being requested
try:
embedded_fields = [k for k, v in client_embedding.items()
if v == 1]
except AttributeError:
# We got something other than a dict
abort(400, description=debug_error_message(
'Unable to parse `embedded` clause'
))
# For each field, is the field allowed to be embedded?
# Pick out fields that have a `data_relation` where `embeddable=True`
enabled_embedded_fields = []
for field in embedded_fields:
# Reject bogus field names
if field in config.DOMAIN[resource]['schema']:
field_definition = config.DOMAIN[resource]['schema'][field]
if 'data_relation' in field_definition and \
field_definition['data_relation'].get('embeddable'):
# or could raise 400 here
enabled_embedded_fields.append(field)
for document in documents:
for field in enabled_embedded_fields:
field_definition = config.DOMAIN[resource]['schema'][field]
# Retrieve and serialize the requested document
embedded_doc = app.data.find_one(
field_definition['data_relation']['resource'],
**{config.ID_FIELD: document[field]}
)
if embedded_doc:
document[field] = embedded_doc
示例4: insert
def insert(self, resource, doc_or_docs):
""" Inserts a document into a resource collection.
.. versionchanged:: 0.0.9
More informative error messages.
.. versionchanged:: 0.0.8
'write_concern' support.
.. versionchanged:: 0.0.6
projection queries ('?projection={"name": 1}')
'document' param renamed to 'doc_or_docs', making support for bulk
inserts apparent.
.. versionchanged:: 0.0.4
retrieves the target collection via the new config.SOURCES helper.
"""
datasource, _, _, _ = self._datasource_ex(resource)
try:
return self.driver.db[datasource].insert(doc_or_docs,
**self._wc(resource))
except pymongo.errors.InvalidOperation as e:
abort(500, description=debug_error_message(
'pymongo.errors.InvalidOperation: %s' % e
))
except pymongo.errors.OperationFailure as e:
# most likely a 'w' (write_concern) setting which needs an
# existing ReplicaSet which doesn't exist. Please note that the
# update will actually succeed (a new ETag will be needed).
abort(500, description=debug_error_message(
'pymongo.errors.OperationFailure: %s' % e
))
示例5: test_debug_error_message
def test_debug_error_message(self):
with self.app.test_request_context():
self.app.config["DEBUG"] = False
self.assertEqual(debug_error_message("An error message"), None)
self.app.config["DEBUG"] = True
self.assertEqual(
debug_error_message("An error message"), "An error message"
)
示例6: insert
def insert(self, resource, doc_or_docs):
""" Inserts a document into a resource collection.
.. versionchanged:: 0.6.1
Support for PyMongo 3.0.
.. versionchanged:: 0.6
Support for multiple databases.
.. versionchanged:: 0.0.9
More informative error messages.
.. versionchanged:: 0.0.8
'write_concern' support.
.. versionchanged:: 0.0.6
projection queries ('?projection={"name": 1}')
'document' param renamed to 'doc_or_docs', making support for bulk
inserts apparent.
.. versionchanged:: 0.0.4
retrieves the target collection via the new config.SOURCES helper.
"""
datasource, _, _, _ = self._datasource_ex(resource)
coll = self.get_collection_with_write_concern(datasource, resource)
if isinstance(doc_or_docs, dict):
doc_or_docs = [doc_or_docs]
try:
return coll.insert_many(doc_or_docs, ordered=True).inserted_ids
except pymongo.errors.BulkWriteError as e:
self.app.logger.exception(e)
# since this is an ordered bulk operation, all remaining inserts
# are aborted. Be aware that if BULK_ENABLED is True and more than
# one document is included with the payload, some documents might
# have been successfully inserted, even if the operation was
# aborted.
# report a duplicate key error since this can probably be
# handled by the client.
for error in e.details['writeErrors']:
# amazingly enough, pymongo does not appear to be exposing
# error codes as constants.
if error['code'] == 11000:
abort(409, description=debug_error_message(
'Duplicate key error at index: %s, message: %s' % (
error['index'], error['errmsg'])
))
abort(500, description=debug_error_message(
'pymongo.errors.BulkWriteError: %s' % e
))
示例7: _change_request
def _change_request(self, resource, id_, changes, original, replace=False):
""" Performs a change, be it a replace or update.
.. versionchanged:: 0.6.1
Support for PyMongo 3.0.
.. versionchanged:: 0.6
Return 400 if an attempt is made to update/replace an immutable
field.
"""
id_field = config.DOMAIN[resource]['id_field']
query = {id_field: id_}
if config.ETAG in original:
query[config.ETAG] = original[config.ETAG]
datasource, filter_, _, _ = self._datasource_ex(
resource, query)
coll = self.get_collection_with_write_concern(datasource, resource)
try:
result = coll.replace_one(filter_, changes) if replace else \
coll.update_one(filter_, changes)
if result and result.acknowledged and result.modified_count == 0:
raise self.OriginalChangedError()
except pymongo.errors.DuplicateKeyError as e:
abort(400, description=debug_error_message(
'pymongo.errors.DuplicateKeyError: %s' % e
))
except pymongo.errors.OperationFailure as e:
# server error codes and messages changed between 2.4 and 2.6/3.0.
server_version = \
self.driver.db.client.server_info()['version'][:3]
if (
(server_version == '2.4' and e.code in (13596, 10148)) or
(server_version in ('2.6', '3.0') and e.code in (66, 16837))
):
# attempt to update an immutable field. this usually
# happens when a PATCH or PUT includes a mismatching ID_FIELD.
self.app.logger.warn(e)
description = debug_error_message(
'pymongo.errors.OperationFailure: %s' % e) or \
"Attempt to update an immutable field. Usually happens " \
"when PATCH or PUT include a '%s' field, " \
"which is immutable (PUT can include it as long as " \
"it is unchanged)." % id_field
abort(400, description=description)
else:
# see comment in :func:`insert()`.
self.app.logger.exception(e)
abort(500, description=debug_error_message(
'pymongo.errors.OperationFailure: %s' % e
))
示例8: process_login
def process_login(items):
"""Hook to add token on POST to /sessions.
Attempts to first login via LDAP (if enabled), then login via database.
If the login is successful, the fields "username" and "password" are
removed and the fields "user" and "token" are added, which will be stored
in the db.
If the login is unsuccessful, abort(401)
Args:
items (list): List of items as passed by EVE to post hooks.
"""
for item in items:
username = item['username']
password = item['password']
# LDAP
if (app.config.get('ldap_connector') and
ldap.authenticate_user(username, password)):
# Success, sync user and get token
updated = ldap.sync_one(username)
_prepare_token(item, updated['_id'])
app.logger.info(
"User '%s' was authenticated with LDAP" % username)
return
# Database, try to find via nethz, mail or objectid
users = app.data.driver.db['users']
lookup = {'$or': [{'nethz': username}, {'email': username}]}
try:
objectid = ObjectId(username)
lookup['$or'].append({'_id': objectid})
except InvalidId:
pass # input can't be used as ObjectId
user = users.find_one(lookup)
if user:
app.logger.debug("User found in db.")
if verify_password(user, item['password']):
app.logger.debug("Login for user '%s' successful." % username)
_prepare_token(item, user['_id'])
return
else:
status = "Login failed: Password does not match!"
app.logger.debug(status)
abort(401, description=debug_error_message(status))
# Abort if everything else fails
status = "Login with db failed: User not found!"
app.logger.debug(status)
abort(401, description=debug_error_message(status))
示例9: resolve_embedded_fields
def resolve_embedded_fields(resource, req):
""" Returns a list of validated embedded fields from the incoming request
or from the resource definition is the request does not specify.
:param resource: the resource name.
:param req: and instace of :class:`eve.utils.ParsedRequest`.
.. versionchanged:: 0.5
Enables subdocuments embedding. #389.
.. versionadded:: 0.4
"""
embedded_fields = []
if req.embedded:
# Parse the embedded clause, we are expecting
# something like: '{"user":1}'
try:
client_embedding = json.loads(req.embedded)
except ValueError:
abort(400, description=debug_error_message(
'Unable to parse `embedded` clause'
))
# Build the list of fields where embedding is being requested
try:
embedded_fields = [k for k, v in client_embedding.items()
if v == 1]
except AttributeError:
# We got something other than a dict
abort(400, description=debug_error_message(
'Unable to parse `embedded` clause'
))
embedded_fields = list(
set(config.DOMAIN[resource]['embedded_fields']) |
set(embedded_fields))
# For each field, is the field allowed to be embedded?
# Pick out fields that have a `data_relation` where `embeddable=True`
enabled_embedded_fields = []
for field in embedded_fields:
# Reject bogus field names
field_def = field_definition(resource, field)
if field_def:
if field_def['type'] == 'list':
field_def = field_def['schema']
if 'data_relation' in field_def and \
field_def['data_relation'].get('embeddable'):
# or could raise 400 here
enabled_embedded_fields.append(field)
return enabled_embedded_fields
示例10: sanitize_keys
def sanitize_keys(spec):
ops = set([op for op in spec.keys() if op[0] == '$'])
unknown = ops - Mongo.operators
if unknown:
abort(400, description=debug_error_message(
'Query contains unknown or unsupported operators: %s' %
', '.join(unknown)
))
if set(spec.keys()) & set(config.MONGO_QUERY_BLACKLIST):
abort(400, description=debug_error_message(
'Query contains operators banned in MONGO_QUERY_BLACKLIST'
))
示例11: payload
def payload():
""" Performs sanity checks or decoding depending on the Content-Type,
then returns the request payload as a dict. If request Content-Type is
unsupported, aborts with a 400 (Bad Request).
.. versionchanged:: 0.3
Allow 'multipart/form-data' content type.
.. versionchanged:: 0.1.1
Payload returned as a standard python dict regardless of request content
type.
.. versionchanged:: 0.0.9
More informative error messages.
request.get_json() replaces the now deprecated request.json
.. versionchanged:: 0.0.7
Native Flask request.json preferred over json.loads.
.. versionadded: 0.0.5
"""
content_type = request.headers['Content-Type'].split(';')[0]
if content_type == 'application/json':
return request.get_json()
elif content_type == 'application/x-www-form-urlencoded':
return request.form.to_dict() if len(request.form) else \
abort(400, description=debug_error_message(
'No form-urlencoded data supplied'
))
elif content_type == 'multipart/form-data':
# as multipart is also used for file uploads, we let an empty
# request.form go through as long as there are also files in the
# request.
if len(request.form) or len(request.files):
# merge form fields and request files, so we get a single payload
# to be validated against the resource schema.
# list() is needed because Python3 items() returns a dict_view, not
# a list as in Python2.
return dict(list(request.form.to_dict().items()) +
list(request.files.to_dict().items()))
else:
abort(400, description=debug_error_message(
'No multipart/form-data supplied'
))
else:
abort(400, description=debug_error_message(
'Unknown or no Content-Type header supplied'))
示例12: insert
def insert(self, resource, doc_or_docs):
""" Inserts a document into a resource collection.
.. versionchanged:: 0.6.1
Support for PyMongo 3.0.
.. versionchanged:: 0.6
Support for multiple databases.
.. versionchanged:: 0.0.9
More informative error messages.
.. versionchanged:: 0.0.8
'write_concern' support.
.. versionchanged:: 0.0.6
projection queries ('?projection={"name": 1}')
'document' param renamed to 'doc_or_docs', making support for bulk
inserts apparent.
.. versionchanged:: 0.0.4
retrieves the target collection via the new config.SOURCES helper.
"""
datasource, _, _, _ = self._datasource_ex(resource)
coll = self.get_collection_with_write_concern(datasource, resource)
if isinstance(doc_or_docs, dict):
doc_or_docs = [doc_or_docs]
try:
return coll.insert_many(doc_or_docs).inserted_ids
except pymongo.errors.DuplicateKeyError as e:
abort(409, description=debug_error_message(
'pymongo.errors.DuplicateKeyError: %s' % e
))
except pymongo.errors.InvalidOperation as e:
self.app.logger.exception(e)
abort(500, description=debug_error_message(
'pymongo.errors.InvalidOperation: %s' % e
))
except pymongo.errors.OperationFailure as e:
# most likely a 'w' (write_concern) setting which needs an
# existing ReplicaSet which doesn't exist. Please note that the
# update will actually succeed (a new ETag will be needed).
self.app.logger.exception(e)
abort(500, description=debug_error_message(
'pymongo.errors.OperationFailure: %s' % e
))
示例13: get_document
def get_document(resource, concurrency_check, **lookup):
""" Retrieves and return a single document. Since this function is used by
the editing methods (POST, PATCH, DELETE), we make sure that the client
request references the current representation of the document before
returning it. However, this concurrency control may be turned off by
internal functions.
:param resource: the name of the resource to which the document belongs to.
:param concurrency_check: boolean check for concurrency control
:param **lookup: document lookup query
.. versionchanged:: 0.5
Concurrency control optional for internal functions.
ETAG are now stored with the document (#369).
.. versionchanged:: 0.0.9
More informative error messages.
.. versionchanged:: 0.0.5
Pass current resource to ``parse_request``, allowing for proper
processing of new configuration settings: `filters`, `sorting`, `paging`.
"""
req = parse_request(resource)
document = app.data.find_one(resource, None, **lookup)
if document:
if not req.if_match and config.IF_MATCH and concurrency_check:
# we don't allow editing unless the client provides an etag
# for the document
abort(403, description=debug_error_message(
'An etag must be provided to edit a document'
))
# ensure the retrieved document has LAST_UPDATED and DATE_CREATED,
# eventually with same default values as in GET.
document[config.LAST_UPDATED] = last_updated(document)
document[config.DATE_CREATED] = date_created(document)
if req.if_match and concurrency_check:
etag = document.get(config.ETAG, document_etag(document))
if req.if_match != etag:
# client and server etags must match, or we don't allow editing
# (ensures that client's version of the document is up to date)
abort(412, description=debug_error_message(
'Client and server etags don\'t match'
))
return document
示例14: aggregate
def aggregate(self, resource, req):
client_projection = {}
spec = {}
if req.where:
try:
spec = self._sanitize(
self._jsondatetime(json.loads(req.where, object_hook=json_util.object_hook)))
except:
try:
spec = parse(req.where)
except ParseError:
abort(400, description=debug_error_message(
'Unable to parse `where` clause'
))
bad_filter = validate_filters(spec, resource)
if bad_filter:
abort(400, bad_filter)
if req.projection:
try:
client_projection = json.loads(req.projection)
except:
abort(400, description=debug_error_message(
'Unable to parse `projection` clause'
))
datasource, spec, projection = self._datasource_ex(resource, spec,
client_projection)
groupers = config.DOMAIN[resource]["default_groupers"]
groupees = config.DOMAIN[resource]["default_groupees"]
group_val = {}
group_val["_id"] = {g: "$%s" % g for g in groupers}
for group_info in groupees:
name = group_info["name"]
group_type = group_info["type"]
group_val[name] = {"$%s" % group_type: "$%s" % name}
pipeline = []
pipeline.append({"$match": spec})
pipeline.append({"$project": projection})
pipeline.append({"$group": group_val})
pipeline.append({"$limit": 1000})
docs = self.driver.db[datasource].aggregate(pipeline)["result"]
cursor = Cursor(docs) #gives required functions to returned result
return cursor
示例15: on_fetched_item_callback
def on_fetched_item_callback(resource, response):
"""Removes `_id` from the fetched document and embeds related
items requested in the `embed` URL query parameter.
Allows multilevel embedding (limited to 3 levels). Nested embedded
relations are separated by dot. Example:
.../organizations/1234567890?embed=["parent", "memberships.person"]
We cannot use Eve's built-in embedded resource serialization
because it handles only entities directly referenced by a field in
the document and replaces that field. However, we need to embed
reverse relations too, e.g. `memberships` in the organization
entity lists all memberships referencing the organization.
Furthermore, unlike the Eve built-in embedding Popolo requires that
referenced items are embedded as a field with different name from
the referencing one (e.g. `organization` vs. `organization_id`) and
allows multilevel embedding.
"""
del response['_id']
if 'embed' in request.args:
try:
embed = json.loads(request.args['embed'])
for path in embed:
_embed_relation(resource, path, response, [(resource, response['id'])])
except:
abort(400, description=debug_error_message('Unable to parse `embed` clause'))