DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Mistakes That Django Developers Make and How To Avoid Them
  • Spring Microservice Tip: Abstracting the Database Hostname With Environment Variable
  • How To Build a Simple GitHub Action To Deploy a Django Application to the Cloud
  • Spring Microservice Application Resilience: The Role of @Transactional in Preventing Connection Leaks

Trending

  • How Large Tech Companies Architect Resilient Systems for Millions of Users
  • Navigating Double and Triple Extortion Tactics
  • Designing for Sustainability: The Rise of Green Software
  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  1. DZone
  2. Data Engineering
  3. Data
  4. Resetting the Database Connection in Django

Resetting the Database Connection in Django

By 
Chase Seibert user avatar
Chase Seibert
·
Mar. 09, 12 · Interview
Likes (0)
Comment
Save
Tweet
Share
8.9K Views

Join the DZone community and get the full member experience.

Join For Free

Django handles database connections transparently in almost all cases. It will start a new connection when your request starts up, and commit it at the end of the request lifetime. Other times you need to dive in further and do your own granular transaction management. But for the most part, it's fully automatic.

However, sometimes your use case may require that you close the current database connection and open a new one. While this is possible in Django, it's not well documented.

Why would you want to do this? I my case, I was writing an automation test framework. Some of the automation tests make database calls through the Django ORM to setup records, clean up after the test, etc. Each test is executed in the same process space, via a thread pool. We found that if one of the early tests threw an unrecoverable database error, such as an IntegrityError due to violating a unique constraint, the database connection would be aborted. Subsequent tests that tried to use the database would raise a DatabaseError:

Traceback (most recent call last):
  File /home/user/project/app/test.py, line 73, in tearDown
    MyModel.objects.all()
  File /usr/local/lib/python2.6/dist-packages/django/db/models/query.py, line 444, in delete
    collector.collect(del_query)
  File /usr/local/lib/python2.6/dist-packages/django/db/models/deletion.py, line 146, in collect
    reverse_dependency=reverse_dependency)
  File /usr/local/lib/python2.6/dist-packages/django/db/models/deletion.py, line 91, in add
    if not objs:
  File /usr/local/lib/python2.6/dist-packages/django/db/models/query.py, line 113, in __nonzero__
    iter(self).next()
  File /usr/local/lib/python2.6/dist-packages/django/db/models/query.py, line 107, in _result_iter
    self._fill_cache()
  File /usr/local/lib/python2.6/dist-packages/django/db/models/query.py, line 772, in _fill_cache
    self._result_cache.append(self._iter.next())
  File /usr/local/lib/python2.6/dist-packages/django/db/models/query.py, line 273, in iterator
    for row in compiler.results_iter():
  File /usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py, line 680, in results_iter
    for rows in self.execute_sql(MULTI):
  File /usr/local/lib/python2.6/dist-packages/django/db/models/sql/compiler.py, line 735, in execute_sql
    cursor.execute(sql, params)
  File /usr/local/lib/python2.6/dist-packages/django/db/backends/postgresql_psycopg2/base.py, line 44, in execute
    return self.cursor.execute(query, args)
DatabaseError: server closed the connection unexpectedly
 This probably means the server terminated abnormally
 before or while processing the request.


It turns out that it's relatively easy to reset the database connection. We just called the following function at the start of every test. Django is smart enough to re-initialize the connection the next time it's used, assuming that it's disconnected properly.

def reset_database_connection():
    from django import db
    db.close_connection()


Database connection Django (web framework)

Published at DZone with permission of Chase Seibert, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Mistakes That Django Developers Make and How To Avoid Them
  • Spring Microservice Tip: Abstracting the Database Hostname With Environment Variable
  • How To Build a Simple GitHub Action To Deploy a Django Application to the Cloud
  • Spring Microservice Application Resilience: The Role of @Transactional in Preventing Connection Leaks

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!