Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Read-Only MySQL Database Connection in Django

Is it possible to add a connection to a database so when using it only select queries are allowed?

Something like this would be great:

DATABASES = {
    #can do update, insert, etc...
    'default': { 
        'ENGINE': 'django.db.backends.mysql',
        'USER': 'root',
        'PASSWORD': '12345',
    }
    #select only
    'default_readonly': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydb',
        'PASSWORD': '12345',
        'READONLY': True,

    }
}

I didn't find anything simple.

like image 437
YardenST Avatar asked Jul 25 '14 07:07

YardenST


People also ask

What is using self _DB in Django?

This is used in case you have multiple databases by which you define which database you need to use for operation. An example user. save(using=self. _db) is usually defined as "default" from your database configuration in settings.py .


1 Answers

As far as I know, Django does not provide any options to restrict the database connection to a "read-only" mode. However, you can do it by creating a readonly user in your MySQL database engine.

Another idea, on the Django code side, would be to create your own cursor, which throws exception if execute or executemany is called. You can look at this module django-db-readonly.

like image 172
Maxime Lorant Avatar answered Oct 07 '22 20:10

Maxime Lorant