export search results to csv file after displaying it in browser - python

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

Related

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

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.

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

How do I use python requests to download a processed files?

I'm using Django 1.8.1 with Python 3.4 and i'm trying to use requests to download a processed file. The following code works perfect for a normal request.get command to download the exact file at the server location, or unprocessed file.
The file needs to get processed based on the passed data (shown below as "data"). This data will need to get passed into the Django backend, and based off the text pass variables to run an internal program from the server and output .gcode instead .stl filetype.
python file.
import requests, os, json
SERVER='http://localhost:8000'
authuser = 'admin#google.com'
authpass = 'passwords'
#data not implimented
##############################################
data = {FirstName:Steve,Lastname:Escovar}
############################################
category = requests.get(SERVER + '/media/uploads/9128342/141303729.stl', auth=(authuser, authpass))
#download to path file
path = "/home/bradman/Downloads/requestdata/newfile.stl"
if category.status_code == 200:
with open(path, 'wb') as f:
for chunk in category:
f.write(chunk)
I'm very confused about this, but I think the best course of action is to pass the data along with request.get, and somehow make some function to grab them inside my views.py for Django. Anyone have any ideas?
To use data in request you can do
get( ... , params=data)
(and you get data as parameters in url)
or
post( ... , data=data).
(and you send data in body - like HTML form)
BTW. some APIs need params= and data= in one request of GET or POST to send all needed information.
Read requests documentation

passing blob parameter to django

I keep my images in the DB as blobs:
class MyClass(db.Model):
icon=db.BlobProperty()
Now, I want to send the blob to my HTML like this :
lets say I have myClass as an instance of MyClass
result = """<div img_attr=%s> Bla Bla </div>""" % (myClass.icon)
Some how it doesn't work. Do you have any idea?
You cannot just dump raw image data into your html page. You need to do this in two pieces:
In your html, you need to refer to an image file:
result = "<div>"
"<img src='{0}' />"
"</div>"
.format(MYSITE + MYIMAGEDIR + myClass.name)
Your browser reads the html page, finds out you want to include an image, and goes looking for the image file to include - so it asks your site for something like http://www.myexample.com/images/icon01.jpg
Now, separately, you respond to this second request with the image content, as #anand has shown.
Your code suggests that you are working on Google application engine with Django.
You just need to query the image in your view and return it as http response.
image = myclassObject.icon
response = HttpResponse(image)
response['Content-Type'] = 'image/jpg'
return response
The value stored in the the data store, and returned by appengine with a db.BlobProperty is not the actual bytes of the blob, but rather a BlobKey that is used to reference it. There are two ways you can use that key. You can create a BlobReader to load the bytes of the blob from the BlobStore into your app, or you can craft a response with ServeHandler.send_blob to transfer those bytes to the client.
Doing the second one in Django is a bit of a headache, because ServeHandler doesn't really fit in well with the Django request processing stack. Here's a view that will do it for you without too much trouble:
def get_image_data(request, key, filename):
"serve original uploaded image"
# verify the users' ability to get the requested image
key = urllib.unquote(key)
img = _load_metadata(request, key)
blob = img.data;
blobkey = blob.key()
# and tell google to serve it
response = http.HttpResponse(
content='',
content_type=blob.content_type)
response['X-AppEngine-BlobKey'] = str(blobkey)
return response

Categories