在使用Flask-SocketIO制作WebSocket应用程序,结果程序启动失败

在使用Flask-SocketIO制作WebSocket应用程序,结果程序启动失败

问题描述:

  • 在使用Flask-SocketIO制作WebSocket的过程中,发现不安装eventlet模块是无法启用WebSocket的,只能使用Ajax轮询(Ajax Polling),占用服务器带宽。
  • 但是,经测试,安装eventlet之后程序不仅无法使用WebSocket,同时还启动不了。通过Flask-SocketIO官方Github提交Issue的Problems分类里的提示,在SocketIO的对象创建时传入两个参数(logger=True, engineio_logger=True),结果日志就这么一行:

Server initialized for eventlet.

  • 证明,错误不在eventlet上......求大佬解释一下这个情况......

代码主程序贴在这里:

# coding: utf-8

from flask import Flask, redirect, render_template, request

from flask_socketio import SocketIO # 连接

import requests

app = Flask("app")

io = SocketIO(app, logger=True, engineio_logger=True)

@app.route("/")

def index_redirect_handler():

return redirect("/ui")

@app.route("/ui")

def index_ui():

return render_template("index.html")

@app.route("/dl", methods=['POST'])

def index_download_file():

return render_template(

"download.html",

**request.form.to_dict()

).replace("__url__", request.form.get("url")) \

.replace("__path__", request.form.get("path"))

@io.on("download")

def download_file(data):

def upload_status(status):

io.emit("status", {

"status": status

})

return

response: requests.Response = requests.get(

url=data['url'],

stream=True,

headers={

"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/"

"537.36 (KHTML, like Gecko) Chrome/79.0.3282.204 Safari/537.36"

}

)

if response.status_code != 200:

io.emit(

"status_code",

{

"code": str(response.status_code)

}

)

io.stop()

return

size = 0

print(response.headers)

try:

content_size = float(response.headers['Content-Length'])

io.emit(

"file_size",

{

"size": str(content_size / 1024 / 1024) + "MB"

}

)

except KeyError:

content_size = None

io.emit(

"file_size",

{

"size": "unknown"

}

)

chunk_size = 1024

f = open(data['path'], "wb")

for data in response.iter_content(chunk_size=chunk_size):

size += len(data)

if content_size is not None:

upload_status("%f%%" % (size / content_size * 100))

f.write(data)

f.close()

io.emit("success")

return

# app.run("0.0.0.0", 8006)

# 使用io.run可以同时启用socketio服务端

io.run(app, "0.0.0.0", 8006)

以上是 在使用Flask-SocketIO制作WebSocket应用程序,结果程序启动失败 的全部内容, 来源链接: utcz.com/a/156512.html

回到顶部