【问题标题】:Flask works locally, but not on a server?Flask 在本地工作,但不能在服务器上工作?
【发布时间】:2021-10-01 03:56:08
【问题描述】:

我正在开发一个 Flask 应用程序,目前它接受请求并回答它们。但是我在本地开发它并且它​​工作得很好,但是当尝试在repl.it上运行它时,它不起作用(请求引发“Winerror 10060”:

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond)

这是为什么呢? (我知道,repl.it 使用的 IP 与我在本地使用的不同,但我已经切换了它们。)

客户:

import json
import requests

conv = [{'id': 1, 'key': 'get_password'}]
payload = json.dumps(conv)
res = requests.post("http://127.0.0.1:5000", json=payload).json()
print(res)

服务器:

from flask import Flask, request
import json

app = Flask(__name__) 

@app.route('/', methods = ['POST'])
def home():
    jsondata = request.get_json()
    data = json.loads(jsondata)

    #stuff happens here that uses the data

    print(data)

    result = {'response': True}
    return json.dumps(result)


if __name__ == '__main__':
    app.run(host = "0.0.0.0", port = 5000)

【问题讨论】:

  • “它不起作用” 不是有用的错误描述。
  • 编辑了错误信息
  • 每次尝试发出请求时都会出错。如果没有,请检查您的互联网连接。也可以使用命名参数app.run(host"0.0.0.0", port=5000)
  • 是的,它确实给出了错误,我的互联网工作正常。我认为它可能是阻止连接的代理或防火墙(在 repl.it 上),但我不知道发生这种情况的情况。已编辑命名参数。

标签: python flask server client


【解决方案1】:

发生错误是因为您在地址 127.0.0.1 上发出请求,以防 repl.it 不使用该地址。

对 repl.it 提供的 url 发出请求。

网址将是:

https://your-app-name.your-replit-username.repl.co/

你的代码是

import json
import requests

conv = [{'id': 1, 'key': 'get_password'}]
payload = json.dumps(conv)
res = requests.post("https://moneyserver.jgroeger.repl.co/", json=payload).json()
print(res)

【讨论】:

  • 谢谢,我现在可以建立连接了。但是现在client.py 在删除.json() res = requests.post("https://address.example/", json=payload) 后给出:<Response:[404]>
  • 为什么你删除了.json() 你也可以查看 repl.it 中的日志,看看发生了什么以及为什么它给出了 404 错误。我不知道是否会导致错误,但请尝试在最后的 url 中添加额外的斜杠。 https://your-app-name.your-replit-username.repl.co/
  • 我删除了.json(),因为client.py 给了json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) in line:res = requests.post("https://moneyserver.jgroeger.repl.co/:5000", data=payload).json()
  • 你为什么用:5000那里没必要用。这肯定会给你 404 错误。你的地址应该只有这个https://moneyserver.jgroeger.repl.co/
  • 我认为误以为您有上面指向您的 repl 的链接,所以我尝试发出相同的请求,并且能够获得结果而没有任何错误。我用我使用的整个代码编辑了答案。
猜你喜欢
  • 2012-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-08
  • 2020-01-25
  • 2023-01-02
  • 1970-01-01
  • 2017-02-22
相关资源
最近更新 更多