get local path of an uploaded file in django - python

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)

Related

python code to upload files to sharepoint

i want to be able to export .csv or excel workbooks directly into Sharepoint using python code - is this even possible?
thanks in advance!
Hi i found something that can help you!
You need this library: Office365 REST python client, to connect to the Microsoft API and upload your files (here you can find an example that does exactly what do you want). I think that you can upload both .csv and .xls, you should try and let us know!
According to my research and testing, I will recommend you to use Office365-Rest-Python-Client to consume SharePoint Rest API.
You can use the following code to upload file:
import os
from office365.sharepoint.client_context import ClientContext
from tests import test_user_credentials, test_team_site_url
ctx = ClientContext(test_team_site_url).with_credentials(test_user_credentials)
path = "../../data/report #123.csv"
with open(path, 'rb') as content_file:
file_content = content_file.read()
list_title = "Documents"
target_folder = ctx.web.lists.get_by_title(list_title).root_folder
name = os.path.basename(path)
target_file = target_folder.upload_file(name, file_content).execute_query()
print("File has been uploaded to url: {0}".format(target_file.serverRelativeUrl))
More information for reference: https://github.com/vgrem/Office365-REST-Python-Client/blob/master/examples/sharepoint/files/upload_file.py

Creating view in browser functionality with python

I have been struggling with this problem for a while but can't seem to find a solution for it. The situation is that I need to open a file in browser and after the user closes the file the file is removed from their machine. All I have is the binary data for that file. If it matters, the binary data comes from Google Storage using the download_as_string method.
After doing some research I found that the tempfile module would suit my needs, but I can't get the tempfile to open in browser because the file only exists in memory and not on the disk. Any suggestions on how to solve this?
This is my code so far:
import tempfile
import webbrowser
# grabbing binary data earlier on
temp = tempfile.NamedTemporaryFile()
temp.name = "example.pdf"
temp.write(binary_data_obj)
temp.close()
webbrowser.open('file://' + os.path.realpath(temp.name))
When this is run, my computer gives me an error that says that the file cannot be opened since it is empty. I am on a Mac and am using Chrome if that is relevant.
You could try using a temporary directory instead:
import os
import tempfile
import webbrowser
# I used an existing pdf I had laying around as sample data
with open('c.pdf', 'rb') as fh:
data = fh.read()
# Gives a temporary directory you have write permissions to.
# The directory and files within will be deleted when the with context exits.
with tempfile.TemporaryDirectory() as temp_dir:
temp_file_path = os.path.join(temp_dir, 'example.pdf')
# write a normal file within the temp directory
with open(temp_file_path, 'wb+') as fh:
fh.write(data)
webbrowser.open('file://' + temp_file_path)
This worked for me on Mac OS.

Best practice to config the dynamically generated file

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

File upload at web2py

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).

Save a pdf file stored in Mongodb GridFS using Python

I had uploaded some PDF, PNG files to a local instance of mongodb. By mistake I deleted these files and I can no longer recover them using the regular recover options. However, they are in my local mongodb database. How can I save them back in their original format on my computer?
I know the following:
import pymongo as pym
import gridfs
def connectToDb():
client = pym.MongoClient('mongodb://localhost:27017/')
db = client.questionbank
collectn = db.questionbank
fs = gridfs.GridFS(db)
return db, collectn, fs
db, collectn, fs = connectToDb()
filelist = list( db.fs.files.find({}, {"_id": 1, "filename": 1}) )
fileid = filelist[0]['_id']
fobj = fs.get(fileid)
## I don't know what to do after this. I think I cannot use read since I don't
## want the string. I want to save the pdf file as a pdf file.
Any help will be greatly appreciated. Thanks in advance.
Okay, I figured this out on my own. It can be done in the following way:
To the above code add the lines:
f = open('tempfigfile.pdf', 'wb')
f.write(fobj.read())
f.close()
This saves the file as tempfigfile.pdf.
This code will save all the files to ur local folder from mongodb gridfs.
i=0
cursor=fs.find()
while(i < cursor.count()):
fi=cursor.next()
with open("C:\\localfolder\\"+fi.filename,"wb") as f:
f.write(fi.read())
f.closed
i=i+1

Categories

Resources