Thi*_*vel 20 python client-server wsgi http uwsgi
我有一台服务器,需要几分钟时间来处理特定请求然后响应它.
客户端必须等待响应,而不知道何时完成.
有没有办法让客户知道处理状态?(比如50%完成,80%完成),客户不需要轮询状态.
D.N*_*bon 11
不使用任何新技术(websockets,webpush/http2,...),我之前使用过简化的Pushlet或Long轮询解决方案,用于HTTP 1.1和各种javascript或自己的客户端实现.如果我的解决方案不适合您的使用案例,您可以随时使用这两个名称来查找其他可能的方法.
客户端 发送请求,读取17个字节(Inital http响应),然后一次读取2个字节,获得处理状态.
服务器 发送有效的HTTP响应,并在请求进度期间发送完成2个字节的百分比,直到最后2个字节为"ok"并关闭连接.
更新:示例uwsgi server.py
from time import sleep
def application(env, start_response):
start_response('200 OK', [])
def working():
yield b'00'
sleep(1)
yield b'36'
sleep(1)
yield b'ok'
return working()
Run Code Online (Sandbox Code Playgroud)
更新:示例请求client.py
import requests
response = requests.get('http://localhost:8080/', stream=True)
for r in response.iter_content(chunk_size=2):
print(r)
Run Code Online (Sandbox Code Playgroud)
示例服务器(仅用于测试:)
import socket
from time import sleep
HOST, PORT = '', 8888
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(1)
while True:
client_connection, client_address = listen_socket.accept()
request = client_connection.recv(1024)
client_connection.send('HTTP/1.1 200 OK\n\n')
client_connection.send('00') # 0%
sleep(2) # Your work is done here
client_connection.send('36') # 36%
sleep(2) # Your work is done here
client_connection.sendall('ok') # done
client_connection.close()
Run Code Online (Sandbox Code Playgroud)
如果最后2个字节不是"ok",则在其他地方处理错误.这不是很好的HTTP状态代码合规性,而是多年前对我有用的解决方法.
telnet客户端示例
$ telnet localhost 8888
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
GET / HTTP/1.1
HTTP/1.1 200 OK
0036okConnection closed by foreign host.
Run Code Online (Sandbox Code Playgroud)