我在同一个网络中有两台计算机,我试图用python将文件从一个传递到另一个(在一个更大的项目的上下文中)。
在服务器端,我有以下瓶脚本:
import bottle
import json
@bottle.hook('after_request')
def enable_cors():
"""
You need to add some headers to each request.
Don't use the wildcard '*' for Access-Control-Allow-Origin in production.
"""
bottle.response.headers['Access-Control-Allow-Origin'] = '*'
bottle.response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS'
bottle.response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
# LANDING (IT IS NOT REALLY NEEDED JUST TO CHECK STUFF)
@bottle.route('/', method='GET')
def root():
return {
'api': 'api/'
}
@bottle.route('/api', method='POST')
def upload():
upload = bottle.request.files.get('file')
print upload.filename
upload.save('input.txt')
if __name__ == '__main__':
bottle.run(host='0.0.0.0', port=8080, debug=True)
在客户端我尝试通过请求库发送文件,例如:
import sys
import requests
r = requests.post('http://ip:port/api/', files={'file': open(sys.argv[1], 'rb')})
print r
( ip 和 port 对应于其各自的值)。
我收到此错误,我不确定如何处理。
Traceback (most recent call last):
File "loopmatch.py", line 4, in <module>
r = requests.post('http://ip:port/api/', files={'file': open(sys.argv[1], 'rb')})
File "/usr/local/lib/python2.7/site-packages/requests/api.py", line 111, in post
return request('post', url, data=data, json=json, **kwargs)
File "/usr/local/lib/python2.7/site-packages/requests/api.py", line 57, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/local/lib/python2.7/site-packages/requests/sessions.py", line 475, in request
resp = self.send(prep, **send_kwargs)
File "/usr/local/lib/python2.7/site-packages/requests/sessions.py", line 585, in send
r = adapter.send(request, **kwargs)
File "/usr/local/lib/python2.7/site-packages/requests/adapters.py", line 453, in send
raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', error(32, 'Broken pipe'))
任何帮助都将受到高度赞赏 谢谢!
答案 0 :(得分:0)
所以...事情很愚蠢......只要留下答案,以防其他人踩到这个愚蠢的错误......
bottle.route 和 requests.url 需要与完全匹配。在可能的情况下,路由为api
,而网址为api/
...这就是他们无法工作的原因......
需要将两者都移至api/
或api
。