首页 > 解决方案 > 向本地主机发送 HTTP 请求

问题描述

我正在用 Flask 构建一个 Rest API。该 API 使用来自在 localhost 上运行的 Elasticsearch 的数据。

可以从 Flask 路由向 localhost 发送 HTTP 请求吗?

像这样的东西:

@flashlog.route('/checkelasticisup')
def check_elastic_is_up():
    res = requests.get('http://localhost:9200/')
    return jsonify({'message': res.text})

我想将您在向 localhost:9200 发送 GET 请求时获得的 Elasticsearch 响应返回给客户端:

{
  "name": "wEV_Spx",
  "cluster_name": "elasticsearch",
  "cluster_uuid": "dbPLLgYLRO69iYuT_pp4WA",
  "version": {
    "number": "6.3.0",
    "build_flavor": "default",
    "build_type": "deb",
    "build_hash": "424e937",
    "build_date": "2018-06-11T23:38:03.357887Z",
    "build_snapshot": false,
    "lucene_version": "7.3.1",
    "minimum_wire_compatibility_version": "5.6.0",
    "minimum_index_compatibility_version": "5.0.0"
  },
  "tagline": "You Know, for Search"
}

现在,我得到:

网络错误 (dns_unresolved_hostname)

<HTML><HEAD>
<TITLE>Network Error</TITLE>
</HEAD>
<BODY>
<FONT face="Helvetica">
<big><strong></strong></big><BR>
</FONT>
<blockquote>
<TABLE border=0 cellPadding=1 width="80%">
<TR><TD>
<FONT face="Helvetica">
<big>Network Error (dns_unresolved_hostname)</big>
<BR>
<BR>
</FONT>
</TD></TR>
<TR><TD>
<FONT face="Helvetica">
Your requested host "localhost" could not be resolved by DNS.
</FONT>
</TD></TR>
<TR><TD>
<FONT face="Helvetica">

</FONT>
</TD></TR>
<TR><TD>
<FONT face="Helvetica" SIZE=2>
<BR>
For assistance, contact your network support team.
</FONT>
</TD></TR>
</TABLE>
</blockquote>
</FONT>
</BODY></HTML>

如何向 localhost 发送 HTTP 请求(我使用的是 Ubuntu 18.04 LTS)?
谢谢!!

标签: pythonhttpelasticsearchflaskubuntu-18.04

解决方案


正如@Metalik 所说,您必须替换localhost127.0.0.1才能使其正常工作。


推荐阅读