Fixed #8867: Corrected a couple typos in the signals documentation
[django.git] / django / db / __init__.py
blobd15fd3238e1a066c252c9994782d4d5e526dfd01
1 import os
2 from django.conf import settings
3 from django.core import signals
4 from django.core.exceptions import ImproperlyConfigured
5 from django.utils.functional import curry
7 __all__ = ('backend', 'connection', 'DatabaseError', 'IntegrityError')
9 if not settings.DATABASE_ENGINE:
10 settings.DATABASE_ENGINE = 'dummy'
12 try:
13 # Most of the time, the database backend will be one of the official
14 # backends that ships with Django, so look there first.
15 _import_path = 'django.db.backends.'
16 backend = __import__('%s%s.base' % (_import_path, settings.DATABASE_ENGINE), {}, {}, [''])
17 except ImportError, e:
18 # If the import failed, we might be looking for a database backend
19 # distributed external to Django. So we'll try that next.
20 try:
21 _import_path = ''
22 backend = __import__('%s.base' % settings.DATABASE_ENGINE, {}, {}, [''])
23 except ImportError, e_user:
24 # The database backend wasn't found. Display a helpful error message
25 # listing all possible (built-in) database backends.
26 backend_dir = os.path.join(__path__[0], 'backends')
27 try:
28 available_backends = [f for f in os.listdir(backend_dir) if not f.startswith('_') and not f.startswith('.') and not f.endswith('.py') and not f.endswith('.pyc')]
29 except EnvironmentError:
30 available_backends = []
31 available_backends.sort()
32 if settings.DATABASE_ENGINE not in available_backends:
33 raise ImproperlyConfigured, "%r isn't an available database backend. Available options are: %s\nError was: %s" % \
34 (settings.DATABASE_ENGINE, ", ".join(map(repr, available_backends)), e_user)
35 else:
36 raise # If there's some other error, this must be an error in Django itself.
38 # Convenient aliases for backend bits.
39 connection = backend.DatabaseWrapper(**settings.DATABASE_OPTIONS)
40 DatabaseError = backend.DatabaseError
41 IntegrityError = backend.IntegrityError
43 # Register an event that closes the database connection
44 # when a Django request is finished.
45 def close_connection(**kwargs):
46 connection.close()
47 signals.request_finished.connect(close_connection)
49 # Register an event that resets connection.queries
50 # when a Django request is started.
51 def reset_queries(**kwargs):
52 connection.queries = []
53 signals.request_started.connect(reset_queries)
55 # Register an event that rolls back the connection
56 # when a Django request has an exception.
57 def _rollback_on_exception(**kwargs):
58 from django.db import transaction
59 try:
60 transaction.rollback_unless_managed()
61 except DatabaseError:
62 pass
63 signals.got_request_exception.connect(_rollback_on_exception)