![](/img/trans.png)
[英]Python : http.server.HTTPServer : How to close ALL opened files?
[英]Is closing http.server.HTTPServer guaranteed to be thread-safe?
from http.server import HTTPServer, SimpleHTTPRequestHandler
import threading
with HTTPServer(("localhost", 8080), SimpleHTTPRequestHandler) as httpd:
threading.Thread(target=httpd.serve_forever, daemon=True).start()
# Do something ...
當程序退出with
塊時,是否保證httpd
正確關閉? 例如,如果httpd
在代碼到達with
塊的末尾時正在傳輸數據,那么該連接是否會被正確切斷(或等待它完成)?
我的理解是ThreadingHTTPServer
應該正確處理這些,因為文檔說:
socketserver.ThreadingMixIn.server_close()
等待所有非守護線程完成,除非socketserver.ThreadingMixIn.block_on_close
屬性為 false。 通過將ThreadingMixIn.daemon_threads
設置為 True 以不等到線程完成來使用守護線程。
但是我想看看Python最基本的內置http服務器HTTPServer
是否也能正確處理這個問題。
http.server.HTTPServer
是socketserver.BaseServer
的子類。TCPServer 是socketserver.TCPServer
的子類。 在BaseServer
中定義.serve_forever
。 在這里,在不同的線程中關閉.serve_forever
的正確方法是調用.shutdown()
。 這是您在with
語句結束之前應該做的事情。
現在回答您提出的問題:當您不調用.shutdown()
時, serve_forever
會做什么? 好吧,我不確定。 __exit__
function 僅關閉套接字,不進行任何清理。 The answer appears to be 'Whatever your OSes implementation of select.select
does when it has no sockets to select over.' 這是什么? 顯然,在 Unix 上就像什么都沒發生一樣繼續,在 Windows 上引發異常? 這意味着在 Unix 上,服務器將永遠繼續服務,而在 Windows 上它將引發異常。 (請注意,我對此不確定。只需.shutdown()
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.