DEV Community

codemee
codemee

Posted on

1 1

讓 MicroPython 的 urequests 模組支援 redirection

如果你使用 MicroPython 的 urequests 模組, 可能會遇到連到某個網址 (例如:(http://flagtech.github.io/flag.txt) 時無法得到正確的結果, 看到這樣的錯誤訊息:

Traceback (most recent call last):
  File "<stdin>", line 10, in <module>
  File "urequests.py", line 108, in get
  File "urequests.py", line 93, in request
NotImplementedError: Redirects not yet supported
Enter fullscreen mode Exit fullscreen mode

這表示該網站希望你改連到另一個網址, 我們使用 curl 工具來觀察就會比較清楚:

❯ curl -i http://flagtech.github.io/flag.txt
HTTP/1.1 301 Moved Permanently
Server: GitHub.com
Content-Type: text/html
permissions-policy: interest-cohort=()
Location: https://flagtech.github.io/flag.txt
X-GitHub-Request-Id: C080:3BB1:18E42:225BC:60A36DC0
...
Enter fullscreen mode Exit fullscreen mode

你可以看到伺服器回應的是 301, 表示該網址已經永久搬遷了, 底下的 Location 項目就告訴我們搬到哪裡去?原來這只是 github 導引使用 http 協定的用戶端要改用 https 的機制。如果是瀏覽器, 看到這樣的回應就會自動重新送一次請求, 改連到 Location 指定的位置, curl 工具則可以指定 -L 選項自動轉址:

❯ curl -L http://flagtech.github.io/flag.txt
FLAG
  ______ _               _____
 |  ____| |        /\   / ____|
 | |__  | |       /  \ | |  __
 |  __| | |      / /\ \| | |_ |
 | |    | |____ / ____ \ |__| |
 |_|    |______/_/    \_\_____|
Enter fullscreen mode Exit fullscreen mode

不過 MicroPython 的 urequests 模組看到 3XX 的回應以及 Location 表頭項目時就會停止運作, 引發 "NotImplementedError" 例外。為了解決這個問題, 我修改了一個 urequests 的版本, 讓他在這種狀況下可以自動轉址到伺服器指定的地方, 這個版本的模組可以在這裡下載, 使用方法都和 urequests 一樣, 例如:

import network
import urequests_alt

sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect('無線網路名稱', '無線網路密碼')
while not sta.isconnected():
    pass

r = urequests_alt.get('http://flagtech.github.io/flag.txt')
print(r.status_code)
print(r.text)

Enter fullscreen mode Exit fullscreen mode

執行後就可以自動轉址取得正確的內容:

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay