How to restore sqlite3 database file programmatically in django - django

The user wishes to have a database backup and restore functionality through the application. They want to be able to download the database file and upload it to restore the database whenever needed. The problem is that django is already running the current DB file. I wrote the following logic to restore the database.
folder ='./'
if request.method == 'POST':
myfile = request.FILES['file']
fs = FileSystemStorage(location=folder)
if myfile.name.split(".")[1] != "sqlite3":
return JsonResponse({"res":"Please upload a database file."})
if os.path.isfile(os.path.join(folder, "db.sqlite3")):
os.remove(os.path.join(folder, "db.sqlite3"))
filename = fs.save("db.sqlite3", myfile)
file_url = fs.url(filename)
return JsonResponse({"res":file_url})
I get the following error which is rightly justified:
[WinError 32] The process cannot access the file because it is being used by another process
So, is there a way I can achieve this functionality through my application?

I found a better way to create this functionality using a csv. One could store the data from the DB into a csv file and restore it when uploaded. Following is my implementation:
def back_up_done(request):
tables = getTableNames()
sql3_cursor = connection.cursor()
for table in tables:
sql3_cursor.execute(f'SELECT * FROM {table}')
with open('output.csv','a') as out_csv_file:
csv_out = csv.writer(out_csv_file)
for result in sql3_cursor:
csv_out.writerow('Null' if x is None else x for x in result)
csv_out.writerow("|")
BaseDir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
csv_path = os.path.join(BaseDir, 'output.csv')
dbfile = File(open(csv_path, "rb"))
response = HttpResponse(dbfile, content_type='application/csv')
response['Content-Disposition'] = 'attachment; filename=%s' % 'backup.csv'
response['Content-Length'] = dbfile.size
os.remove(os.path.join("./", "output.csv"))
return response
def back_up_restore(request):
if request.method == 'POST':
DBfile = request.FILES['file']
cursor = connection.cursor()
if DBfile.name.split(".")[1] != "csv":
messages.add_message(request, messages.ERROR, "Please upload a CSV file.")
return redirect('back-up-db')
tables = getTableNames()
i = 0
deleteColumns()
decoded_file = DBfile.read().decode('utf-8').splitlines()
reader = csv.reader(decoded_file)
for row in reader:
if len(row) != 0:
if(row[0] == "|"):
i += 1
else:
query = f'''Insert into {tables[i]} values({concatRowValues(row)})'''
cursor.execute(query)
connection.close()
messages.add_message(request, messages.SUCCESS, "Data Restored Successfully.")
return redirect('login')
def concatRowValues(row):
data = ''
for i,value in enumerate(row):
if value == "False":
value = '0'
elif value == "True":
value = '1'
if i != len(row) - 1:
data = f'{data}{str(value)},' if value == "Null" else f'{data}\'{str(value)}\','
else:
data = f'{data}{str(value)}' if value == "Null" else f'{data}\'{str(value)}\''
return data
Where getTableNames and concatRowValues are helper functions to get the names of tables and to concatenate column values to form an executable sql statement, respectively. The "|" character is used to mark the end of a table's data.

Related

django filter data and make union of all data points to assignt to a new data

My model is as follows
class Drawing(models.Model):
drawingJSONText = models.TextField(null=True)
project = models.CharField(max_length=250)
Sample data saved in drawingJSONText field is as below
{"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]}
I am trying to write a view file where the data is filtered based on project field and all the resulting queryset of drawingJSONText field are made into one data
def load(request):
""" Function to load the drawing with drawingID if it exists."""
try:
filterdata = Drawing.objects.filter(project=1)
ids = filterdata.values_list('pk', flat=True)
length = len(ids)
print(list[ids])
print(len(list(ids)))
drawingJSONData = dict()
drawingJSONData = {'points': [], 'lines': []}
for val in ids:
if length >= 0:
continue
drawingJSONData1 = json.loads(Drawing.objects.get(id=ids[val]).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]
length -= 1
#print(drawingJSONData)
drawingJSONData = json.dumps(drawingJSONData)
context = {
"loadIntoJavascript": True,
"JSONData": drawingJSONData
}
# Editing response headers and returning the same
response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context))
return response
I runs without error but it shows a blank screen
i dont think the for function is working
any suggestions on how to rectify
I think you may want
for id_val in ids:
drawingJSONData1 = json.loads(Drawing.objects.get(id=id_val).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]

\u0000 cannot be converted to text in django/postgreSQl

