|
| 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 | +import pymongo |
| 36 | + |
| 37 | +if pymongo.version_tuple >= (3, 5, 0): |
| 38 | + from bson.json_util import RELAXED_JSON_OPTIONS |
| 39 | + DEFAULT_JSON_OPTIONS = RELAXED_JSON_OPTIONS |
| 40 | +else: |
| 41 | + DEFAULT_JSON_OPTIONS = None |
| 42 | + |
| 43 | + |
| 44 | +def _iteritems(obj): |
| 45 | + if hasattr(obj, "iteritems"): |
| 46 | + return obj.iteritems() |
| 47 | + elif hasattr(obj, "items"): |
| 48 | + return obj.items() |
| 49 | + else: |
| 50 | + raise TypeError("{!r} missing iteritems() and items()".format(obj)) |
| 51 | + |
| 52 | + |
| 53 | +class BSONObjectIdConverter(BaseConverter): |
| 54 | + |
| 55 | + """A simple converter for the RESTful URL routing system of Flask. |
| 56 | +
|
| 57 | + .. code-block:: python |
| 58 | +
|
| 59 | + @app.route("/<ObjectId:task_id>") |
| 60 | + def show_task(task_id): |
| 61 | + task = mongo.db.tasks.find_one_or_404(task_id) |
| 62 | + return render_template("task.html", task=task) |
| 63 | +
|
| 64 | + Valid object ID strings are converted into |
| 65 | + :class:`~bson.objectid.ObjectId` objects; invalid strings result |
| 66 | + in a 404 error. The converter is automatically registered by the |
| 67 | + initialization of :class:`~flask_pymongo.PyMongo` with keyword |
| 68 | + :attr:`ObjectId`. |
| 69 | +
|
| 70 | + The :class:`~flask_pymongo.helpers.BSONObjectIdConverter` is |
| 71 | + automatically installed on the :class:`~flask_pymongo.PyMongo` |
| 72 | + instnace at creation time. |
| 73 | +
|
| 74 | + """ |
| 75 | + |
| 76 | + def to_python(self, value): |
| 77 | + try: |
| 78 | + return ObjectId(value) |
| 79 | + except InvalidId: |
| 80 | + raise abort(404) |
| 81 | + |
| 82 | + def to_url(self, value): |
| 83 | + return str(value) |
| 84 | + |
| 85 | + |
| 86 | +class JSONEncoder(flask_json.JSONEncoder): |
| 87 | + |
| 88 | + """A JSON encoder that uses :mod:`bson.json_util` for MongoDB documents. |
| 89 | +
|
| 90 | + .. code-block:: python |
| 91 | +
|
| 92 | + @app.route("/cart/<ObjectId:cart_id>") |
| 93 | + def json_route(cart_id): |
| 94 | + results = mongo.db.carts.find({"_id": cart_id}) |
| 95 | + return jsonify(results) |
| 96 | +
|
| 97 | + # returns a Response with JSON body and application/json content-type: |
| 98 | + # '[{"count":12,"item":"egg"},{"count":1,"item":"apple"}]' |
| 99 | +
|
| 100 | + Since this uses PyMongo's JSON tools, certain types may serialize |
| 101 | + differently than you expect. See :class:`~bson.json_util.JSONOptions` |
| 102 | + for details on the particular serialization that will be used. |
| 103 | +
|
| 104 | + A :class:`~flask_pymongo.helpers.JSONEncoder` is automatically |
| 105 | + automatically installed on the :class:`~flask_pymongo.PyMongo` |
| 106 | + instance at creation time, using |
| 107 | + :const:`~bson.json_util.RELAXED_JSON_OPTIONS`. You can change the |
| 108 | + :class:`~bson.json_util.JSONOptions` in use by passing |
| 109 | + ``json_options`` to the :class:`~flask_pymongo.PyMongo` |
| 110 | + constructor. |
| 111 | +
|
| 112 | + .. note:: |
| 113 | +
|
| 114 | + :class:`~bson.json_util.JSONOptions` is only supported as of |
| 115 | + PyMongo version 3.4. For older versions of PyMongo, you will |
| 116 | + have less control over the JSON format that results from calls |
| 117 | + to :func:`~flask.json.jsonify`. |
| 118 | +
|
| 119 | + .. versionadded:: 2.4.0 |
| 120 | +
|
| 121 | + """ |
| 122 | + |
| 123 | + def __init__(self, json_options, *args, **kwargs): |
| 124 | + if json_options is None: |
| 125 | + json_options = DEFAULT_JSON_OPTIONS |
| 126 | + if json_options is not None: |
| 127 | + self._default_kwargs = {"json_options": json_options} |
| 128 | + else: |
| 129 | + self._default_kwargs = {} |
| 130 | + |
| 131 | + super(JSONEncoder, self).__init__(*args, **kwargs) |
| 132 | + |
| 133 | + def default(self, obj): |
| 134 | + """Serialize MongoDB object types using :mod:`bson.json_util`. |
| 135 | +
|
| 136 | + Falls back to Flask's default JSON serialization for all other types. |
| 137 | +
|
| 138 | + This may raise ``TypeError`` for object types not recignozed. |
| 139 | +
|
| 140 | + .. versionadded:: 2.4.0 |
| 141 | +
|
| 142 | + """ |
| 143 | + if hasattr(obj, "iteritems") or hasattr(obj, "items"): |
| 144 | + return SON((k, self.default(v)) for k, v in iteritems(obj)) |
| 145 | + elif hasattr(obj, "__iter__") and not isinstance(obj, string_types): |
| 146 | + return [self.default(v) for v in obj] |
| 147 | + else: |
| 148 | + try: |
| 149 | + return json_util.default(obj, **self._default_kwargs) |
| 150 | + except TypeError: |
| 151 | + # PyMongo couldn't convert into a serializable object, and |
| 152 | + # the Flask default JSONEncoder won't; so we return the |
| 153 | + # object itself and let stdlib json handle it if possible |
| 154 | + return obj |
0 commit comments