我在使用 aiohttp 框架进行 http 流式处理时遇到了一些问题。我是大多数基于网络的东西的新手,据我所知,这段代码应该提供一个带有嵌入式 javascript 的 html 页面,该页面将从后端接收到 console.log 块,但是我只是得到一个“GET http ://0.0.0.0:8200/subscribe net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 (OK)”错误出现在我的浏览器控制台中。我希望在设置 Nginx 服务器之前让它工作。
我的 aiohttp python 服务器:
from aiohttp import web
class webserver():
def __init__(self, webport):
self.webport = webport
self.start_web()
def start_web(self):
routes = web.RouteTableDef()
@routes.get('/')
async def index_handler(request):
return self.html_response('./index.html')
@routes.get('/subscribe')
async def subscribe(request):
"""Process incoming HTTP request."""
response = web.StreamResponse(headers={
'Content-Type' : 'text/event-stream'
})
# response.content_type = 'text/plain'
await response.prepare(request)
for _ in range(100):
bts = bytearray('line %d\n' % _, 'utf-8')
print(bts)
await response.write(bts)
await asyncio.sleep(1)
print('resp')
return response
self.app = web.Application()
self.app.add_routes(routes)
web.run_app(self.app, port=self.webport)
def html_response(self, document):
s = open(document, "r")
return web.Response(text=s.read(), content_type='text/html')
def main():
server = webserver(8200)
if __name__ == '__main__':
main()
这是我的带有嵌入式 javascript 的 html 页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Roomio</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="toggleButton" class="button">OFF</div>
<script>
const button = document.getElementById('toggleButton');
let isOn = false;
button.addEventListener('click', () => {
const source = new EventSource("/subscribe")
console.log("Hello1")
source.onmessage = (e) => {
console.log("Hello2")
console.log(`message: ${e.data}`)
};
console.log("Hello3")
isOn = !isOn;
button.textContent = isOn ? 'ON' : 'OFF';
document.body.style.backgroundColor = isOn ? '#2ECC40' : '#FF4136';
});
</script>
</body>
</html>
我已经运行了这段代码的几次不同的迭代,我的后端/订阅端点被命中了,我知道因为我的后端成功地打印出了循环值,但是在我的前端浏览器控制台上,我收到了一个周期性的错误消息 ERR_INCOMPLETE_CHUNKED_ENCODING 200(OK ) 以及 Hello1 和 Hello2 消息。我还通读了 here 和 here 中的 javascript 和 aiohttp 文档。提前感谢您的帮助。