python - Send intermittent status of request before sending actual response -
i have server, takes few minutes process specific request , responds it.
the client has keep waiting response without knowing when complete.
is there way let client know processing status? (say 50% completed, 80% completed), without client having poll status.
without using of newer techniques (websockets, webpush/http2, ...), i've used simplified pushlet or long polling solution http 1.1 , various javascript or own client implementation. if solution doesn't fit in use case, can google 2 names further possible ways.
client sends request, reads 17 bytes (inital http response) , reads 2 bytes @ time getting processing status.
server sends valid http response , during request progress sends 2 bytes of percentage completed, until last 2 bytes "ok" , closes connection.
updated: example uwsgi server.py
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()
updated: example requests client.py
import requests response = requests.get('http://localhost:8080/', stream=true) r in response.iter_content(chunk_size=2): print(r)
example server (only use testing :)
import socket 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) # work done here client_connection.send('36') # 36% sleep(2) # work done here client_connection.sendall('ok') # done client_connection.close()
if last 2 bytes aren't "ok", handle error someway else. isn't beautiful http status code compliance more of workaround did work me many years ago.
telnet client example
$ telnet localhost 8888 trying 127.0.0.1... connected localhost. escape character '^]'. / http/1.1 http/1.1 200 ok 0036okconnection closed foreign host.
Comments
Post a Comment