Cherrypy Upload File
I'm want to POST a file from a python3 client to cherrypy. I'm using the requests library. My client code: import requests url = 'http://127.0.0.1:8080/upload' files = {'file.zip'
Solution 1:
It's usefull to get information from response. When you send a request, you receive a response. From this response you can get information about HTTP code where 200 means OK and 400 means bad request. That's the text you can see in your cherrypy log: POST /upload HTTP/1.1" 400
. To get more information, print the response text using print(r.text)
#!/usr/bin/env python# -*- coding: UTF-8 -*-import requests
url = 'http://127.0.0.1:9090/upload'
files = {'ufile': open('file.txt', 'rb')}
r = requests.post(url, files=files)
print(r)
print(r.text)
If you use the code above with the code bellow, it's working example of uploading file to cherrypy server.
#!/usr/bin/env python# -*- coding: UTF-8 -*-import os
import cherrypy
config = {
'global' : {
'server.socket_host' : '127.0.0.1',
'server.socket_port' : 9090,
'server.thread_pool' : 8,
'server.max_request_body_size' : 0,
'server.socket_timeout' : 60
}
}
classApp:
@cherrypy.exposedefupload(self, ufile):
upload_path = os.path.normpath('/path/to/project/data/')
upload_file = os.path.join(upload_path, ufile.filename)
size = 0withopen(upload_file, 'wb') as out:
whileTrue:
data = ufile.file.read(8192)
ifnot data:
break
out.write(data)
size += len(data)
out = '''
length: {}
filename: {}
mime-type: {}
''' .format(size, ufile.filename, ufile.content_type, data)
return out
if __name__ == '__main__':
cherrypy.quickstart(App(), '/', config)
Replace the path /path/to/project/data/
to path that fits your project.
Post a Comment for "Cherrypy Upload File"