Python - open uploaded file - python

I have a Tornado web application where I want to read the an uploaded file. This is received from the client and I try to do so like this:
def post(self):
file = self.request.files['images'][0]
dataOpen = open(file['filename'],'r');
dataRead = dataOpen.read()
But it gives an IOError:
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\tornado\web.py", line 1332, in _execute
result = method(*self.path_args, **self.path_kwargs)
File "C:\Users\rsaxdsxc\workspace\pi\src\Server.py", line 4100, in post
dataOpen = open(file['filename'],'r');
IOError: [Errno 2] No such file or directory: u'000c02c55024aeaa96e6c79bfa2de3926dbd3767.jpg'
Why isn't it able to see the file?

Value of file['filename'] is just name of uploaded file, it is not path in your filesystem. Content of file is in file['body']. You can use StringIO module to emulate file interface if you want, or just directly iterate over file['body'].
Very good example you could use is here
So, your post request handler could look like:
def post(self):
file = self.request.files['images'][0]
dataRead = file['body']
store_file_somewhere(file['filename'], dataRead)

Related

I'm trying to pass a variable to another script as an argument but it isnt working

When I change the content file and styleFile vars for just the file path, it works fine. So I know that the content file is there and that it can find it.
I must be passing a variable incorrectly to the other python script. I've been trying but I can't google myself out of this one at the moment.
import os
listStyles = ['/content/neural-style-tf/styles/1.png']
listContent = ['/content/neural-style-tf/image_input/00078.png']
i = 0
for imageName in listStyles:
stylefile = imageName
contentfile = listContent[i]
i = i + 1
print (stylefile)
print (contentfile)
print ('')
!python neural_style.py --content_img contentfile --style_imgs stylefile
Output:
/content/neural-style-tf/styles/1.png
/content/neural-style-tf/image_input/00078.png
Traceback (most recent call last):
File "neural_style.py", line 889, in <module>
main()
File "neural_style.py", line 886, in main
else: render_single_image()
File "neural_style.py", line 849, in render_single_image
content_img = get_content_image(args.content_img)
File "neural_style.py", line 715, in get_content_image
check_image(img, path)
File "neural_style.py", line 552, in check_image
raise OSError(errno.ENOENT, "No such file", path)
FileNotFoundError: [Errno 2] No such file: './image_input/contentfile'
I'm just dumb and need to not just brute force a language when I need it and learn it beforehand.
If anyone else comes across this you need to put a $ in front of the variable to let python know you're passing a var instead of a string.

How do I use ftp.storbinary to upload a file? [duplicate]

This question already has an answer here:
ftplib.error_perm: 553 Could not create file. (Python 2.4.4)
(1 answer)
Closed 2 years ago.
I am just starting to learn Python. I'm trying to upload a file as follows:
import ftplib
myurl = 'ftp.example.com'
user = 'user'
password = 'password'
myfile = '/Users/mnewman/Desktop/requested.txt'
ftp = ftplib.FTP(myurl, user, password)
ftp.encoding = "utf-8"
ftp.cwd('/public_html/')
ftp.storbinary('STOR '+myfile, open(myfile, 'rb'))
But get the following error:
Traceback (most recent call last):
File "/Users/mnewman/.spyder-py3/temp.py", line 39, in <module>
ftp.storbinary('STOR '+myfile, open(myfile, 'rb'))
File "ftplib.pyc", line 487, in storbinary
File "ftplib.pyc", line 382, in transfercmd
File "ftplib.pyc", line 348, in ntransfercmd
File "ftplib.pyc", line 275, in sendcmd
File "ftplib.pyc", line 248, in getresp
error_perm: 553 Can't open that file: No such file or directory
What does "that file" refer to and what do I need to do to fix this?
Reading the traceback, the error is deep in the ftp stack processing a response from the server. FTP server messages aren't standardized, but from the text its clear that the FTP server is unable to write the file on the remote side. This can happen for a variety of reasons - perhaps there is a permissions problem (the identity of the FTP server process does not have rights to a target), the write is outside of a sandbox setup on the server, or even that its already open in another program.
But in your case, you are using the full source file name in the "STOR" command when it wants the target path. Depending on whether you want to write subdirectories on the server, calculating the target name can get complicated. If you just want the server's current working directory, you could
ftp.storbinary(f'STOR {os.path.split(myfile)[1]}', open(myfile, 'rb'))
"That file" refers to the file that you're trying to upload to the FTP. According to your code, it refers to the line: myfile = '/Users/mnewman/Desktop/requested.txt'. You get this error because Python can't find the file in the path. Check whether it exists in the correct path. If you want to test whether there is an error in the script, you can add a test file to the directory in which your Python script exists and then run the script with the path of that file.
Example Script for FTP Upload:
import ftplib
session = ftplib.FTP('ftp.example.com','user','password')
file = open('hello.txt','rb') # file to send
session.storbinary('STOR hello.txt', file) # send the file
file.close() # close file and FTP
session.quit()

