|
| 1 | +# Copyright 2020 Francesco Lombardo <franclombardo@gmail.com> |
| 2 | + |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | + |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | + |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +__all__ = ("FlaskArango") |
| 16 | + |
| 17 | +from arango import ArangoClient |
| 18 | +from flask import current_app, _app_ctx_stack |
| 19 | + |
| 20 | + |
| 21 | +class FlaskArango(object): |
| 22 | + |
| 23 | + """Manages ArangoDB connections for your Flask app. |
| 24 | + FlaskArango objects provide access to ArangoDB MongoDB server via the :attr:`db` |
| 25 | + attribute. You must either pass the :class:`~flask.Flask` |
| 26 | + app to the constructor, or call :meth:`init_app`. |
| 27 | + """ |
| 28 | + |
| 29 | + def __init__(self, app=None): |
| 30 | + if app is not None: |
| 31 | + self.init_app(app) |
| 32 | + |
| 33 | + def init_app(self, app): |
| 34 | + self.app = app |
| 35 | + app.teardown_appcontext(self.teardown) |
| 36 | + |
| 37 | + def connect(self): |
| 38 | + |
| 39 | + host = self.app.config.get("ARANGODB_HOST", None) |
| 40 | + db_name = self.app.config.get("ARANGODB_DB", None) |
| 41 | + db_username = self.app.config.get("ARANGODB_USERNAME", None) |
| 42 | + db_password = self.app.config.get("ARANGODB_PSW", None) |
| 43 | + |
| 44 | + if host is None: |
| 45 | + raise ValueError( |
| 46 | + "You must set the ARANGO_HOST Flask config variable", |
| 47 | + ) |
| 48 | + if db_name is None: |
| 49 | + raise ValueError( |
| 50 | + "You must set the ARANGODB_DB Flask config variable", |
| 51 | + ) |
| 52 | + # Initialize the client for ArangoDB. |
| 53 | + client = ArangoClient(hosts=host) |
| 54 | + # Connect to database. |
| 55 | + return client.db( |
| 56 | + db_name, username=db_username, password=db_password) |
| 57 | + |
| 58 | + def teardown(self, exception): |
| 59 | + ctx = _app_ctx_stack.top |
| 60 | + if hasattr(ctx, 'arango_db'): |
| 61 | + del ctx.arango_db |
| 62 | + |
| 63 | + @property |
| 64 | + def connection(self): |
| 65 | + ctx = _app_ctx_stack.top |
| 66 | + if ctx is not None: |
| 67 | + if not hasattr(ctx, 'arango_db'): |
| 68 | + ctx.arango_db = self.connect() |
| 69 | + return ctx.arango_db |
0 commit comments