I made the file like this in views.py.
csvDir = 'exportedCsv/'
file_path = csvDir + 'test.csv'
df.to_csv(path_or_buf=file_path,sep=',',float_format='%.2f',index=False,decimal=",",encoding='utf_8_sig')
Dynamically generate file and path the filepath to html.
Now there is my file in /exportedCsv/test.csv
However I have no way to access this from html.
My idea is basiclly wrong???
What should I do when I want to make csv file and let the user download it??
You could add a link to it in your html like so: Download
Related
this is an URL example "https://procurement-notices.undp.org/view_file.cfm?doc_id=257280"
if you put it in the browser a file will start downloading in your system.
I want to download this file using python and store it somewhere on my computer
this is how tried
import requests
# first_url = 'https://readthedocs.org/projects/python-guide/downloads/pdf/latest/'
second_url="https://procurement-notices.undp.org/view_file.cfm?doc_id=257280"
myfile = requests.get(second_url , allow_redirects=True)
# this works for the first URL
# open('example.pdf' , 'wb').write(myfile.content)
# this did't work for both of them
# open('example.txt' , 'wb').write(myfile.content)
# this works for the second URL
open('example.doc' , 'wb').write(myfile.content)
first: if I put the first_url in the browser it will download a pdf file, putting second_url will download a .doc file How can I know what type of file will the URL give to us or what type of file will be downloaded so that I use the correct open(...) method?
second: If I use the second URL in the browser a file with the name "T__proc_notices_notices_080_k_notice_doc_79545_770020123.docx" starts downloading. how can I know this file name when I try to download the file?
if you know any better solution kindly let me know for the implementation.
kindly have a quick look at Downloading Files from URLs and zip downloaded files in python question aswell
myfile.headers['content-type'] will give you the MIME-type of the URL's content and myfile.headers['content-disposition'] gives you info like filename etc. (if the response contains this header at all)
you can use response headers content-type like for first url it is application/pdf and sencond url for is application/msword you save file according to it. you can make extension dictinary where you can store possible file format and their types and match with it. your second question is also same like this one so i am taking your two urls from that question and for file name i am using just integers
all_Urls = ['https://omextemplates.content.office.net/support/templates/en-us/tf16402488.dotx' ,
'https://procurement-notices.undp.org/view_file.cfm?doc_id=257280']
extension_dict = {'application/vnd.openxmlformats-officedocument.wordprocessingml.document':'.docx',
'application/vnd.openxmlformats-officedocument.wordprocessingml.template':'.dotx',
'application/vnd.ms-word.document.macroEnabled.12':'.docm',
'application/vnd.ms-word.template.macroEnabled.12':'.dotm',
'application/pdf':'.pdf',
'application/msword':'.doc'}
for i,url in enumerate(all_Urls):
resp = requests.get(url)
response_headers = resp.headers
file_extension = extensio_dict[response_headers['Content-Type']]
with open(f"{i}.{file_extension}",'wb') as f:
f.write(resp.content)
for MIME-Type see this answer
I need my pdf files that is generated by weasyprint to be some specified folder, for example in the folder "my_project/pdf_files/"
NOTE: I am using django framework for my project. And here is the structure of project.
my_project/
----pdf_generator_app/
--------admin.py
--------models.py
--------views.py
pdf_files/
Currently I have this in my views.py
def generate(student_id):
student = get_object_or_404(Student, application_id=student_id)
html = render_to_string('contract.html', {'student': student})
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'filename="some_file.pdf"'
weasyprint.HTML(string=html).write_pdf('myfile.pdf',
presentational_hints=True,
stylesheets=[weasyprint.CSS(settings.STATIC_ROOT + '/css/styles.css')])
return response
But this view does not store pdf file to a directory. It simply show file on browser. I need the file to be stored in the directory my_project/pdf_files/
I wrote the out put to the binary mode and it worked.
dirname = os.path.dirname(__file__)
def hello_pdf():
# Make a PDF straight from HTML in a string.
html = render_template('template-1.html', name=name)
pdf = HTML(string=html).write_pdf()
if os.path.exists(dirname):
f = open(os.path.join(dirname, 'mypdf.pdf'), 'wb')
f.write(pdf)
Oppsite to me, I got the PDF file but couldn't view it on my browser.
Replace 'myfile.pdf' to an absolulte path and check if if generates the pdf file. It work for me in my condition.
You can pass a file name as a parameter and it will store the PDF as a file:
HTML(string=html).write_pdf('out.pdf')
I am using the web2py framework.
I have uploaded txt a file via SQLFORM and the file is stored in the "upload folder", now I need to read this txt file from the controller, what is the file path I should use in the function defined in the default.py ?
def readthefile(uploaded_file):
file = open(uploaded_file, "rb")
file.read()
....
You can do join of application directory and upload folder to build path to file.
Do something like this:
import os
filepath = os.path.join(request.folder, 'uploads', uploaded_file_name)
file = open(filepath, "rb")
request.folder: the application directory. For example if the
application is "welcome", request.folder is set to the absolute path
"/path/to/welcome". In your programs, you should always use this
variable and the os.path.join function to build paths to the files you
need to access.
Read request.folder
The transformed name of the uploaded file is stored in the upload field of your database table, so you need a way to query the specific record that was inserted via the SQLFORM submission in order to get the name of the stored file. Here is how it would look assuming you know the record ID:
stored_filename = db.mytable(record_id).my_upload_field
original_filename, stream = db.mytable.my_upload_field.retrieve(stored_filename)
stream.read()
When you pass a filename to the .retrieve method of an upload field, it will return a tuple containing the original filename as well as the open file object (called stream in the code above).
I want to open an uploaded csv file in the clean function of a django form.
The code looks like this:
def clean(self):
file_csv = self.cleaned_data['csv_file']
records = csv.reader(open('file_csv.name, 'rU'), dialect=csv.excel_tab)
how do I get the local path of file_csv ?
Could this work ? It's using basic python though...
import os
os.path.abspath(file_csv.name)
Just wondered if anyone could help I'm trying to download a NetCDF file from the internet within my code. The website is wish to download from is:
http://www.esrl.noaa.gov/psd/cgi-bin/db_search/DBListFiles.pl?did=3&tid=38354&vid=20
the file name which I would like to download is air.sig995.2013.nc
and if its downloaded manually the link is:
ftp://ftp.cdc.noaa.gov/Datasets/ncep.reanalysis.dailyavgs/surface/air.sig995.2013.nc
Thanks
I would use urllib to retrieve the file
like this:
urllib.urlretrieve(url, filename)
where url is the url of the download and filename is the what you want to name the file
You can try this :
#!/usr/bin/env python
# Read data from an opendap server
import netCDF4
# specify an url, the JARKUS dataset in this case
url = 'http://dtvirt5.deltares.nl:8080/thredds/dodsC/opendap/rijkswaterstaat/jarkus/profiles/transect.nc'
# for local windows files, note that '\t' defaults to the tab character in python, so use prefix r to indicate that it is a raw string.
url = r'f:\opendap\rijkswaterstaat\jarkus\profiles\transect.nc'
# create a dataset object
dataset = netCDF4.Dataset(url)
# lookup a variable
variable = dataset.variables['id']
# print the first 10 values
print variable[0:10]
from
https://publicwiki.deltares.nl/display/OET/Reading%2Bdata%2Bfrom%2BOpenDAP%2Busing%2Bpython