Dive into Code

Discover code snippets, tutorials, and programming insights

Postgresql

Backup postgres databases

Backup postgres databases

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
#!/bin/bash
logfile="/home/user/pgsql.log"
backup_dir="/home/user/backup"
touch $logfile
databases=`psql -h localhost -U postgres -q -c "\l" | sed -n 4,/\eof/p | grep -v rows\) | grep -v template0 | grep -v template1 | awk {'print $1'}`

echo "Starting backup of databases " >> $logfile
for i in $databases; do
        dateinfo=`date '+%Y-%m-%d %H:%M:%S'`
        timeslot=`date '+%Y%m%d%H%M'`
        /usr/bin/vacuumdb -z -h localhost -U postgres $i >/dev/null 2>&1
        /usr/bin/pg_dump -U postgres  -F c -b $i -h 127.0.0.1 -f $backup_dir/$i-database-$timeslot.backup
        echo "Backup and Vacuum complete on $dateinfo for database: $i " >> $logfile
done
echo "Done backup of databases " >> $logfile

tail -15 /home/user/pgsql.log
Django

Example wsgi file windows

Example wsgi file windows

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
"""
WSGI config for myproject project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""

import os
import sys
DJANGO_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
sys.path.append(DJANGO_PATH)
sys.path.append('c:/myproject/env/Scripts')
sys.path.append('c:/myproject/env/Lib/site-packages')
activate_this = 'c:/myproject/env/scripts/activate_this.py'
exec(open(activate_this).read(),dict(__file__=activate_this))
from django.core.wsgi import get_wsgi_application
#exec(open(activate_this).read())
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
application = get_wsgi_application()
Django

example virtualhost django apache2

example virtualhost django apache2

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<VirtualHost *:80>
	ServerName myproject
	WSGIScriptAlias / c:/myproject/myproject/myproject/wsgi.py
	Alias /favicon.ico c:/myproject/myproject/favicon.ico
	Alias /media/ c:/myproject/myproject/media/
	Alias /static/ c:/myproject/myproject/static/
	DocumentRoot c:/myproject/myproject/
  CustomLog c:/log/web_access.log combined
  ErrorLog c:/log/web_error.log
  LogLevel warn
	<Directory  "c:/myproject/myproject/myproject/">
		Options +Indexes +FollowSymLinks +MultiViews
		AllowOverride All
		Require local
	</Directory>
</VirtualHost>
Python

create backup with python 3 one archive

create backup with python 3 one archive

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import os
import datetime
import subprocess
import shutil
import errno
from pathlib import Path


home = str(Path.home())
now = datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
date_string = "{}".format(now)


dest = ''
'''
    dest var used to move created archives to another location
    example : dest = '/media/disk/'
'''
#dest = '{}/backup'.format(home)
'''
    folders is a list of folder paths to backup
    for example

    folders = [
        '/var/www/',
        '.ssh'
    ]
'''
folders = [
    
]

try:
    if dest is not None:
        os.makedirs(dest)
except OSError as e:
    if e.errno == errno.EEXIST:
        print('Directory not created.')
    else:
        raise
archived_name = "backup_{}.tar.gz".format(date_string)
print('create archive for folder :', archived_name)
out = subprocess.Popen(['tar','--use-compress-program=pigz','-cvf', archived_name ] + folders,
                       stdout=subprocess.PIPE,
                       stderr=subprocess.STDOUT)
stdout, stderr = out.communicate()
archive_exists = os.path.exists("{}/{}".format(home, archived_name))
if archive_exists:
    print('archive {} created '.format(archived_name))
if dest:
    if archived_name:
        filename = "{}/{}".format(home, archived_name)
        shutil.move(os.path.join(
            home, archived_name), os.path.join(dest, archived_name))