Script Python using plone.api to create File appear error WrongType when set a file

Dears,
I'm creating a script python to mass upload files in Plone site, the installation is UnifiedInstaller Plone 4.3.10.
This script read a txt, and this txt have separation with semicolon, the error appear when set up a file in a new created item.
Bellow the Script.
from zope.site.hooks import setSite
from plone.namedfile.file import NamedBlobFile
from plone import api
import transaction
import csv
portal = app['Plone']
setSite(portal)
container = portal['PROCESSOS']
with open('CARGA/C008_0002.txt', 'rb') as csvfile:
reader = csv.DictReader(csvfile, delimiter=';', quotechar='|')
for row in reader:
pdf_id = 'P'+str(row['IMAGEM']).strip('Pasta Geral\\ ')
file_obj = api.content.create(
container, 'File',
title=str(row['INTERESSADO']),
id=pdf_id,
description=str(row['CNPJ / CPF'])+' '+str(row['ASSUNTO']),
safe_id=True
)
pdf_path = 'INMEQ/'+str(row['IMAGEM']).replace("\\", "/")
print(pdf_path)
file_obj.file = NamedBlobFile(
data=open(pdf_path, 'r').read(),
contentType='application/pdf',
filename=str(file_obj.id),
)
print('Created: '+row['NDOPROCESSO']+'.')
transaction.commit()
When the script will set up a file the error "WrongType" appear. See verbose bellow.
Traceback (most recent call last):
File "<console>", line 18, in <module>
File "/home/jaf/plone4310/buildout-cache/eggs/plone.namedfile-3.0.9-py2.7.egg/plone/namedfile/file.py", line 384, in __init__
self.filename = filename
File "/home/jaf/plone4310/buildout-cache/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/fieldproperty.py", line 52, in __set__
field.validate(value)
File "/home/jaf/plone4310/buildout-cache/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/_bootstrapfields.py", line 182, in validate
self._validate(value)
File "/home/jaf/plone4310/buildout-cache/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/_bootstrapfields.py", line 309, in _validate
super(MinMaxLen, self)._validate(value)
File "/home/jaf/plone4310/buildout-cache/eggs/zope.schema-4.2.2-py2.7.egg/zope/schema/_bootstrapfields.py", line 209, in _validate
raise WrongType(value, self._type, self.__name__)
WrongType: ('processo-al-1.pdf', <type 'unicode'>, 'filename')
Thanks for you attention!
--
Juliano Araújo
You need to pass the filename as unicode.
file_obj.file = NamedBlobFile(
data=open(pdf_path, 'r').read(),
contentType='application/pdf',
filename=unicode(file_obj.id), # needs to be unicode
)
More Info in the plone.namedfile docu --> https://github.com/plone/plone.namedfile/blob/36014d67c3befacfe3a058f1d3d99a6a4352a31f/plone/namedfile/usage.rst

