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
Related
I'm pretty new to asking questions on stack overflow and building a web app with flask so I apologize in advance if I say something that's incorrect.
I'm building a flask web app that handles scheduling appointments and naturally i'm using 3rd party libraries/wrappers to make API calls and to handle db queries (sqlite). As it is currently, my app doesn't use any kind of async code. I got thinking about scenarios where multiple users try to login or book an appointment, both involving db queries and api calls, and whether my application will block or not. Given that its all synchronous, if multiple users do try and login and book an appointment, will it block for some users while it handles other user requests, or is that all independent of my flask app and dependent on the WSGI server running the app? Any tips on how I can improve the performance of my app with regards to handling multiple requests?
Example route that multiple users try to visit at the same time:
...
#app.route('/signup/')
def signup():
# has a form that takes user input and submits it for processing in process_signup()
return render_template('signup.html')
#app.route('/process_signup/', methods=['POST'])
def process_signup():
form = request.forms
username = form['username']
password = form['password']
# insert values into customer db in a synchronous fashion
db = db() #gets the database
cursor = db.execute('insert into customers (username, password) values (?,?)', [username, password])
db.commit()
#send out a verification email using email api without any async
email_new_customer()
return redirect(url_for('signin'))
NOTE: I read that its better to have db queries and api calls handled asynchronously but not sure where to start or what kind of library compatible with flask will help me achieve that.
Thank you for your help and again I may have a big misunderstanding of how it all works as i'm very to new to this so I apologize.
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/
My company has a Flask application that uses flask-login to handle user logins/logouts and sessions. We use the #login_required decorator to protect views. Our clients log via persistent users stored in a database. However, we want employees of our company to be able to log in to our clients' sites without popping up in their users lists. We verify our own authenticity by CAS login at our own CAS server and checking that the username belongs to our company.
We want the employees to simply be able to login without needing to be persisted in the database but flask-login requires a persisted user model.
Sorry for the troublesome use of words here, but I hope this is understadable.
Every authorization system should check user in some storage by some field and in usual cases return exist or has permisions.
So with flask-login you can implement it with next: user_loader/header_loader/request_loader and UserMixin with user_id.
Every request with login_required call *_loader to get UserMixin. So it can look like next:
#login_manager.request_loader
def loader(request):
identifier = get_identifier_from_request(request)
exist = check_on_cas_server(identifier)
if not exist:
return None
user = UserMixin()
user.id = get_specified_or_random_id(identifier, exist)
return user
Details you can found with https://flask-login.readthedocs.org/en/latest/.
I have a python flask app using mongoengine and flask-security built up from the examples to expose all of the confirmation, registration, tracking, and recovery functionality.
Everything works except that a user created imperatively in the code using:
MongoEngineUserDatastore.create_user(...)
cannot login. That is, when you try to login with this user, you get an error message:
"Email requires confirmation"
Since the email with a hashed URL has not been sent, there is no way to confirm. Is there a parameter I can pass somewhere to confirm this user on creation or set the confirmed flag somewhere?
Here's my code:
I figured it out by confirming a newly registered user and examining mongodb to see what fields were added. Turns out that the required field for confirmation is confirmed_at, which must have a datetime so:
import datetime
# Create a user to test with
#app.before_first_request
def create_user():
user_datastore.create_user(
email='me#mydomain.com',
password=utils.encrypt_password('password'),
confirmed_at=datetime.datetime.now())
I've updated the gist here:
https://gist.github.com/davidthewatson/327776905ef30815c138
When you create your test user you need to make them active eg:
#app.before_first_request
def create_user():
user_datastore.create_user(
email='me#mydomain.com',
password=utils.encrypt_password('password'),
active=True)
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