i have a project with django .on the host when i want to upload an image sometime error occurred(problem with specific images)! the below show how i resize uploaded images:
def save_files_to_media(request, is_public=False, klass=None, conversation=None):
from apps.file.models import File
fs = FileSystemStorage()
file_items = {}
for data_item in request.data:
file_match = re.search('^fileToUpload\[(\d+)\]$', data_item)
if file_match and file_match.groups():
item_index = file_match.groups()[0]
if item_index not in file_items:
file_items[item_index] = {}
file_items[item_index]['file_to_upload'] = request.data[data_item]
else:
optimize_match = re.search('^optimizeType\[(\d+)\]$', data_item)
if optimize_match and optimize_match.groups():
item_index = optimize_match.groups()[0]
if item_index not in file_items:
file_items[item_index] = {}
file_items[item_index]['optimize_type'] = request.data[data_item]
files = []
for file_item_key in file_items:
input_file = file_items[file_item_key]['file_to_upload']
# TODO: checking validation. if input_file.name is not exist
optimize_type = file_items[file_item_key].get('optimize_type')
file_uuid = str(uuid4())
if is_public:
orig_filename, file_ext = splitext(basename(input_file.name))
directory_name = join(settings.MEDIA_ROOT, file_uuid)
filename = file_uuid + file_ext
else:
directory_name = join(settings.MEDIA_ROOT, file_uuid)
mkdir(directory_name)
filename = input_file.name
filepath = join(directory_name, filename)
fs.save(filepath, input_file)
is_optimized = False
if optimize_type == 'image':
is_success, filepath = image_optimizer(filepath)
filename = basename(filepath)
is_optimized = is_success
file_obj = File(
orig_name=filename,
uuid=file_uuid,
md5sum=get_md5sum(filepath),
filesize=get_filesize(filepath),
meta=get_meta_info(filepath),
is_optimized=is_optimized,
creator=request.user
)
if is_public:
file_obj.is_public = True
else:
file_obj.klass = klass
file_obj.conversation = conversation
file_obj.save()
files.append(file_obj)
return files
here is the error i got with some images:
unsupported Unicode escape sequence
LINE 1: ..., 'ada90ead20f7994837dced344266cc51', 145216, '', '{"FileTyp...
^
DETAIL: \u0000 cannot be converted to text.
CONTEXT: JSON data, line 1: ...ecTimeDigitized": 506779, "MakerNoteUnknownText":
its funny that in my local but not in host. for more information i must tell you guys my postgreSQL version is 11.3 and host postgreSQl is 9.5.17 . where you think is problem? as error it's seems for postgreSQL. thank you

Python2.7: reading a gzfile content inside a zipfile

Hello I was wondering if there is a way of reading a unformatted file which is stored in gzformat that is stored in zipformat. also this should be done without extracting any file format and outside pluggin than what python 2.7 can provides.
I just want to read entire or line (depending on minimal for memory usage) of the content if there is a bunch of gz in a zipfile then store it in a txt format outside.
My code as of now can read out .log, .gz, .zip also .zip in a zip.
the idea is that it should repeat itself until we get the main file !
Thanks in advance :=)
.zip--->.gz--->unformattedfile
def decompress_file(filepath,type,file=None):
result = {}
if type.lower() == '.log':
if file ==None:
inFile = open(filepath, 'r')
return getLog(inFile)
else:
return getLog(file)
if type.lower() == '.gz':
if file == None:
inFile = gzip.open(filepath, "r")
else:
#content = io.BytesIO(file.read())
with file:
Gz_file= open(file,'r')
for gzFiles in file.namelist():
zFile=file.getinfo(file)
return getLog(zFile)
return getLog(inFile)
print inFile
return getLog(inFile)
if type.lower() == '.zip':
if file == None:
with zip.ZipFile(filepath,'r'):
zFile = zip.ZipFile(filepath)
else:
with zip.ZipFile(file,'r'):
zFile = zip.ZipFile(file)
for f_list in zFile.namelist():
content= io.BytesIO(zFile.read(f_list))
pattern = r'(.+)(?P<file>\.zip|\.gz)'
rgz = re.compile(pattern, re.IGNORECASE)
m = rgz.match(f_list)
if m==None:
type = '.log'
decompress_file(f_list,type,zFile)
else:
decompress_file(f_list,m.group('file').lower(),content)
return result
return result
if __name__ == '__main__':
decompress_file("filepath",'.zip' )

flask + wtforms nameerror

