4

以下のコードに示すように、要求ライブラリを使用して XML イベントを読み取っています。リクエストが開始されたら、接続が失われたというエラーを発生させるにはどうすればよいですか? サーバーは HTTP プッシュ/ロング ポーリングをエミュレートしています -> http://en.wikipedia.org/wiki/Push_technology#Long_pollingであり、デフォルトでは終了しません。10 分経過しても新しいメッセージがない場合は、while ループを終了する必要があります。

import requests
from time import time


if __name__ == '__main__':
    #: Set a default content-length
    content_length = 512
    try:
        requests_stream = requests.get('http://agent.mtconnect.org:80/sample?interval=0', stream=True, timeout=2)
        while True:
            start_time = time()
            #: Read three lines to determine the content-length         
            for line in requests_stream.iter_lines(3, decode_unicode=None):
                if line.startswith('Content-length'):
                    content_length = int(''.join(x for x in line if x.isdigit()))
                    #: pause the generator
                    break

            #: Continue the generator and read the exact amount of the body.        
            for xml in requests_stream.iter_content(content_length):
                print "Received XML document with content length of %s in %s seconds" % (len(xml), time() - start_time)
                break

    except requests.exceptions.RequestException as e:
        print('error: ', e)

サーバー プッシュは、コマンド ライン経由で curl を使用してテストできます。

curl http://agent.mtconnect.org:80/sample\?interval\=0
4

1 に答える 1