Dive into Code

Discover code snippets, tutorials, and programming insights

Linux

Bash script to create django project

Bash script to create django project

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash
if [ $# -eq 0 ]
then
    echo "No arguments supplied"
    exit 1;
else
  mkdir -p $1
  cd $1
  python3 -m venv env
  source env/bin/activate
  pip install django django-debug-toolbar django-extensions python-memcached
  mkdir public
  pip freeze > requirements.txt
  django-admin startproject $1
  cd $1
  mkdir templates static
  cd templates
  touch index.html base.html
  cd ..
  pwd
fi
Python

Python script to create a django project

Python script to create a django project

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
import os
import argparse


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("-n", "--name", required=True,
                    help="name of the project")
    args = vars(ap.parse_args())
    name = args["name"]
    path = os.getcwd()
    directory = "{}/sites/{}".format(path, name)
    if not os.path.exists(directory):
        os.mkdir(directory)
    os.chdir(directory)
    if not os.path.exists('public'):
        os.mkdir('public')
    os.system("""python3 -m venv env &&
              . {0}/env/bin/activate &&
              pip install django django-debug-toolbar django-extensions &&
              pip freeze > requirements.txt &&
              django-admin startproject {1} &&
              cd {1} &&
              mkdir static &&
              mkdir templates &&
              cd templates &&
              touch base.html &&
              touch index.html""".format(directory, name))
Python

Create backup with python 3 multiple archives

<p>Create backup with python 3 multiple-archives</p>

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
55
56
57
58
59
60
61
62
import os
import datetime
import subprocess
import shutil
from pathlib import Path


home = str(Path.home())
now = datetime.datetime.now()
year = now.year
day = now.day
month = now.month
date_string = "{}_{}_{}".format(year, day, month)


#dest = '/media/disk1/backups/'
'''
	dest var used to move created archives to another location
	example : dest = '/media/disk/'
'''
dest = None


'''
	folders is a list of folder paths to backup
	for example

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

]


for folder in folders:
	archived_name = None
	exists = os.path.exists(folder)
	if exists:
		folder_path = folder
		archived_name = "backup{}{}.tar.gz".format(
			folder.replace('/', '_').replace('.',''), date_string)
	if archived_name:
		if not os.path.exists(archived_name):
			print('create archive for folder :', archived_name)
			out = subprocess.Popen(
				['tar', '--exclude', '{}/env'.format(folder),
			 	 '{}/virtualenv'.format(folder),
			 	 '{}/bower_components'.format(
				 	folder), '-zcvf', archived_name, folder],
				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:
		filename = "{}/{}".format(home, archived_name)
		shutil.move(os.path.join(
			home, archived_name), os.path.join(dest, archived_name))
Python

Find srid of a shapefile in python 3

Find srid of shapefile in python 3

python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
import urllib.parse
import urllib.request
import json
from osgeo import ogr, osr

prj_file = open('file.prj', 'r')
prj_txt = prj_file.read()
prj_file.close()

query = {
    'exact': True,
    'error': True,
    'mode': 'wkt',
    'terms': prj_txt}
webres = 'http://prj2epsg.org/search.json'
data = urllib.parse.urlencode(query).encode("utf-8")
req = urllib.request.Request(webres)
with urllib.request.urlopen(req, data=data) as f:
    jres = json.loads(f.read())
    if jres['codes']:
        srid = int(jres['codes'][0]['code'])
        print(srid)