|
| 1 | +# Copyright (c) 2011-2019, Dan Crosta |
| 2 | +# All rights reserved. |
| 3 | +# |
| 4 | +# Redistribution and use in source and binary forms, with or without |
| 5 | +# modification, are permitted provided that the following conditions are met: |
| 6 | +# |
| 7 | +# * Redistributions of source code must retain the above copyright notice, |
| 8 | +# this list of conditions and the following disclaimer. |
| 9 | +# |
| 10 | +# * Redistributions in binary form must reproduce the above copyright notice, |
| 11 | +# this list of conditions and the following disclaimer in the documentation |
| 12 | +# and/or other materials provided with the distribution. |
| 13 | +# |
| 14 | +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
| 15 | +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
| 16 | +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| 17 | +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE |
| 18 | +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR |
| 19 | +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF |
| 20 | +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS |
| 21 | +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN |
| 22 | +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) |
| 23 | +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
| 24 | +# POSSIBILITY OF SUCH DAMAGE. |
| 25 | + |
| 26 | + |
| 27 | +__all__ = ("BSONObjectIdConverter", "JSONEncoder") |
| 28 | + |
| 29 | +from bson import json_util, SON |
| 30 | +from bson.errors import InvalidId |
| 31 | +from bson.objectid import ObjectId |
| 32 | +from flask import abort, json as flask_json |
| 33 | +from six import iteritems, string_types |
| 34 | +from werkzeug.routing import BaseConverter |
| 35 | + |
| 36 | + |
| 37 | +def _iteritems(obj): |
| 38 | + if hasattr(obj, "iteritems"): |
| 39 | + return obj.iteritems() |
| 40 | + elif hasattr(obj, "items"): |
| 41 | + return obj.items() |
| 42 | + else: |
| 43 | + raise TypeError("{!r} missing iteritems() and items()".format(obj)) |
| 44 | + |
| 45 | + |
| 46 | +class BSONObjectIdConverter(BaseConverter): |
| 47 | + |
| 48 | + """A simple converter for the RESTful URL routing system of Flask. |
| 49 | +
|
| 50 | + .. code-block:: python |
| 51 | +
|
| 52 | + @app.route("/<ObjectId:task_id>") |
| 53 | + def show_task(task_id): |
| 54 | + task = mongo.db.tasks.find_one_or_404(task_id) |
| 55 | + return render_template("task.html", task=task) |
| 56 | +
|
| 57 | + Valid object ID strings are converted into |
| 58 | + :class:`~bson.objectid.ObjectId` objects; invalid strings result |
| 59 | + in a 404 error. The converter is automatically registered by the |
| 60 | + initialization of :class:`~flask_pymongo.PyMongo` with keyword |
| 61 | + :attr:`ObjectId`. |
| 62 | +
|
| 63 | + """ |
| 64 | + |
| 65 | + def to_python(self, value): |
| 66 | + try: |
| 67 | + return ObjectId(value) |
| 68 | + except InvalidId: |
| 69 | + raise abort(404) |
| 70 | + |
| 71 | + def to_url(self, value): |
| 72 | + return str(value) |
| 73 | + |
| 74 | + |
| 75 | +class JSONEncoder(flask_json.JSONEncoder): |
| 76 | + |
| 77 | + """A JSON encoder that uses :mod:`bson.json_util` for MongoDB documents. |
| 78 | +
|
| 79 | + .. code-block:: python |
| 80 | +
|
| 81 | + @app.route("/cart/<ObjectId:cart_id>") |
| 82 | + def json_route(cart_id): |
| 83 | + results = mongo.db.carts.find({"_id": cart_id}) |
| 84 | + return jsonify(results) |
| 85 | +
|
| 86 | + # returns a Response with body content: |
| 87 | + # '[{"count":12,"item":"egg"},{"count":1,"item":"apple"}]\\n' |
| 88 | +
|
| 89 | + .. note:: |
| 90 | +
|
| 91 | + Since this uses PyMongo's JSON tools, certain types may |
| 92 | + serialize differently than you expect. See |
| 93 | + :class:`~bson.json_util.JSONOptions` for details on the |
| 94 | + particular serialization that will be used. |
| 95 | +
|
| 96 | + """ |
| 97 | + |
| 98 | + def __init__(self, json_options, *args, **kwargs): |
| 99 | + self._json_options = json_options |
| 100 | + super(JSONEncoder, self).__init__(*args, **kwargs) |
| 101 | + |
| 102 | + def default(self, obj): |
| 103 | + """Serialize MongoDB object types using :mod:`bson.json_util`. |
| 104 | +
|
| 105 | + Falls back to Flask's default JSON serialization for all other types. |
| 106 | +
|
| 107 | + This may raise ``TypeError`` for object types not recignozed. |
| 108 | +
|
| 109 | + .. versionadded:: 2.4.0 |
| 110 | +
|
| 111 | + """ |
| 112 | + if hasattr(obj, "iteritems") or hasattr(obj, "items"): |
| 113 | + return SON((k, self.default(v)) for k, v in iteritems(obj)) |
| 114 | + elif hasattr(obj, "__iter__") and not isinstance(obj, string_types): |
| 115 | + return [self.default(v) for v in obj] |
| 116 | + else: |
| 117 | + try: |
| 118 | + return json_util.default(obj) |
| 119 | + except TypeError: |
| 120 | + # PyMongo couldn't convert into a serializable object, and |
| 121 | + # the Flask default JSONEncoder won't; so we return the |
| 122 | + # object itself and let stdlib json handle it if possible |
| 123 | + return obj |
0 commit comments