I am creating a file download functionality on link click from admin panel in django. I am using FileField for storing the files. For the download purpose I researched and found help on stackoverflow. After using that help, I have the following code for file download (with some minor changes of my own).
def pdf_download(request):
#print("request: ", request.META["PATH_INFO"])
a = request.META["PATH_INFO"]
#print(type(a))
a = a.split("/")
a = a[-1]
#print(a)
#print(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
with open(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+"\\router_specifications\\"+a ,"rb") as pdf:
#Here router_specifications is the directory on local storage where the uploaded files are being stored.
response = HttpResponse(pdf.read()) #can add ', content_type = "application/pdf" as a specific pdf parameter'
response["Content-Disposition"] = "attachment; filename ="+a
pdf.close()
return response
Now, when I this code runs in my laptop, the file is downloaded automatically. but, when I switch to some other laptop, it asks me where should I save the file i.e. it's not automatically getting downloaded.
What changes should I do so that the file automatically gets downloaded without asking for manual save. Requesting help at the earliest.
You can try adding the following content_type:
content_type='application/force-download'
Related
I am working with pydrive to list files in a directory using the following loop
file_list = drive.ListFile({'q': 'trashed=false'}).GetList()
for file1 in file_list:
print('title: %s, id: %s' % (file1['title'], file1['id']))
I adjusted the oauth_scope as mentioned in another question response however I can only list the files created by pydrive and not uploaded by the user
My settings.yaml is having the following scope
oauth_scope:
https://www.googleapis.com/auth/drive
Any idea why I only get the files uploaded by pydrive, is there something that I need to adjust in the credentials settings in the google drive API?
Thanks and best regards
I tried adjusting outh scope in settings.yamlwith no luck
I'm making a django project that lets specific users to:
* first, upload a file with specified file-type;
* second, use that file to perform some calculations; and
* third, provide a derivative file for download.
The user can then view the list of all the files that was uploaded including the files uploaded by other users and choose which files to download or delete.
I made an app to manage the user's accounts and another app (core) for file uploads and calculations. Now I want to store the uploaded file in a specific directory so that I can easily access the file for data retrieval.
I tried doing this:
core_app/models.py
def file_path_dir(instance, filename):
return 'files/{0}/{1}'.format(instance.id, filename)
class Core(models.Model):
id = models.AutoField(primary_key=True, editable=False)
date_created = models.DateField(auto_now_add=True)
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
csv = models.FileField(upload_to=file_path_dir,
validators=[FileExtensionValidator(allowed_extensions=['csv'])]) # NOT SAFE
Here, I want the file to be uploaded in a directory using the id that will be stored in the database. However, the file was stored in this directory instead - files/None/filename.
I don't know why it says 'None' when I have successfully saved the file in the database (using postgresql). I need help how to solve this or how to properly do this in order for it to work.
Also, I would like to know the safest/ more secure way of validating file extensions.
The file_path_dir is called before an actual save on the database side happens. And the id that you are making use of, is not created yet because the save function isn't called yet.
In order to have the id you need to save the instance and the file in a temporary folder and then move it after you got the id from the database.
But a better way of doing is using something else instead of the id. You can use month, day or even year instead and if you really need something unique for each file directory, you can add a unique field like an extra id or slug and generate it yourself and make use of that.
And for your second question about validating file extensions:
the first step is to check the format which you're already doing and it's usually safe enough depending on the platform. But if you need more security, you can read the file in a safe environment and see if it meets the rules for that type of extension. Or you can use other apps that do that for you and use them in the background.
I have an analysis project that is requiring me to extract the 'current state' of a PDF that houses our report that is sent out 4 times daily. I have the code written to scrape my PDF but I need to figure out how to extract the PDF from the email so I can step through it with my code.
I tried using the code below
import win32com.client
import os
location = r'C:\Users\myusername\OneDrive - companyinfo\Department Projects\TestEmails'
files = [f for f in os.listdir(location)]
print(files)
for file in files:
if file.endswith('.msg'):
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
msg = outlook.OpenSharedItem(file)
att = msg.Attachments
for i in att:
i.SaveAsFil`e(os.path.join(r'C:\Users\username\OneDrive - companyname\Department Projects\TestPDF', i.FileName))
The error it produces is:
pywintypes.com_error: (-2147352567, 'Exception occurred.', (4096, u'Microsoft Outlook', u"We can't open 'Stats Report.msg'. It's possible the file is already open, or you don't have permission to open it.\n\nTo check your permissions, right-click the file folder, then click Properties.", None, 0, -2147287038), None)
I am only currently testing with one saved test.msg file but I have over 1400 I need to parse through. Maybe this isn't the best technique as I know VBA could do something similar within outlook, but I don't have much skills in the VBA region.
I have outlook 2016 installed on Windows 7 computer running python 2.7. Is this error something easy to fix? Is there a better technique to take an attached PDF and save it to a folder so my other program can grab the necessary data?
Desired output: PDF Attachment is Extracted and Saved into a separate folder.
Thank you for your help and expertise,
Andy
So I figured out the answer and how simple and stupid it was makes me unreasonably frustrated.....
My working directory was wrong even though I grabbed the file, the file name was the only item created.
I created a true_location variable that gave it the true full working directory and it worked like a charm.
true_location = location + '\\' + file
Enter that in the for loop under the if clause and it works like a charm.
Best,
Andy
I currently have a 34x22 .xlsx spreadsheet. I am downloading it via pydrive, filling in some of the blank values, and uploading the file back via pydrive. When I upload the file back, all cells with formulas are blank (any cell that starts with =). I have a local copy of the file I want to upload, and it looks fine so I'm pretty sure the issue must be with pydrive.
My code:
def upload_r1masterfile(filename='temp.xlsx'):
"""
Upload a given file to drive as our master file
:param filename: name of local file to upload
:return:
"""
# Get the file we want
master_file = find_r1masterfile()
try:
master_file.SetContentFile(filename)
master_file.Upload()
print 'Master file updated. ' + str(datetime.datetime.now())
except Exception, e:
print "Warning: Something wrong with file R1 Master File."
print str(e)
return e
The only hint I have is that if I add the param={'convert': True} tag to Upload, then there is no loss. However, that means I am now working in google sheets format, and I would rather not do that. Not only because it's not the performed format to work with here, but also because if I try to master_file.GetContentFile(filename) I get the error: No downloadLink/exportLinks for mimetype found in metadata
Any hints? Is there another attribute on upload that I am not aware of?
Thanks!
Robin was able to help me answer this question at the github repository. Both suggested solutions worked:
1) When you upload the file, did you close Excel first? IIRC MS Office writes a lot of the content to a temporary file, so that may explain why some parts are missing. If you tried the non converting upload first, the full file may have been saved to disk between the two tries, and thus the second converting upload attempt worked.
2) GetContentFile takes a second argument called mimetype, which should allow you to download the file. Could you try .GetContentFile(filename, mimetype="application/vnd.ms-excel")? If that mimetype doesn't work as anticipated, there is a great StackOverflow post here which lists a bunch of different types you can try.
Thanks again Robin!
I am trying to export a ModelView's data to CSV. Activating can_export = True as recommended in the docs does nothing.
I inspected my Flask-Admin installation, and even though it was the latest version (1.3.0), the source is different, so I downloaded and installed the master.zip available on GitHub.
Now, the Export button appears on my View, but clicking it generates BuildError: ('tableview.export_csv', {}, None)
I tried manually pasting the source's export_csv method into my class (which seems kludgy), but all I get is an empty CSV file.
How can I let the user download a CSV with the table view data?
My code for reference:
class DataTable(Secure):
def __init__(self, modelclass, session, **kwargs):
super(DataTable, self).__init__(modelclass, session, **kwargs)
self.can_export = True
self.column_filters = [c[0] for c in self._list_columns]
# Add view to menu
admin.add_view(DataTable(modelclass, name='TESTE', category=u'TEST'))
Solved:
There were multiple versions of Flask-Admin installed: All of these were 1.3.0, but Flask-Admin's code on GitHub changed without changing the version number. I manually deleted offending folder my environment's site-packages.
Flask-Admin's master.zip on GitHub does not contain the exact code as the website. This is not obvious, and I only found out because I needed a feature that was listed in the Documentation, but did not actually exist on master.zip, only on the Web version.