FTP login to get file, getting no such file or directory

I've been working on retrieving a file from my ftp server, the intention is to get the file, untar it on the local machine and compare the MD5 sum to the locally install package. My main focus is getting this file from the ftp server.
After running the script I get the following:
Traceback (most recent call last):
File "./tgzTest.py", line 27, in <module>
proof = tarfile.is_tarfile("test.tgz")
File "/usr/pkg/lib/python2.7/tarfile.py", line 2585, in
is_tarfile t = open(name)
File "/usr/pkg/lib/python2.7/tarfile.py", line 1660, in
open return func(name, "r", fileobj, **kwargs)
File "/usr/pkg/lib/python2.7/tarfile.py", line 1722, in
gzopen fileobj = bltn_open(name, mode + "b")
IOError: [Errno 2] No such file or directory: 'test.tgz'
The following is the code I'm currently using, thanks for any suggestions!
#!/usr/bin/python
import tarfile
import os
import ftplib
from ftplib import FTP
import hashlib
ftpServer = 'myserver.com'
password = 'null'
os.chdir("/home/user/testFolder")
ftp = FTP(ftpServer)
ftp.login('Anonymous', password)
print "You're in"
fileDir = "/pub/pkgsrc/base_pkgs"
tfile = "test.tgz"
ftp.cwd(fileDir)
print ftp.pwd()
tar = tarfile.open("test.tgz", 'r|gz')
for file in tar.getmembers():
print file.name
tar.close()
The tarfile package expects files in the local file system, not on the FTP server. You have to download the file first using the retrbinary() method of the ftp object, and pass the path to the downloaded file to tarfile.open().

Python lib execute error

I made this python lib and it had this function with uses urllib and urllib2 but when i execute the lib's functions from python shell i get this error
>>> from sabermanlib import geturl
>>> geturl("roblox.com","ggg.html")
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
geturl("roblox.com","ggg.html")
File "sabermanlib.py", line 21, in geturl
urllib.urlretrieve(Address,File)
File "C:\Users\Andres\Desktop\ddd\Portable Python 2.7.5.1\App\lib\urllib.py", line 94, in urlretrieve
return _urlopener.retrieve(url, filename, reporthook, data)
File "C:\Users\Andres\Desktop\ddd\Portable Python 2.7.5.1\App\lib\urllib.py", line 240, in retrieve
fp = self.open(url, data)
File "C:\Users\Andres\Desktop\ddd\Portable Python 2.7.5.1\App\lib\urllib.py", line 208, in open
return getattr(self, name)(url)
File "C:\Users\Andres\Desktop\ddd\Portable Python 2.7.5.1\App\lib\urllib.py", line 463, in open_file
return self.open_local_file(url)
File "C:\Users\Andres\Desktop\ddd\Portable Python 2.7.5.1\App\lib\urllib.py", line 477, in open_local_file
raise IOError(e.errno, e.strerror, e.filename)
IOError: [Errno 2] The system cannot find the file specified: 'roblox.com'
>>>
and here's the code for the lib i made:
import urllib
import urllib2
def geturl(Address,File):
urllib.urlretrieve(Address,File)
EDIT 2
I cant understand why i get this error in the python shell executing:
geturl(Address,File)
You don't want urllib.urlretrieve. This takes a file-like object. Instead, you want urllib.urlopen:
>>> help(urllib.urlopen)
urlopen(url, data=None, proxies=None)
Create a file-like object for the specified URL to read from.
Additionally, if you want to download and save a document, you'll need a more robust geturl function:
def geturl(Address, FileName):
html_data = urllib.urlopen(Address).read() # Open the URL
with open(FileName, 'wb') as f: # Open the file
f.write(html_data) # Write data from URL to file
geturl(u'http://roblox.com') # URL's must contain the full URI, including http://

Categories