Skip to content
This repository was archived by the owner on May 16, 2019. It is now read-only.

Commit d18ca0a

Browse files
committed
Separate archive from database export
1 parent 1e8a6ec commit d18ca0a

File tree

3 files changed

+96
-58
lines changed

3 files changed

+96
-58
lines changed

api/restapi.py

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -472,14 +472,24 @@ def get_node(node):
472472
self.kserver.resolve(seller_guid).addCallback(get_node)
473473
return server.NOT_DONE_YET
474474

475-
@POST('^/api/v1/backup')
476-
def backup(self, request):
477-
tablesAndColumns = request.args["tablesAndColumns"][0]
475+
@POST('^/api/v1/backup_files')
476+
def backup_files(self, request):
478477
output = request.args["output"][0]
479-
return backupTool.backup(tablesAndColumns, output)
478+
return backupTool.backupFiles(output)
480479

481-
@POST('^/api/v1/restore')
482-
def restore(self, request):
480+
@POST('^/api/v1/export_database')
481+
def export_database(self, request):
482+
tables_and_columns = request.args["tables_and_columns"][0]
483+
remove_previous = request.args["remove_previous"][0]
484+
return backupTool.exportDatabase(tables_and_columns, remove_previous)
485+
486+
@POST('^/api/v1/restore_files')
487+
def restore_files(self, request):
483488
input = request.args["input"][0]
484-
deleteTableDataFirst = request.args["deleteTableDataFirst"][0]
485-
return backupTool.restore(input, deleteTableDataFirst)
489+
remove_previous_database_files = request.args["remove_previous_database_files"][0]
490+
return backupTool.restoreFiles(input, remove_previous_database_files)
491+
492+
@POST('^/api/v1/import_database')
493+
def import_database(self, request):
494+
remove_previous = request.args["remove_previous"][0]
495+
return backupTool.importDatabase(remove_previous)

backup.html

