Enable Dark Mode!
how-to-setup-automatic-database-backup-in-odoo-15.jpg
By: Aswathi C

How to Setup Automatic Database Backup in Odoo 15

Technical Odoo 15

A backup is a copy of your database data that can be used to reproduce that data. The importance of database backup is that when something goes wrong and a business can’t recover its data, it can be disastrous for them. So by creating a backup for the database, one can recover the data if any failures occur. Odoo already has an option to backup the database manually.

In this blog, we will discuss how we can automate the process of database backup by using scheduled actions.

Step 1: Create a custom module with the following directories.

how-to-setup-automatic-database-backup-in-odoo-15-cybrosys

1. First create an option on General Settings to configure automatic database backup.

Create a python file custom_res_config_settings.py under models to add a new option on general settings.

Add the below code to add the option on general settings.

from odoo import models,fields
class CustResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
database_backup_config = fields.Boolean("Database Auto Backup", config_parameter='db_backup.database_backup_config')

Create an XML file res_config_settings.xml on the views directory to add the XML view for the new option we created and add the below code to it.

<record id="res_config_settings_view_form" model="ir.ui.view">
    <field name="name">res.config.settings.view.form.inherit.base.setup</field>
    <field name="model">res.config.settings</field>
    <field name="priority" eval="0" />
    <field name="inherit_id" ref="base_setup.res_config_settings_view_form" />
    <field name="arch" type="xml">
        <xpath expr="//div[@id='contacts_settings']" position="before">
            <div id="db_backup_settings">
                <h2>Database Backup</h2>
                <div class='row mt16 o_settings_container' id='backup_div'>
                    <div class="col-12 col-lg-6 o_setting_box" title="...fggfhfgh" name="db_backup_setting_container">
                        <div class="o_setting_left_pane">
                            <field name="database_backup_config" />
                        </div>
                        <div class="o_setting_right_pane">
                            <label string="Database Backup" for="database_backup_config" />
                            <div class="text-muted" id="fghj">
                                Configure database backups.
                            </div>
                            <div class="content-group" attrs="{'invisible': [('database_backup_config','=',False)]}">
                                <div class="mt8">
                                    <button type="action" name="%(db_backup.action_db_backup)d"
                                        string="Configure Database Backups" icon="fa-arrow-right" class="btn-link" />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </xpath>
    </field>
</record>

The result of the above code will be as shown below:

how-to-setup-automatic-database-backup-in-odoo-15-cybrosys

Step 2: In the first step, we added the Database Configuration option on the General Settings of Odoo. In the second step, we are going to create the model and view for database configuration.

1. Create a python file backup_db.py under the models directory and add the following code to create a model for database backup.

import os
import odoo
from odoo import models, fields, api
from odoo15.odoo.tools.safe_eval import datetime
class DbBackup(models.Model):
_name = 'db.backup'
_rec_name = 'database'
database = fields.Char(string="Database", help="Database Name")
directory = fields.Char(string="Directory", help="Directory to store backup.")
backup_format = fields.Selection([
('zip', 'Zip'),
('dump', 'Dump')
], string='Backup Format', default='zip', required=True)
is_auto_remove = fields.Boolean(default=False)

2. Create an XML file db_backup_view.xml under the views directory. Add the following code on db_backup_view.xml to set up the form view of the model.

<record id="db_backup_tree" model="ir.ui.view">
    <field name="name">db.backup.tree</field>
    <field name="model">db.backup</field>
    <field name="arch" type="xml">
        <tree>
            <field name="database" />
            <field name="directory" />
            <field name="backup_format" />
        </tree>
    </field>
</record>
<record id="db_backup_form_view" model="ir.ui.view">
    <field name="name">Db Backup form</field>
    <field name="model">db.backup</field>
    <field name="arch" type="xml">
        <form>
            <sheet>
                <group>
                    <group>
                        <field name="database" />
                        <field name="directory" />
                    </group>
                    <group>
                        <field name="backup_format" />
                        <field name="is_auto_remove" />
                    </group>
                </group>
            </sheet>
        </form>
    </field>
</record>
<record id="action_db_backup" model="ir.actions.act_window">
    <field name="name">Database Backup</field>
    <field name="res_model">db.backup</field>
    <field name="view_mode">tree,form</field>
</record>

The output of the above code will be as shown below:

how-to-setup-automatic-database-backup-in-odoo-15-cybrosys

Database - The name of the database to backup.

Directory - The directory where the backup databases were stored.

Backup Format - The format of the backup (zip or dump).

Is Auto Remove - Specifies the databases need to be deleted from the folder automatically.

Step 3: In step3, we are going to create two scheduled actions for automatic database backup and automatic removal of backup databases.

Below is the code to create scheduled action for Automatic Database Backup. Add the following code inside the ir_cron_data.xml inside the data folder.

<record id="ir_cron_auto_db_backup" model="ir.cron">
    <field name="name">Backup : Automatic Database Backup</field>
    <field name="model_id" ref="db_backup.model_db_backup" />
    <field name="state">code</field>
    <field name="code">model.backup_database()</field>
    <field name="interval_number">1</field>
    <field name="interval_type">days</field>
    <field name="numbercall">-1</field>
</record>

Add the below method to the db_backup.py file:

def backup_database(self):
    res = self.env['db.backup'].search([])
for rec in res:
    try:
    if not os.path.isdir(rec.directory):
    os.makedirs(rec.directory)
backup_file = os.path.join(rec.directory, rec.database)
f = open(backup_file, "wb")
odoo.service.db.dump_db(rec.database, f, rec.backup_format)
f.close()
except Exception as e:
    print("Exception", e)

The output of the above code will be as shown below :

how-to-setup-automatic-database-backup-in-odoo-15-cybrosys

Also, add the below code inside  ir_cron_data.xml  to create a scheduled action for the automatic removal of backup databases from the specified directory.

<record id="ir_cron_remove_db_backup" model="ir.cron">
   <field name="name">Backup :Auto Remove Database Backup</field>
   <field name="model_id" ref="db_backup.model_db_backup"/>
   <field name="state">code</field>
   <field name="code">model.remove_backup_database()</field>
   <field name="interval_number">1</field>
   <field name="interval_type">days</field>
   <field name="numbercall">-1</field>
</record>

Add the below method to the db_backup.py file:

def remove_backup_database(self):
   res = self.env['db.backup'].search([])
   for rec in res:
       try:
           if rec.is_auto_remove:
               file = os.path.join(rec.directory, rec.database)
               os.remove(file)
       except Exception as e:
           print("Exception", e)

The output of the above code will be shown as follows :

how-to-setup-automatic-database-backup-in-odoo-15-cybrosys

In the above example, both the scheduled actions will execute every day.  The database will be backup every day based on the backup format (zip, dump) on the specified directory with the database name. If the is_auto_remove option is enabled for any of the records, the database specified on it will remove automatically from the specified directory on every execution time which is set on the scheduled action.

The result of the automatic backup of the database is shown in the following image. Here two databases db_new_15 and test_db in two different formats are backup.

how-to-setup-automatic-database-backup-in-odoo-15-cybrosys

Hope that you guys get the basic idea of how to backup a database automatically by using scheduled actions.

For further reference, you can refer to the following app Automatic Database Backup To Local Server, Remote Server, Google Drive, & Dropbox


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment

 
whatsapp
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

London

Cybrosys Limited
Alpha House,
100 Borough High Street, London,
SE1 1LB, United Kingdom

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message