Export XML filled-up in form automatilly after filled-up - python

i'm trying to export a XML to user that fille-up in form in page.html and got 2 problems thats cannot resolve.
Little look at view.xml
nomeEmpresa = request.GET.get('insi')
caminhoXML = 'sistema/templates/paginas/geras-prev/previc/caixa/'
file = f'{nomeEmpresa}-{now.now()}'
nomeXML = ET.Element('caixa')
ET.SubElement(nomeXML, "isininstituicao").text = request.GET.get('insi')
ET.SubElement(nomeXML, "tpconta").text = request.GET.get('tipoDeConta')
ET.SubElement(nomeXML, "saldo").text = request.GET.get('saldo')
ET.SubElement(nomeXML, "nivelrsc").text = request.GET.get('nivelDeRisco')
ET.ElementTree(nomeXML).write(f"{caminhoXML}{file}.xml")
for file in glob.glob(f'{caminhoXML}*.xml'):
if 'None' in file:
os.remove(file)
download = False
else:
download = True
if download == False:
return render(request, 'paginas/geras-prev/previc/caixa/index.html')
else:
return render(request, 'paginas/geras-prev/previc/caixa/index.html')
Questions:
Everytime the user access the page.html it generate a null xml, because user doesn't fill the form in index.html, what need i do to doesn't generate it without the if/else ?
After user will fill the form, it will generate a right XMl file, but it save in sever. How to export that file download it automatilly after fill the form ?
PS: I don't want to use a database, because its a simple XML export without any interaction.

Related

"non-zero exit status 1" due to pdf file not found when using pypdftk to fill pdf forms in Django project in virtual env on dev server in Windows

The following python code successfully fills out a pdf form:
import pypdftk
data_dict = {key:value pairs}
PDF_PATH = 'form.pdf' #form to be filled out in same folder as the file executing this code
out_file = 'out_file.pdf' #completed pdf file
generated_pdf = pypdftk.fill_form(
pdf_path = PDF_PATH,
datas = data_dict,
out_file = out_file,
)
However, the same code used in my django project results in the following error message:
Error: Unable to find file.
Error: Failed to open PDF file:
form.pdf
Errors encountered. No output created.
Done. Input errors, so no output created.
... REMAINDER OF TRACEBACK EXCLUDED FOR BREVITY IF YOU WANT TO SEE IT I'LL POST...
raise subprocess.CalledProcessError(retcode, cmd, output=output) output=output) df fill_form C:\Users\Home\AppData\Local\Temp\tmpbqq__7c4 output out_file.pdf flatten
subprocess.CalledProcessError: Command 'pdftk l_a_r.pdf fill_form C:\Users\Home\AppData\Local\Temp\tmpbqq_0 87495_7c4 output out_file.pdf flatten'
returned non-zero exit status 1.
pypdftk is installed in the virtual environment the project is running in.
The pdftk server is added as a windows path variable.
In the above example, and every other time this has happened the temp file referenced at the end of the error message contains all of the expected data in XML.
I've tried the following combinations of code to try to make this work:
Running the exact above code within a view function, with the pdf form to be filled in the same folder as the views.py file:
import pypdftk
def filler_view(request):
form = MyForm()
if request.method =='POST':
#code to successfully populate dictionary data_dict with form data
PDF_PATH = 'form.pdf' #form to be filled out in same folder as the file executing this code
out_file = 'out_file.pdf #completed pdf file
generated_pdf = pypdftk.fill_form(
pdf_path = PDF_PATH,
datas = data_dict,
out_file = out_file,
)
return render(request, 'success.html')
Storing the code and file in a folder and importing to call the relevant function within the view:
-appFolder
-pfd_filler_folder
-form.pdf
-form_filler.py
-views.py
views.py
from appFolder.pdf_filler_folder import form_filler as f
def filler_view(request):
form = MyForm()
if request.method =='POST':
#code to successfully populate dictionary data_dict with form data
f.fill_form(data_dict, 'output.pdf')
form_filler.py:
import pypdftk
def fill_form(data_dict, out_file):
PDF_PATH = 'form.pdf'
generated_pdf = pypdftk.fill_form(
pdf_path = PDF_PATH,
datas = data_dict,
out_file = out_file,
)
Running both of the above with the full path from c:\... of the form.pdf file.
I've also verified that I can successfully fill a form with the executing .py file and the form.pdf file in same folder on two storage drives and from within the django project itself, when not being executed by the django project. pdftk finds the forms.py with no problems at all in this circumstance.
I believe that the file not found error message is key, as it seems to refer to the pdf form I'm trying to fill out. I've spent from 1500 till 1800 researching this, and I haven't managed to get it to work, although I am lead to believe that my error message indicates a missing parameter in the cl execution command. I'm not sure what this would be, as all parameters seem present and correct.
Interestingly enough, a friend of mine is experiencing the same error message just in windows. I'm aware that pdftk can sometimes be touchy in windows, and I think there's probably a nuance I'm missing here.
The outcome I'd like is to fill out a pdf form from within my django project, with data obtained from a form through a post request.
I'd welcome either someone enlightening me as to why pdftk is struggling to either see or use the form file whilst being used from within my django project and pointing me in the right direction
I'm aware that there are alternatives to using pdftk, but pdftk is the simplest, and honestly pypdftk is the only library I've found to reliably work with python to fill out pdf forms so far in Windows. I don't want to go down the route of generating my own replica form and populating it with data, but I'm aware that that is also an option.
Question answered just now on Reddit:
When in Django, it is either wsgi.py or manage.py which is ultimately responsible for what goes on. On that basis, placing the form.pdf file in the same folder as wsgy.py solved the problem and the code now runs as intended, with an unbound form POSTing data back to a view, and a pdf form being filled out and a duplicate saved with said data. Hope that helps anyone else who comes up against this!

