CherryPy上传文件 [英] CherryPy upload file
问题描述
我想将文件从python3客户端发布到cherrypy.我正在使用请求库.我的客户代码:
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': open('file.zip', 'rb')}
r = requests.post(url, files=files)
我的服务器代码:
import os
import tempfile
import shutil
import cherrypy
config = {
'global' : {
'server.socket_host' : '127.0.0.1',
'server.socket_port' : 8080,
'server.thread_pool' : 8,
'server.max_request_body_size' : 0,
'server.socket_timeout' : 60
}
}
class App:
@cherrypy.config(**{'response.timeout': 3600})
@cherrypy.expose()
def upload(self):
'''Handle non-multipart upload'''
destination = os.path.join('/home/uvv/upload')
with open(destination, 'wb') as f:
shutil.copyfileobj(cherrypy.request.body, f)
return 'Okay'
if __name__ == '__main__':
cherrypy.quickstart(App(), '/', config)
服务器返回错误:
127.0.0.1 - - [17/Aug/2016:11:38:49] "POST /upload HTTP/1.1" 400 2083 "" "python-requests/2.10.0"
推荐答案
从响应中获取信息很有用.发送请求时,您会收到响应.从此响应中,您可以获得有关HTTP代码的信息,其中200表示可以,而400表示错误的请求.这就是您在cherrypy日志中看到的文本: POST/upload HTTP/1.1"400
.要获取更多信息,请使用 print(r.text)
打印响应文本
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)
如果将上面的代码与下面的代码一起使用,则它是将文件上传到cherrypy服务器的有效示例.
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
}
}
class App:
@cherrypy.expose
def upload(self, ufile):
upload_path = os.path.normpath('/path/to/project/data/')
upload_file = os.path.join(upload_path, ufile.filename)
size = 0
with open(upload_file, 'wb') as out:
while True:
data = ufile.file.read(8192)
if not 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)
将路径/path/to/project/data/
替换为适合您的项目的路径.
Replace the path /path/to/project/data/
to path that fits your project.
这篇关于CherryPy上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!