I am using Django and Postgresql as my DBMS.
I wish to set a setting that enables to enable/disable database connection. When the connection is set to closed (in settings.py) the site will display a message such as "meintanence mode" or something like that. Django will not show any db connection error message (or mail them to admins). It is appreciated if django do not try to connect to the database at all.
Maybe creating a middleware solves your problem. Put your new middleware "maintenancemiddleware" as the FIRST item of your settings.middleware tuple.
# code not tested, only for demonstration.
# maintenancemiddleware.py
from django.conf.settings import MAINTENANCE
class MaintenanceMiddleware(object):
def process_request(self, request):
if MAINTENANCE:
# redirect to a static url (like /media/maintenancemode.html)
Further info: http://docs.djangoproject.com/en/1.2/topics/http/middleware/#topics-http-middleware
Related
I use Django 2.2 and trying to detect if user is still connected when the user close his browser without logging out
I tried to use some Django packages like qsessions but it need to replace 'django.contrib.sessions.middleware.SessionMiddleware', with qsession middleware but it makes another error
django.contrib.sessions.middleware.SessionMiddleware not found
I need your help to get every user session separately.
Django sessions are not meant to be queried for their content. The user id in the session can be decoded from a session, but you need to iterate through all sessions:
from django.contrib.sessions.models import Session
from django.utils import timezone
def get_unexpired_sessions_for_user(user):
user_sessions = []
all_sessions = Session.objects.filter(expire_date__gte=timezone.now())
for session in all_sessions:
session_data = session.get_decoded()
if user.pk == session_data.get('_auth_user_id'):
user_sessions.append(session.pk)
return Session.objects.filter(pk__in=user_sessions)
This approach will work, but will not be performant when you have a lot of sessions in your database.
I have a Django application that is working perfectly. It's connected to a MySQL server hosted on the cloud.
The MySQL server is set to auto-rotate the password every 30 days for security reasons. Django can access the new password only when settings.py is loaded using a custom function I have developed (that will fetch the new password from AWS Secrets Manager).
I'm looking for a way to allow Django to detect if a connection has a problem then update the password all transparent to the user.
Is that possible?
Options I can think of:
You could use a custom middleware that checks the connection before each request.
You could use a cron job that periodically checks for failed database connections, and updates the settings if it finds such a failure.
To check for connections you can use the method django.db.connection.ensure_connection(). If you look at this answer, you could try something like this:
from django.db import connection
from django.db.utils import OperationalError
class Command(BaseCommand):
def handle(self, *args, **options):
try:
# if this succeeds, no further action is needed
connection.ensure_connection()
except OperationalError:
# update the DB password and try again
I'm using PyMongo for a project, what I have found is that all I need is the server name to create, update or delete any entry/collection or even a database. I mean, it doesn't care if I'm authenticated with a username and password with read/write roles. Here's an example:
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.wow
db.wowagain.insert_one({'field':'value'})
My question is:
Is it safe to use Mongodb with python applications, specially with web applications?
I have also tried mongoengine for Django and still I found the same.
You must first enable authentication on the server with --auth and create an administrator account on the server; after that, authentication is enforced.
https://docs.mongodb.com/manual/tutorial/enable-authentication/
I have formulated test cases in Django framework.
Use Case:
I am using API that register user by sending them an Email and when they click on the link provided in the Email their account get activated.
In my settings.py I am using
EMAIL_FILE_PATH ='django.core.mail.backends.filebased.EmailBackend'
which points to the local directory.
When running PyUnit test case from eclipse everything works file. Text file gets generated for each email sent
But, When i am using
python ./manage.py test <component_name>
the files does not generate.
Any insight what is the difference when I execute test case with ./manage.py and when I use pyUnit ?
It's possible to overwrite this aspect in Django if you want to use a specific email backend.
In django.test.utils, Django will change the e-mail backend to locmem as mentioned in the Django Testing documentation when Django sets up the testing environment:
def setup_test_environment():
...
mail.original_email_backend = settings.EMAIL_BACKEND
settings.EMAIL_BACKEND = 'django.core.mail.backends.locmem.EmailBackend'
So if you want to enable sending e-mails for a test, you just need to change the setting to what you want.
from django.test.utils import override_settings
#override_settings(EMAIL_BACKEND='django.core.mail.backends.filebased.EmailBackend')
class MyTest(TestCase):
# your test case
The simple answer:
You can't do this without engineering your own email system, but that would probably be silly. I would suggest doing something else to verify that the code was successful without requiring the email to be sent. Like, run the code, assume the user clicks the link and create RequestFactory to get/post the link to run the view code associated with it.
From the Django Testing Application:
Email services
"If any of your Django views send email using Django's email functionality,
you probably don't want to send email each time you run a test using that
view. For this reason, Django's test runner automatically redirects all
Django-sent email to a dummy outbox. This lets you test every aspect of
sending email -- from the number of messages sent to the contents of each
message -- without actually sending the messages."
For somebody (like me) that need to use custom email backend for all tests, another solution would be to override TestRunner class and force settings change.
from django.conf import settings
from django.test.runner import DiscoverRunner
class CustomTestRunner(DiscoverRunner):
def setup_test_environment(self, **kwargs):
super().setup_test_environment(**kwargs)
settings.EMAIL_BACKEND = 'path.to.your.email.backend'
And after that register the test runner in settings:
TEST_RUNNER = 'path.to.CustomTestRunner'
I'm using a web service backend to provide authentication to Django, and the get_user method must retain a cookie provided by the web service in order to associate with a session. Right now, I make my remote calls just by calling urllib2.urlopen(myTargetService) but this doesn't pass the cookie for the current session along.
I have created a session access middleware to store the session in the settings:
class SessionAccessMiddleware:
def process_request(self, request):
settings.current_session = request.session
So, I can access the request session in get_request and post_request, but I don't know how to have urllib2 remember my cookies in a session-specific way.
How do I do this?
Here: http://docs.python.org/library/cookielib.html#examples are examples of doing exactly what you try to do with urllib2 and cookielib. So according to docs you need to create cookielib.CookieJar, set cookie with correct data (from session), build an opener that uses your CookieJar and use it to fetch yourTargetService.
If settings in your middleware code means from django.conf import settings it's not good idea. Look at http://github.com/svetlyak40wt/django-globals/ for a place where you can safely store request-wide data for access from somewhere where request object is unaccessible. Also, it would be probably good idea to write custom authentication backend and use it with django.contrib.auth - instead of rolling your own auth system from scratch - which is covered here: http://docs.djangoproject.com/en/dev/topics/auth/#writing-an-authentication-backend .