How can I upload files in Postman?

I want to pass images through POST method in POSTMAN but I get None type response in the line request.files['image']
I have tried a number of different things but I am not able to solve the problem.
from flask import Flask,jsonify
from flask import request
import face_recognition
import json
app = Flask(__name__)
#app.route('/')
def index():
return ''
#app.route('/valid_faces', methods=['POST'])
def POST():
if request.method == 'POST':
# getting the images url from the request
print('....')
name1 = request.files['file'] if request.files.get('file') else None
print('....')
print (name1) # name2 = request.form.get('name2')
# map the url to the ones in the folder images
firstImage = name1
# loading the image inside a variable
firstImage = face_recognition.load_image_file(firstImage)
result=face_recognition.face_locations(firstImage)
if result:
# x={'valid_faces':True}
# return jsonify(x)
return "True"
else:
# x={'valid_faces':False}
# return jsonify(x)
return "False"
if __name__ == "__main__":
app.run(debug=True)
If you wish to append a file to a postman call it needs to be added to the body.
Check form-data and select file instead of text. You can now select a file with the windows file explorer.
To obtain the given file use the request package.
file = request.files['file']
The index has to be the same string you specified within the postman body data.
In Postman, do the following:
Set the method to POST
Set the body type to form-data
Establish Key/Value pairs for input. Set the value for the Key to
"file"
Mouse over the Key field and choose Text or File from the drop-down
menu
Click Send to process the request
In my case Postman set empty first value for FileStorage object in request.files . You can check this using:
print(str(request.files))
And in case of empty index instead
file = request.files['file']
try to use
file = request.files['']
follow this process: https://i.stack.imgur.com/GGm4I.png
Set Method to POST
Change body tab to form-data
Set key
in Value, hover, you can see file/text. in here select file
Select file you want to upload.
Send request.
you can do it
files = request.files.getlist("file")

Flask - render page without return

I'm working on an application, where user fills in form.
One of the fields asks for postcode. When request is sent, a separate thread runs python code using PYQT5, rendering page and scraping web, (don't want to pay for API from google) providing mileage between given postcode and set postcode. Results of this thread are saved in a file.
What i would like to do is to open a new webpage with information that the data is being checked. This page would run python code, which checks for results in a file (that takes up to few seconds) using while loop. if the result is in the file, the page redirect to another page.
Is there a way to render a page (or redirect to another page) without using RETURN? i understand that when I use return render_templates (page), rest of the code is ignored.
#app.route('/add_user', methods=['GET', 'POST'])
def add_user():
file = open('app/results_from_g.txt','w')
file.write('')
file.close()
form = AddForm()
if form.validate_on_submit():
url = 'https://google.co.uk/maps/dir/...'
def sendtogoogle(url):
os.system('python googlemaps_mileage.py ' +url)
thread1=threading.Thread(target=sendtogoogle, args=(url,))
thread1.start()
the next line of the code should be redirect to another page, and when results are in the file, either back here, or different page:
while result_from_file==0:
file = open('results_from_g.txt','r')
result_from_file = file.read()
if result_from_file =='': #means no data saved in the file yet
time.sleep(1)
elif wynik =='0': #means wrong postcode
//render page 'wrong postcode'
else:
//render page 'correct postcode

Is there a way to call a function when user enters the website/link?

So basically I'm working on a project that will allow users to download vCard when they enter the link. For example: https://www.google.com, when users open the link, a vCard will be downloaded.
I already have the download method written in views.py. and I want it to be executed when users open the link.
I tried to search on the internet, but I got no result.
This is the method to open the link:
def shareContact(request, data):
try:
cardDetails = uservcfDetails.objects.all().filter(uuid=data)
cardID = uservcfDetails.objects.get(uuid=data)
userID = cardID.user_id_id
checkBalance = userExchangeBalance.objects.get(user_id_id=userID)
context = {
'details': cardDetails,
}
return render(request, 'webapp/VCFCard/shareContact.html', context)
except Exception as error:
return render(request, 'webapp/VCFCard/CardNotFound.html')
I also have another method to download the file:
def download(request):
...
return
My question is: how to call the download method automatically?

export search results to csv file after displaying it in browser

I have tried to solve this problem for a week now and couldn't find a suitable solution.
I have a search bar to input gene ids (alternatively upload afile). It then queries the database and returns interactions between these genes. We display those interactions in a matrix on the html page. (I basically return a python array).
Now I want to include an export button to download the matrix / table in a csv or text file so the user can manipulate it for further research.
How can I do this without saving every query result in a file?
Because after returning the matrix, the python script (views.py) has run and the gene ids are gone.
Can it be done with jQuery?
Thank you so much for your help.
You only need to provide a link that contains current url plus a flag to indicate that it's a download csv request not a render page request:
def return_result(request):
# your original query
query = request.GET.get('id', None)
if query:
results = Model.objects.filter(field=query)
response = request.GET.get('download', None)
if response == 'csv':
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
# create a csv
return response
else:
context = {'results': results}
return render(request, 'results.html', context)
In your page you create a link to download csv, {{ request.get_full_path }} is to get current url from request:
Download as CSV

Categories