带有请求模块的Python Flask

时间:2013-09-19 20:54:41

标签: python http flask python-requests

我正在使用Python服务器与Python的Requests模块进行http调用。请求调用在常规python shell中没有问题。但是在Flask中,它出现了“引发ConnectionError(e)”的错误。这真的很痛,因为我需要使用python在后端调用url,因为我不能使用javascript因为跨域限制。

flask python # cat myapp.py
import json
import requests
from flask import Flask
app = Flask(__name__)


@app.route('/', defaults={'path': ''}, methods=('GET', 'POST'))
@app.route('/<path:path>', methods=('GET', 'POST'))
def catch_all(path):
    link = "http://10.44.11.33/api/v1/counts/latest/15"
    r = requests.get(link)
    return "Hello World"


if __name__ == '__main__':
    app.run(debug=True, host="0.0.0.0")

错误输出:

File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1836, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1820, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1403, in handle_exception
reraise(exc_type, exc_value, tb)
File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1817, in wsgi_app
response = self.full_dispatch_request()
File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1477, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1381, in handle_user_exception
Display the sourcecode for this frameOpen an interactive python shell in this framereraise(exc_type, exc_value, tb)
File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1475, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/lib64/python2.7/site-packages/flask/app.py", line 1461, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/python/myapp.py", line 13, in catch_all
r = requests.get(core_link)
File "/usr/lib64/python2.7/site-packages/requests/api.py", line 55, in get
return request('get', url, **kwargs)
File "/usr/lib64/python2.7/site-packages/requests/api.py", line 44, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib64/python2.7/site-packages/requests/sessions.py", line 335, in request
resp = self.send(prep, **send_kwargs)
File "/usr/lib64/python2.7/site-packages/requests/sessions.py", line 438, in send
r = adapter.send(request, **kwargs)
File "/usr/lib64/python2.7/site-packages/requests/adapters.py", line 327, in send
raise ConnectionError(e)

1 个答案:

答案 0 :(得分:5)

它无法从您的云服务器运行的原因是10. * IP范围是私有的,不可公开路由。

与192.168。*和172等相同。

您需要将10.44.11.33绑定到其他IP地址。一个可通过互联网访问。