DEV Community 👩‍💻👨‍💻

codemee
codemee

Posted on

使用 urequests 請記得關閉連線釋放佔用的資源

在 MicroPython 中要使用 http 協定存取網路服務, 最簡單的方式就是藉助內建的 urequests 模組, 一般的使用情境大概會是這樣:

import network
import urequests

# 連線至無線網路
sta=network.WLAN(network.STA_IF)
sta.active(True)   
sta.connect('FLAG-SCHOOL','12345678')

while not sta.isconnected() :
    pass

print('Wi-Fi connected.')

res = urequests.get("https://flagtech.github.io/flag.txt")
if(res.status_code == 200):
    print("Success.")
else:
    print("Oops.")
Enter fullscreen mode Exit fullscreen mode

不過您可能沒有注意到的是到上面的寫法 get 並沒有完成, 而是只接收到 http 回應的表頭而以, 也就是說整個連線還佔著。如果我們會重複進行 get, 像是以下這樣的極端狀況:

import network
import urequests
import time

# 連線至無線網路
sta=network.WLAN(network.STA_IF)
sta.active(True)   
sta.connect('FLAG-SCHOOL','12345678')

while not sta.isconnected() :
    pass

print('Wi-Fi connected.')

while True:
    res = urequests.get("https://flagtech.github.io/flag.txt")
    if(res.status_code == 200):
        print("Success.")
Enter fullscreen mode Exit fullscreen mode

執行後很可能就會很快出錯:

>>> %Run -c $EDITOR_CONTENT
Wi-Fi connected.
Success.
Success.
Traceback (most recent call last):
  File "<stdin>", line 16, in <module>
  File "urequests.py", line 116, in get
  File "urequests.py", line 55, in request
OSError: -2
Enter fullscreen mode Exit fullscreen mode

才兩次 get 就掛了。

Response.content 才會關閉連線

如果你看 ureqests 模組的原始碼, 就會發現你必須取用 Response 物件的 content 屬性, 才會接續收取從伺服器送來跟在表頭後面的內容, 並且關閉連線。取用 Response.text 或是 Responses.json 屬性都會連帶取用 Response.content。因此, 最好的作法就是取用上述這些屬性, 完成整個 http 傳輸過程。如果你並不需要取得伺服器送來的內容, 也可以暴力一點, 直接叫用 Response.close() 關閉連線:

import network
import urequests
import time

# 連線至無線網路
sta=network.WLAN(network.STA_IF)
sta.active(True)   
sta.connect('FLAG-SCHOOL','12345678')

while not sta.isconnected() :
    pass

print('Wi-Fi connected.')

while True:
    res = urequests.get("https://flagtech.github.io/flag.txt")
    if(res.status_code == 200):
        res.close() # 或是 txt = res.text 也可以
        print("Success.")
Enter fullscreen mode Exit fullscreen mode

現在就可以正常一直 get 了:

>>> %Run -c $EDITOR_CONTENT
Wi-Fi connected.
Success.
Success.
Success.
Success.
Success.
Success.
Success.
...
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.