Stay organized with collections
Save and categorize content based on your preferences.
Source code for google.appengine.ext.ndb.django_middleware
#
# Copyright 2008 The ndb Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Django middleware for NDB."""
__author__ = 'James A. Morrison'
from . import eventloop, tasklets
[docs]class NdbDjangoMiddleware(object):
"""Django middleware for NDB.
To use NDB with django, add
'ndb.NdbDjangoMiddleware',
to the MIDDLEWARE_CLASSES entry in your Django settings.py file.
Or, if you are using the ndb version from the SDK, use
'google.appengine.ext.ndb.NdbDjangoMiddleware',
It's best to insert it in front of any other middleware classes,
since some other middleware may make datastore calls and those won't be
handled properly if that middleware is invoked before this middleware.
See http://docs.djangoproject.com/en/dev/topics/http/middleware/.
"""
[docs] def process_request(self, unused_request):
"""Called by Django before deciding which view to execute."""
# Compare to the first half of toplevel() in context.py.
tasklets._state.clear_all_pending()
# Create and install a new context.
ctx = tasklets.make_default_context()
tasklets.set_context(ctx)
@staticmethod
def _finish():
# Compare to the finally clause in toplevel() in context.py.
ctx = tasklets.get_context()
tasklets.set_context(None)
ctx.flush().check_success()
eventloop.run() # Ensure writes are flushed, etc.
[docs] def process_response(self, request, response):
"""Called by Django just before returning a response."""
self._finish()
return response
[docs] def process_exception(self, unused_request, unused_exception):
"""Called by Django when a view raises an exception."""
self._finish()
return None
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2025-06-16 UTC.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],["Last updated 2025-06-16 UTC."],[[["This code provides the `NdbDjangoMiddleware` class, which is essential for integrating NDB (a Google App Engine datastore library) with Django web applications."],["To use NDB with Django, the `NdbDjangoMiddleware` or `google.appengine.ext.ndb.NdbDjangoMiddleware` must be added to the `MIDDLEWARE_CLASSES` setting in the Django `settings.py` file."],["The `process_request` method in the middleware clears any pending tasks, creates a new context, and sets this as the active context before a view is executed."],["The `_finish` method, called by `process_response` and `process_exception`, ensures data writes are flushed and the context is cleared, effectively managing data consistency and cleanup."],["It is recommended to place `NdbDjangoMiddleware` at the front of the `MIDDLEWARE_CLASSES` list to ensure that all datastore calls are properly managed."]]],[]]