flask + wtforms
Hello, I have some problems with the transfer of data into a form
def edit_comment(n):
idlist = str(n)
if (r.exists('entries:%s' %idlist) != True):
return abort(404)
if 'user_id' not in session:
return abort(401)
if (g.user['group_access'] == '1'):
return abort(403)
form = EditForm(idlist)
return render_template('edit_comment.html',idlist = idlist, r = r, form = form)
...
class EditForm(Form):
edit_title = TextField("Title",validators = [Required()] ,default =r.hget('entries:%s' %idlist, 'title'))
edit_text = TextAreaField("Text",validators = [Required()],default =r.hget('entries:%s' %idlist, 'text'))
...
Traceback (most recent call last):
File "run.py", line 129, in <module>
class EditForm(Form):
File "run.py", line 130, in EditForm
edit_title = TextField("Title",validators = [Required()] ,default =r.hget('entries:%s' %idlist, 'title'))
NameError: name 'idlist' is not defined
here there are clear problems with data transmission. tried to pass through the constructor, but so far No results
You need to set the default value on the EditForm instance. Right now it' set at import time - clearly not what you want, even if the variable was defined. Actually, you don't even need the default field for it - just set it directly:
form = EditForm()
form.edit_title.data = r.hget('entries:%s' % idlist, 'title')
form.edit_text.data = r.hget('entries:%s' % idlist, 'text')
return render_template('edit_comment.html', idlist=idlist, r=r, form=form)
Note: Usually it's a good idea to have your view function to have a structure similar to this:
form = EditForm()
if form.validate_on_submit():
# do whatever should be done on submit, then redirect somewhere
return redirect(...)
elif request.method == 'GET':
# Populate the form with initial values
form.edit_title.data = ...
form.edit_text.data = ...
return render_template(..., form=form)
That way whatever the user entered is preserved in case the validation fails, but if he opens the form for the first time it's populated with whatever default data (e.g. the current values from your db) you want.

django: Class-based Form has no errors but is not valid. What is happening?

I have a form which is returning False from .is_valid(), but .errors and .non_field_errors() appear to be empty. Is there any other way to check out what might be causing this?
In case it's a problem with my logging code, here it is:
logger.debug('form.non_field_errors(): ' + str(form.non_field_errors()))
logger.debug('form.errors: ' + str(form.errors))
My form code:
class IncorporateForm(forms.Form):
type_choices = (("LTD", "Private company limited by shares"),
("LTG", "Private company limited by guarantee"),
("PLC", "Public limited company"),
("USC", "Unlimited company with share capital"),
("UWS", "Unlimited company without share capital"))
country_choices = (("EW", "England and Wales"),
("CY", "Wales"),
("SC", "Scotland"),
("NI", "Northern Ireland"))
articles_choices = (("MOD", "Model articles"),
("AMD", "Model articles with amendments"),
("BES", "Entirely bespoke articles"))
name = forms.CharField(initial = "[name] limited")
registered_office = forms.CharField(widget=forms.Textarea,
label='Registered office address')
registration_country = forms.ChoiceField(choices=country_choices,
widget=forms.RadioSelect(renderer=SaneRadioField))
company_type = forms.ChoiceField(choices=type_choices,
widget=forms.RadioSelect(renderer=SaneRadioField), initial="LTD")
articles_type = forms.ChoiceField(choices=articles_choices,
initial='MOD',
widget=forms.RadioSelect(renderer=SaneRadioField))
restricted_articles = forms.BooleanField()
arts_upload = forms.FileField(label='Articles to upload')
My view code (to the point where I detect that the form is not valid):
def incorporate_view(request):
form = IncorporateForm()
DirectorsFormset = forms.formsets.formset_factory(OfficerForm, extra=30)
CapitalFormset = forms.formsets.formset_factory(CapitalForm, extra=30)
HoldingFormset = forms.formsets.formset_factory(HoldingForm, extra=30)
AmendsFormset = forms.formsets.formset_factory(ArticlesAmendsForm, extra=50)
if request.method == 'POST':
#bind and validate
form.data = request.POST
guarantee_form = GuaranteeForm(data=request.POST)
directors_formset = DirectorsFormset(prefix='directors', data=request.POST)
capital_formset = CapitalFormset(prefix='capital', data=request.POST)
holding_formset = HoldingFormset(prefix='holding', data=request.POST)
amends_formset = AmendsFormset(prefix='amends', data=request.POST)
save_objects = [] # objects to be saved at the end if there is no error
user_objects = {} # keyed by email
individual_objects = {} # keyed by email?
if(not (form.is_valid() and guarantee_form.is_valid()
and directors_formset.is_valid()
and capital_formset.is_valid() and
holding_formset.is_valid() and
amends_formset.is_valid())):
dbg_str = """
form.is_valid(): %s
guarantee_form.is_valid(): %s
directors_formset.is_valid(): %s
capital_formset.is_valid(): %s
holding_formset.is_valid(): %s
amends_formset.is_valid(): %s
""" % (form.is_valid(), guarantee_form.is_valid(),
directors_formset.is_valid(),
capital_formset.is_valid(),
holding_formset.is_valid(),
amends_formset.is_valid())
logger.debug(dbg_str)
logger.debug('form.non_field_errors(): ' + str(form.non_field_errors()))
logger.debug('form.errors: ' + str(form.errors))
Assigning to form.data does not bind the form — you should pass the data dict when the object is constructed (or look into the code and see which flags are set, but that's probably not documented and therefore not recommended).