Lines changed: 34 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,33 +3,44 @@
33
<u>Underscored fields are required</u><br />
44
Example data is provided below each input<br />
55
<br />
6-
<b>Backup</b><br />
7-
<br />
8-
<form action="http://localhost:18469/api/v1/backup/" method="post">
9-
List of tables to backup (comma separated):<br />
10-
<input type="text" name="tablesAndColumns"><br>
11-
hashmap, profile, listings<br />
12-
<br />
6+
7+
<b>Backup files</b><br /><br />
8+
<form action="http://localhost:18469/api/v1/backup_files/" method="post">
139
Name of file to create (don't forget to add .tar.gz), leave empty for todays date:<br />
14-
<input type="text" name="output"><br>
15-
myveryspecialbackup.tar.gz<br />
16-
<br />
17-
<input type="submit" value="Backup" />
18-
</form>
19-
<br />
20-
<br />
21-
<b>Restore</b><br />
22-
<br />
23-
<form action="http://localhost:18469/api/v1/restore/" method="post">
10+
<input type="text" name="output"><br />
11+
myveryspecialbackup.tar.gz<br /><br />
12+
<input type="submit" value="Backup files" />
13+
</form><br /><br />
14+
15+
<b>Export database</b><br /><br />
16+
<form action="http://localhost:18469/api/v1/export_database/" method="post">
17+
List of tables to backup (comma separated):<br />
18+
<input type="text" name="tables_and_columns"><br />
19+
hashmap, profile, listings<br /><br />
20+
If previous table files should be removed before export:<br />
21+
<input type="text" name="remove_previous"><br />
22+
True / False (default)<br /><br />
23+
<input type="submit" value="Export database" />
24+
</form><br /><br />
25+
26+
<b>Restore Files</b><br /><br />
27+
<form action="http://localhost:18469/api/v1/restore_files/" method="post">
2428
<u>Input file</u>:<br />
2529
<input type="text" name="input"><br>
26-
myveryspecialbackup.tar.gz<br />
27-
<br />
28-
Boolean, if data should be removed in the table before input:<br />
29-
<input type="text" name="deleteTableDataFirst"><br>
30-
True for delete, False or empty for append<br />
31-
<br />
30+
myveryspecialbackup.tar.gz<br /><br />
31+
If data should be removed in the table before input:<br />
32+
<input type="text" name="remove_previous_database_files"><br>
33+
True / False (default)<br /><br />
3234
<input type="submit" value="Restore" />
35+
</form><br /><br />
36+
37+
<b>Import database</b><br /><br />
38+
<form action="http://localhost:18469/api/v1/import_database/" method="post">
39+
If previous table files should be removed before import:<br />
40+
<input type="text" name="remove_previous"><br />
41+
True / False (default)<br /><br />
42+
<input type="submit" value="Import database" />
43+
</form><br /><br />
3344

3445
</body>
3546
</html>

backupTool.py

Lines changed: 44 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@
22
from constants import DATA_FOLDER
33
import csv
44
import db.datastore as db
5+
import errno
56
import os
67
import re
78
import shutil
89
import sqlite3 as lite
910
import tarfile
1011
import time
1112

12-
TABLES = {
13+
_TABLES = {
1314
'hashmap': ['hash', 'filepath'],
1415
'profile': ['id', 'serializedUserInfo'],
1516
'listings': ['id', 'serializedListings'],
@@ -26,9 +27,18 @@
2627
}
2728

2829
def _getDatabase():
30+
"""Retrieves the OpenBazaar database file."""
2931
Database = db.Database()
3032
return Database.DATABASE
3133

34+
def silentRemove(filename):
35+
"""Silently removes a file if it exists."""
36+
try:
37+
os.remove(filename)
38+
except OSError as e:
39+
if e.errno != errno.ENOENT: # ENOENT: no such file or directory
40+
raise
41+
3242
def _exportDatabaseToCsv(tablesAndColumns):
3343
"""Reads the database for all given tables and stores them as CSV files."""
3444
dbFile = _getDatabase()
@@ -48,36 +58,40 @@ def _exportDatabaseToCsv(tablesAndColumns):
4858
writer.writerows(data)
4959
return result
5060

51-
def backup(tableList=None, output=None):
52-
"""Archives given tables and files in a single tar archive."""
61+
def backupFiles(output=None):
62+
"""Archives OpenBazaar files in a single tar archive."""
5363
os.chdir(DATA_FOLDER)
5464

55-
if tableList:
56-
# Parse table list
57-
tableList = tableList.replace(' ', '').split(',')
58-
tablesAndColumns = []
59-
for table in tableList:
60-
if table in TABLES:
61-
tablesAndColumns.append((table, TABLES[table]))
62-
else:
63-
return 'ERROR, Table not found: {0}'.format(table)
64-
65-
# Remove existing database files and re-make them
66-
if os.path.exists('backup'):
67-
shutil.rmtree('backup')
68-
os.makedirs('backup')
69-
_exportDatabaseToCsv(tablesAndColumns)
70-
7165
# Archive files
7266
files = os.listdir(DATA_FOLDER)
7367
if not output:
7468
output = 'backup_{0}.tar.gz'.format(time.strftime('%Y-%m-%d'))
69+
silentRemove(output)
7570
with tarfile.open(output, 'w:gz') as tar:
7671
for f in files:
7772
tar.add(f)
7873
tar.close()
7974
return 'Success'
8075

76+
def exportDatabase(tableList, removePrevious=False):
77+
"""Exports given tables to the OpenBazaar folder."""
78+
# Parse table list
79+
tableList = tableList.replace(' ', '').split(',')
80+
tablesAndColumns = []
81+
for table in tableList:
82+
if table in _TABLES:
83+
tablesAndColumns.append((table, _TABLES[table]))
84+
else:
85+
return 'ERROR, Table not found: {0}'.format(table)
86+
87+
# Remove existing database files and re-make them
88+
if removePrevious and os.path.exists('backup'):
89+
shutil.rmtree('backup')
90+
if not os.path.exists('backup'):
91+
os.makedirs('backup')
92+
_exportDatabaseToCsv(tablesAndColumns)
93+
return 'Success'
94+
8195
def _importCsvToTable(fileName, deleteDataFirst=False):
8296
"""Imports given CSV file to the database."""
8397
tableName = re.search('table_(\w+).csv', fileName).group(1)
@@ -101,27 +115,30 @@ def _importCsvToTable(fileName, deleteDataFirst=False):
101115
cursor.execute(insertsql, row)
102116

103117

104-
def restore(input, deleteTableDataFirst=False):
105-
"""Restores files and tables of given archive."""
118+
def restoreFiles(input, removePreviousDatabaseFiles=False):
119+
"""Restores files of given archive to OpenBazaar folder."""
106120
if not input:
107121
return 'Input path is needed'
108122
os.chdir(DATA_FOLDER)
109123

110124
# Remove existing database files if any
111-
if os.path.exists('backup'):
125+
if removePreviousDatabaseFiles and os.path.exists('backup'):
112126
shutil.rmtree('backup')
113127

114128
# Unarchive files
115129
with tarfile.open(input, 'r:gz') as tar:
116130
tar.extractall()
117131

132+
return 'Success'
133+
134+
if __name__ == '__main__':
135+
print 'Backup tool works as a library.'
136+
137+
def importDatabase(deletePreviousData=False):
138+
"""Imports table files from the OpenBazaar folder."""
118139
# Restore database files to the database
119140
if os.path.exists('backup'):
120141
files = ['backup/{0}'.format(f) for f in os.listdir('backup')]
121142
for f in files:
122-
_importCsvToTable(f, deleteTableDataFirst)
123-
143+
_importCsvToTable(f, deletePreviousData)
124144
return 'Success'
125-
126-
if __name__ == '__main__':
127-
print 'Backup tool works as a library.'

0 commit comments

Comments
 (0)