在 Heroku 上部署 Flask Websockets 应用程序时遇到问题
Posted
技术标签:
【中文标题】在 Heroku 上部署 Flask Websockets 应用程序时遇到问题【英文标题】:Trouble deploying a Flask Websockets App on Heroku 【发布时间】:2017-01-18 00:46:55 【问题描述】:我编写了一个使用 websockets 的 Flask 应用程序,它对我来说运行良好本地。
但是当我尝试通过 Heroku 部署它并在浏览器中打开它时,我收到以下错误:
在 Chrome 中:WebSocket connection to 'wss://flask-realtime-chat-app.herokuapp.com/chat' failed: Error during WebSocket handshake: Unexpected response code: 404
。
在 Firefox 中:Firefox can’t establish a connection to the server at ws://flask-realtime-chat-app.herokuapp.com/chat.
以下是我的代码的相关部分:
import json
from flask import Flask, send_from_directory, request
from flask_sockets import Sockets
app = Flask(__name__)
sockets = Sockets(app)
@app.route("/")
def index():
return send_static("index.html")
@app.route("/static/<path>")
def send_static(path):
return send_from_directory("../client/static", path)
connections = []
messages = []
usernames =
@sockets.route("/chat")
def chat_socket(web_socket):
global connections, usernames
connections = add_socket(web_socket, connections)
while not web_socket.closed:
data = json.loads(web_socket.receive())
connections = remove_closed_sockets(connections)
messages.append(data)
json_message = json.dumps(data)
send_message(json_message, connections)
def add_socket(web_socket, connections):
return connections + [web_socket]
def remove_closed_sockets(connections):
return [c for c in connections if not c.closed]
def send_message(message, connections):
for socket in connections:
socket.send(message)
if __name__ == "__main__":
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
server = pywsgi.WSGIServer(('', 5000), app, handler_class=WebSocketHandler)
server.serve_forever()
前端:
if (window.location.protocol == "https:")
var ws_scheme = "wss://";
else
var ws_scheme = "ws://";
var socket = new WebSocket(ws_scheme + location.host + "/chat");
socket.onopen = function (event)
console.log("Websocket open!");
socket.onclose = function (event)
console.log("Websocket closed!");
socket.onmessage = function (event)
var incomingMessage = JSON.parse(event.data);
if (incomingMessage["message"])
addMessageToChatScreen(incomingMessage);
else if (incomingMessage["usernames"])
usernames = incomingMessage["usernames"];
...
function sendMessage()
var data = JSON.stringify(
uid: uid,
message: $("#message_input").val()
);
socket.send(data);
$("#message_input").val("");
任何建议将不胜感激!
【问题讨论】:
【参考方案1】:在 procfile 中提供一个工人类。这里我使用了eventlet。
web: gunicorn --worker-class eventlet -w 1 --pythonpath app:app
【讨论】:
以上是关于在 Heroku 上部署 Flask Websockets 应用程序时遇到问题的主要内容,如果未能解决你的问题,请参考以下文章
在已部署的 Flask 应用程序 (Heroku) 上使用 OpenCV
使用flask在heroku bert pytorch模型上部署:错误:_pickle.UnpicklingError:无效的加载键,'v'
由于 Error=H10,Flask App 在通过 Heroku 部署时导致应用程序错误
Python Flask(部署在 Heroku 上):ImportError: cannot import name 'secure_filename' from 'werkzeug' when de