如何使用请求模块将数据发布到烧瓶应用程序?

时间:2014-09-01 23:51:08

标签: python python-2.7 flask python-requests

我正在尝试使用flask和请求模块开发一个小的小应用程序。我试图将一些数据发布到烧瓶Web应用程序中。但我坚持这个错误。

flask.py

@app.route('/add/', methods=['POST'])
def add_paths():
    paths = request.form['paths']
    tags = 'others'
    for path in paths:
        g.db.execute('insert into entries (path, tags) values(?, ?)',
            [path, tags])
        g.db.commit()
    message = 'New paths are posted'
    return jsonify(result = message)

用于发布数据的命令行文件

import json
import glob2
import requests

list = glob2.glob('/home/sheeshmohsin/*/**')
post_data = {'paths' : list }
headers = {'content-type': 'application/json'}
post_response = requests.post(url='http://localhost:9696/add/', data=json.dumps(post_data), headers=headers)
print post_response
print post_response.text

我得到的错误是: -

File "commandline.py", line 8, in <module>
    post_response = requests.post(url='http://127.0.0.1:9696/add/', data=json.dumps(post_data), headers=headers)
File "/usr/lib/python2.7/site-packages/requests/api.py", line 88, in post
    return request('post', url, data=data, **kwargs)
File "/usr/lib/python2.7/site-packages/requests/api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 335, in request
    resp = self.send(prep, **send_kwargs)
File "/usr/lib/python2.7/site-packages/requests/sessions.py", line 438, in send
    r = adapter.send(request, **kwargs)
File "/usr/lib/python2.7/site-packages/requests/adapters.py", line 327, in send
    raise ConnectionError(e)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=9696): Max retries exceeded with url: /add/ (Caused by <class 'socket.error'>: [Errno 111] Connection refused)

1 个答案:

答案 0 :(得分:0)

连接被拒绝错误消息表明它可能是您的防火墙或环回:

  • 检查防火墙是否阻止端口9696.
  • 我有环回(127.0.0.1)导致类似问题,因此请用实际IP地址替换localhost,以便Python不使用环回接口(requests.post(url='http://localhost:9696/add/',...)。您可能必须对Flask(app..run(host='192.168...', port=9696))执行相同操作。