99精品伊人亚洲|最近国产中文炮友|九草在线视频支援|AV网站大全最新|美女黄片免费观看|国产精品资源视频|精彩无码视频一区|91大神在线后入|伊人终合在线播放|久草综合久久中文

0
  • 聊天消息
  • 系統(tǒng)消息
  • 評(píng)論與回復(fù)
登錄后你可以
  • 下載海量資料
  • 學(xué)習(xí)在線課程
  • 觀看技術(shù)視頻
  • 寫文章/發(fā)帖/加入社區(qū)
會(huì)員中心
創(chuàng)作中心

完善資料讓更多小伙伴認(rèn)識(shí)你,還能領(lǐng)取20積分哦,立即完善>

3天內(nèi)不再提示

如何使用Twitter API從特定用戶獲取推文

454398 ? 來源:網(wǎng)絡(luò)整理 ? 作者:網(wǎng)絡(luò)整理 ? 2019-11-29 16:31 ? 次閱讀
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

概述

此指南顯示了如何使用Twitter API從特定用戶獲取推文(但是您可以做很多事情)。舉一個(gè)具體的例子,它將用于定期從@codewisdom獲取最新的tweet,這是一個(gè)tweet來自軟件行業(yè)的引用的feed。我們將獲取這些推文,并將其顯示在PyPortal上。

Adafruit PyPortal-CircuitPython Powered Internet Display

產(chǎn)品ID:4116

PyPortal是我們易于使用的IoT設(shè)備,可讓您在數(shù)分鐘內(nèi)為“物聯(lián)網(wǎng)”創(chuàng)建所有東西。制作自定義觸摸屏界面。..

$ 54.95

進(jìn)貨

添加到購物車

粉紅色和紫色編織USB A至Micro B電纜-2米長

產(chǎn)品ID:4148

這條電纜具有粉紅色和紫色Blinka編織圖案,非常適合用于時(shí)尚!首先,我們來談?wù)劯采w層和包覆成型。我們將這些顏色制成自定義顏色,。..

$ 3.95

入庫存

添加到購物車

其他工具和材料

您可能想為PyPortal事件倒計(jì)時(shí)時(shí)鐘創(chuàng)建可選的桌面支架。為此,您需要:

3D打印機(jī)

細(xì)絲

PyPortal支架模型文件

M3支腳和螺釘

如果您無權(quán)使用3D打印機(jī),則可以選擇使用在線服務(wù)(例如3D集線器)按需為您打印。

電路場螺栓固定套件

產(chǎn)品ID:3816

您有Circuit Playground Express,但您需要將其安裝到迷人的紙板機(jī)器人朋友身上,是嗎?如果您。..

$ 3.95

進(jìn)貨

添加到購物車

安裝CircuitPython

CircuitPython是MicroPython的派生版,旨在簡化低成本微控制器上的實(shí)驗(yàn)和教學(xué)。它不需要任何前期桌面軟件下載,因此比以往任何時(shí)候都更容易獲得原型。只需復(fù)制并編輯 CIRCUITPY “閃存”驅(qū)動(dòng)器上的文件即可進(jìn)行迭代。

以下說明將向您展示如何安裝CircuitPython。如果您已經(jīng)安裝了CircuitPython,但希望對(duì)其進(jìn)行更新或重新安裝,則同樣的步驟也適用!

設(shè)置CircuitPython快速入門!

請(qǐng)遵循以下快速逐步操作以獲取超快速的Python功能:)

通過CircuitPython.org為該板下載最新版本的CircuitPython

點(diǎn)擊上面的鏈接,為PyPortal下載最新版本的CircuitPython。

下載并將其保存到您的桌面(或方便的任何地方)。

使用已知良好的USB電纜將PyPortal插入計(jì)算機(jī)。

A很多人最終使用僅可充電的USB電纜,這非常令人沮喪!因此,請(qǐng)確保您擁有知道對(duì)數(shù)據(jù)同步有用的USB電纜。

雙擊中間頂部頂部的重置按鈕(洋紅色箭頭)在板上,您將看到NeoPixel RGB LED(綠色箭頭)變?yōu)榫G色。如果它變成紅色,請(qǐng)檢查USB電纜,嘗試使用另一個(gè)USB端口,等等。注意:USB接口旁邊的紅色小LED指示燈將呈紅色閃爍。沒關(guān)系!

如果第一次雙擊不起作用,請(qǐng)重試。有時(shí)可能需要一些嘗試才能使節(jié)奏正確!

您將看到一個(gè)名為 PORTALBOOT 。

將 adafruit-circuitpython-pyportal- .uf2 文件拖到 PORTALBOOT。

LED將閃爍。然后, PORTALBOOT 驅(qū)動(dòng)器將消失,并且將出現(xiàn)一個(gè)名為 CIRCUITPY 的新磁盤驅(qū)動(dòng)器。

如果未在板上添加任何代碼,唯一存在的文件是 boot_out.txt 。這是絕對(duì)正常的!是時(shí)候添加您的 code.py 并開始使用它了!

就這樣,您完成了! :)

PyPortal默認(rèn)文件

單擊下面的按鈕,下載PyPortal附帶的文件的zip。

PyPortal默認(rèn)文件

PyPortal CircuitPython設(shè)置

要在CircuitPython中使用PyPortal的所有出色功能,必須首先安裝許多庫。本頁涵蓋了該過程。

Adafruit CircuitPython捆綁包

下載Adafruit CircuitPython庫捆綁包。您可以在此處找到最新版本:

最新的Adafruit CircuitPython庫包

下載 adafruit-circuitpython-bundle-4。 x-mpy-*。zip 捆綁zip文件,然后解壓縮同名文件夾。在內(nèi)部,您會(huì)找到一個(gè) lib 文件夾。您有兩個(gè)選擇:

您可以將 lib 文件夾添加到您的 CIRCUITPY 驅(qū)動(dòng)器中。這將確保您擁有所有驅(qū)動(dòng)程序。但是這將占用8 MB磁盤上的一堆空間

根據(jù)需要添加每個(gè)庫,這將減少空間使用量,但您需要

至少,我們推薦以下庫,實(shí)際上我們比推薦的要多。基本上是必需的。因此,立即抓住它們并將它們安裝到 CIRCUITPY/lib !

adafruit_esp32spi -這是一個(gè)庫,可通過ESP32進(jìn)行互聯(lián)網(wǎng)訪問使用(您猜對(duì)了?。㏒PI傳輸。 Internet所需的任何東西都需要使用它

adafruit_requests -該庫使我們能夠執(zhí)行HTTP請(qǐng)求并從服務(wù)器獲取響應(yīng)。 GET/POST/PUT/PATCH-它們都在這里!

adafruit_pyportal -這是我們友好的包裝器庫,可處理很多項(xiàng)目,顯示圖形和文本,從互聯(lián)網(wǎng)上獲取數(shù)據(jù)。

adafruit_touchscreen -一個(gè)用于從電阻式觸摸屏讀取觸摸的庫。

adafruit_cursorcontrol -用于讀取PyGamer和PyBadge游戲桿和按鈕的庫。為您處理所有圖形,按鈕閱讀和操縱桿移動(dòng)。

adafruit_io -該庫有助于將PyPortal連接到我們的免費(fèi)數(shù)據(jù)記錄和查看服務(wù)

adafruit_imageload -任何圖形所需的圖像顯示助手!

adafruit_display_text -毫不奇怪,它在屏幕上顯示文本

adafruit_bitmap_font -我們擁有精美的字體支持,并且易于制作新字體。該庫讀取并解析字體文件。

adafruit_slideshow -用于制作圖像幻燈片-方便快速顯示圖形和聲音

neopixel -用于控制板載新像素

adafruit_adt7410 -用于從板載Analog Devices ADT7410精密溫度傳感器讀取溫度的庫

adafruit_sdcard -支持從板載SD卡插槽中讀取/寫入數(shù)據(jù)。

adafruit_bus_device -對(duì)I2C/SPI的低級(jí)支持

Internet連接!

一旦您安裝了CircuitPython安裝程序和庫,我們就可以將您的電路板連接到Internet。請(qǐng)注意,目前不支持訪問企業(yè)級(jí)安全的WiFi網(wǎng)絡(luò),僅支持需要SSID和密碼的WiFi網(wǎng)絡(luò)。

要建立連接,您需要先創(chuàng)建一個(gè)秘密文件。

什么是機(jī)密文件?

我們希望人們?cè)跇?gòu)建CircuitPython WiFi小部件時(shí)共享大量項(xiàng)目。我們要避免的是人們不小心共享了他們的密碼或秘密令牌和API密鑰。因此,我們?cè)O(shè)計(jì)了所有示例,以使用 CIRCUITPY 驅(qū)動(dòng)器中的secrets.py文件來保存秘密/私有/自定義數(shù)據(jù)。這樣,您就可以共享您的主項(xiàng)目,而不必?fù)?dān)心意外共享私有內(nèi)容。

您的 secrets.py 文件應(yīng)如下所示:

下載:文件

復(fù)制代碼

# This file is where you keep secret settings, passwords, and tokens!

# If you put them in the code you risk committing that info or sharing it

secrets = {

‘ssid’ : ‘home ssid’,

‘password’ : ‘my password’,

‘timezone’ : “America/New_York”, # http://worldtimeapi.org/timezones

‘github_token’ : ‘fawfj23rakjnfawiefa’,

‘hackaday_token’ : ‘h4xx0rs3kret’,

}

# This file is where you keep secret settings, passwords, and tokens!

# If you put them in the code you risk committing that info or sharing it

secrets = {

‘ssid’ : ‘home ssid’,

‘password’ : ‘my password’,

‘timezone’ : “America/New_York”, # http://worldtimeapi.org/timezones

‘github_token’ : ‘fawfj23rakjnfawiefa’,

‘hackaday_token’ : ‘h4xx0rs3kret’,

}

Inside是一個(gè)名為secrets的python字典,每個(gè)條目都有一行。每個(gè)條目都有一個(gè)條目名稱(例如‘ssid’),然后是一個(gè)冒號(hào)以將其與條目鍵‘home ssid’分開,最后是一個(gè)逗號(hào),

至少您需要ssid和password用于您的本地WiFi設(shè)置。在創(chuàng)建項(xiàng)目時(shí),您可能需要更多的令牌和密鑰,只需一次添加一行即可。例如,請(qǐng)參見其他令牌,例如用于訪問github或hackaday API的令牌。其他非機(jī)密數(shù)據(jù)(例如您的時(shí)區(qū))也可以在此處,僅因?yàn)槠浞Q為機(jī)密的信息并不意味著您不能在其中包含常規(guī)的自定義數(shù)據(jù)!

有關(guān)正確的時(shí)區(qū)字符串,請(qǐng)查看http://worldtimeapi.org/timezones,請(qǐng)記住,如果未列出您的城市,請(qǐng)?jiān)谕粫r(shí)區(qū)中查找城市,例如,波士頓,紐約,費(fèi)城,華盛頓特區(qū)和邁阿密都與紐約位于同一時(shí)間。

當(dāng)然,不要共享您的 secrets.py -將其保存在GitHub,Discord或其他項(xiàng)目共享站點(diǎn)之外。

連接到WiFi

好,現(xiàn)在您已設(shè)置好機(jī)密-您可以連接到Internet。讓我們使用ESP32SPI和Requests庫-您需要訪問CircuitPython捆綁包并安裝:

adafruit_bus_device

adafruit_esp32spi

adafruit_requests

neopixel

進(jìn)入您的lib文件夾。完成后,使用Mu或您喜歡的編輯器加載以下示例:

下載:項(xiàng)目郵編或 esp32spi_simpletest.py | 在Github上查看

復(fù)制代碼

import board

import busio

from digitalio import DigitalInOut

import adafruit_esp32spi.adafruit_esp32spi_socket as socket

from adafruit_esp32spi import adafruit_esp32spi

import adafruit_requests as requests

print(“ESP32 SPI webclient test”)

TEXT_URL = “http://wifitest.adafruit.com/testwifi/index.html”

JSON_URL = “http://api.coindesk.com/v1/bpi/currentprice/USD.json”

# If you are using a board with pre-defined ESP32 Pins:

esp32_cs = DigitalInOut(board.ESP_CS)

esp32_ready = DigitalInOut(board.ESP_BUSY)

esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:

# esp32_cs = DigitalInOut(board.D9)

# esp32_ready = DigitalInOut(board.D10)

# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

requests.set_socket(socket, esp)

if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:

print(“ESP32 found and in idle mode”)

print(“Firmware vers.”, esp.firmware_version)

print(“MAC addr:”, [hex(i) for i in esp.MAC_address])

for ap in esp.scan_networks():

print(“ %s RSSI: %d” % (str(ap[‘ssid’], ‘utf-8’), ap[‘rssi’]))

print(“Connecting to AP.。.”)

while not esp.is_connected:

try:

esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)

except RuntimeError as e:

print(“could not connect to AP, retrying: ”,e)

continue

print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)

print(“My IP address is”, esp.pretty_ip(esp.ip_address))

print(“IP lookup adafruit.com: %s” % esp.pretty_ip(esp.get_host_by_name(“adafruit.com”)))

print(“Ping google.com: %d ms” % esp.ping(“google.com”))

#esp._debug = True

print(“Fetching text from”, TEXT_URL)

r = requests.get(TEXT_URL)

print(‘-’*40)

print(r.text)

print(‘-’*40)

r.close()

print()

print(“Fetching json from”, JSON_URL)

r = requests.get(JSON_URL)

print(‘-’*40)

print(r.json())

print(‘-’*40)

r.close()

print(“Done!”)

import board

import busio

from digitalio import DigitalInOut

import adafruit_esp32spi.adafruit_esp32spi_socket as socket

from adafruit_esp32spi import adafruit_esp32spi

import adafruit_requests as requests

print(“ESP32 SPI webclient test”)

TEXT_URL = “http://wifitest.adafruit.com/testwifi/index.html”

JSON_URL = “http://api.coindesk.com/v1/bpi/currentprice/USD.json”

# If you are using a board with pre-defined ESP32 Pins:

esp32_cs = DigitalInOut(board.ESP_CS)

esp32_ready = DigitalInOut(board.ESP_BUSY)

esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:

# esp32_cs = DigitalInOut(board.D9)

# esp32_ready = DigitalInOut(board.D10)

# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

requests.set_socket(socket, esp)

if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:

print(“ESP32 found and in idle mode”)

print(“Firmware vers.”, esp.firmware_version)

print(“MAC addr:”, [hex(i) for i in esp.MAC_address])

for ap in esp.scan_networks():

print(“ %s RSSI: %d” % (str(ap[‘ssid’], ‘utf-8’), ap[‘rssi’]))

print(“Connecting to AP.。.”)

while not esp.is_connected:

try:

esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)

except RuntimeError as e:

print(“could not connect to AP, retrying: ”,e)

continue

print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)

print(“My IP address is”, esp.pretty_ip(esp.ip_address))

print(“IP lookup adafruit.com: %s” % esp.pretty_ip(esp.get_host_by_name(“adafruit.com”)))

print(“Ping google.com: %d ms” % esp.ping(“google.com”))

#esp._debug = True

print(“Fetching text from”, TEXT_URL)

r = requests.get(TEXT_URL)

print(‘-’*40)

print(r.text)

print(‘-’*40)

r.close()

print()

print(“Fetching json from”, JSON_URL)

r = requests.get(JSON_URL)

print(‘-’*40)

print(r.json())

print(‘-’*40)

r.close()

print(“Done!”)

,并將其保存到您的板上,名稱為code.py。

第一個(gè)連接示例不使用機(jī)密文件-您將首先輸入SSID/密碼來驗(yàn)證連接性!

然后轉(zhuǎn)到此行

esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)

并更改MY_SSID_NAME和 MY_SSID_PASSWORD 設(shè)置為您的訪問點(diǎn)名稱和密碼,并將其保留在‘’引號(hào)內(nèi)。 (此示例不使用機(jī)密文件,但它也非常獨(dú)立,因此,如果其他事情似乎不起作用,則可以始終重新加載該文件。您應(yīng)該獲得如下內(nèi)容:

示例代碼。..

使用SPI端口和3個(gè)控制引腳通過SPI初始化ESP32:

下載:文件

復(fù)制代碼

esp32_cs = DigitalInOut(board.ESP_CS)

esp32_ready = DigitalInOut(board.ESP_BUSY)

esp32_reset = DigitalInOut(board.ESP_RESET)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) esp32_cs = DigitalInOut(board.ESP_CS)

esp32_ready = DigitalInOut(board.ESP_BUSY)

esp32_reset = DigitalInOut(board.ESP_RESET)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

告訴我們的requests庫我們正在使用的套接字的類型(套接字類型隨連接類型而變化-在此示例中,我們將使用adafruit_esp32spi_socket)。還將接口設(shè)置為

下載:文件

復(fù)制代碼

esp requests

驗(yàn)證找到ESP32,檢查固件和MAC地址

下載:文件

復(fù)制代碼

requests.set_socket(socket, esp) requests.set_socket(socket, esp)

掃描它可以看到的所有訪問點(diǎn),并打印出名稱和信號(hào)強(qiáng)度:

下載:文件

復(fù)制代碼

if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:

print(“ESP32 found and in idle mode”)

print(“Firmware vers.”, esp.firmware_version)

print(“MAC addr:”, [hex(i) for i in esp.MAC_address]) if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:

print(“ESP32 found and in idle mode”)

print(“Firmware vers.”, esp.firmware_version)

print(“MAC addr:”, [hex(i) for i in esp.MAC_address])

連接到我們?cè)诖颂幎x的AP,然后打印出來本地IP地址,嘗試進(jìn)行域名查找并ping google.com以檢查網(wǎng)絡(luò)連接(請(qǐng)注意,有時(shí)ping失敗或需要一段時(shí)間,這沒什么大不了的)

下載:文件

復(fù)制代碼

for ap in esp.scan_networks():

print(“ %s RSSI: %d” % (str(ap[‘ssid’], ‘utf-8’), ap[‘rssi’])) for ap in esp.scan_networks():

print(“ %s RSSI: %d” % (str(ap[‘ssid’], ‘utf-8’), ap[‘rssi’]))

好的,現(xiàn)在我們進(jìn)入真正有趣的部分。使用SAMD51或其他大容量RAM(超過32 KB)設(shè)備,我們可以做很多巧妙的事情。例如,我們可以像請(qǐng)求一樣實(shí)現(xiàn)一個(gè)接口,這使得獲取數(shù)據(jù)非常簡單

從Web URL調(diào)用 print(“Connecting to AP.。.”)

esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)

print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)

print(“My IP address is”, esp.pretty_ip(esp.ip_address))

print(“IP lookup adafruit.com: %s” % esp.pretty_ip(esp.get_host_by_name(“adafruit.com”)))

print(“Ping google.com: %d ms” % esp.ping(“google.com”))

中讀取所有文本-您可以傳入 print(“Connecting to AP.。.”)

esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)

print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)

print(“My IP address is”, esp.pretty_ip(esp.ip_address))

print(“IP lookup adafruit.com: %s” % esp.pretty_ip(esp.get_host_by_name(“adafruit.com”)))

print(“Ping google.com: %d ms” % esp.ping(“google.com”))

用于SSL連接的URL

下載:文件

復(fù)制代碼

requests.get https

或者,如果數(shù)據(jù)使用結(jié)構(gòu)化JSON,則可以獲取json pre -解析為可以輕松查詢或遍歷的Python字典。 (同樣,僅適用于nRF52840,M4和其他高RAM板)

下載:文件

復(fù)制代碼

TEXT_URL = “http://wifitest.adafruit.com/testwifi/index.html”

print(“Fetching text from”, TEXT_URL)

r = requests.get(TEXT_URL)

print(‘-’*40)

print(r.text)

print(‘-’*40)

r.close() TEXT_URL = “http://wifitest.adafruit.com/testwifi/index.html”

print(“Fetching text from”, TEXT_URL)

r = requests.get(TEXT_URL)

print(‘-’*40)

print(r.text)

print(‘-’*40)

r.close()

Requests

我們已經(jīng)為Web接口編寫了一個(gè)類似請(qǐng)求的庫,名為Adafruit_CircuitPython_Requests。該庫允許您發(fā)送HTTP/1.1請(qǐng)求,而無需“設(shè)計(jì)”它們,并提供了有用的方法來解析服務(wù)器的響應(yīng)。

下載:Project Zip 或 requests_simpletest.py | 在Github上查看

復(fù)制代碼

JSON_URL = “http://api.coindesk.com/v1/bpi/currentprice/USD.json”

print(“Fetching json from”, JSON_URL)

r = requests.get(JSON_URL)

print(‘-’*40)

print(r.json())

print(‘-’*40)

r.close() JSON_URL = “http://api.coindesk.com/v1/bpi/currentprice/USD.json”

print(“Fetching json from”, JSON_URL)

r = requests.get(JSON_URL)

print(‘-’*40)

print(r.json())

print(‘-’*40)

r.close()

代碼首先設(shè)置ESP32SPI接口。然后,它使用ESP32 # adafruit_requests usage with an esp32spi_socket

import board

import busio

from digitalio import DigitalInOut

import adafruit_esp32spi.adafruit_esp32spi_socket as socket

from adafruit_esp32spi import adafruit_esp32spi

import adafruit_requests as requests

# If you are using a board with pre-defined ESP32 Pins:

esp32_cs = DigitalInOut(board.ESP_CS)

esp32_ready = DigitalInOut(board.ESP_BUSY)

esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:

# esp32_cs = DigitalInOut(board.D9)

# esp32_ready = DigitalInOut(board.D10)

# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

print(“Connecting to AP.。.”)

while not esp.is_connected:

try:

esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)

except RuntimeError as e:

print(“could not connect to AP, retrying: ”,e)

continue

print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)

# Initialize a requests object with a socket and esp32spi interface

requests.set_socket(socket, esp)

TEXT_URL = “http://wifitest.adafruit.com/testwifi/index.html”

JSON_GET_URL = “http://httpbin.org/get”

JSON_POST_URL = “http://httpbin.org/post”

print(“Fetching text from %s”%TEXT_URL)

response = requests.get(TEXT_URL)

print(‘-’*40)

print(“Text Response: ”, response.text)

print(‘-’*40)

response.close()

print(“Fetching JSON data from %s”%JSON_GET_URL)

response = requests.get(JSON_GET_URL)

print(‘-’*40)

print(“JSON Response: ”, response.json())

print(‘-’*40)

response.close()

data = ‘31F’

print(“POSTing data to {0}: {1}”.format(JSON_POST_URL, data))

response = requests.post(JSON_POST_URL, data=data)

print(‘-’*40)

json_resp = response.json()

# Parse out the ‘data’ key from json_resp dict.

print(“Data received from server:”, json_resp[‘data’])

print(‘-’*40)

response.close()

json_data = {“Date” : “July 25, 2019”}

print(“POSTing data to {0}: {1}”.format(JSON_POST_URL, json_data))

response = requests.post(JSON_POST_URL, json=json_data)

print(‘-’*40)

json_resp = response.json()

# Parse out the ‘json’ key from json_resp dict.

print(“JSON Data received from server:”, json_resp[‘json’])

print(‘-’*40)

response.close()

和# adafruit_requests usage with an esp32spi_socket

import board

import busio

from digitalio import DigitalInOut

import adafruit_esp32spi.adafruit_esp32spi_socket as socket

from adafruit_esp32spi import adafruit_esp32spi

import adafruit_requests as requests

# If you are using a board with pre-defined ESP32 Pins:

esp32_cs = DigitalInOut(board.ESP_CS)

esp32_ready = DigitalInOut(board.ESP_BUSY)

esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:

# esp32_cs = DigitalInOut(board.D9)

# esp32_ready = DigitalInOut(board.D10)

# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

print(“Connecting to AP.。.”)

while not esp.is_connected:

try:

esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)

except RuntimeError as e:

print(“could not connect to AP, retrying: ”,e)

continue

print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)

# Initialize a requests object with a socket and esp32spi interface

requests.set_socket(socket, esp)

TEXT_URL = “http://wifitest.adafruit.com/testwifi/index.html”

JSON_GET_URL = “http://httpbin.org/get”

JSON_POST_URL = “http://httpbin.org/post”

print(“Fetching text from %s”%TEXT_URL)

response = requests.get(TEXT_URL)

print(‘-’*40)

print(“Text Response: ”, response.text)

print(‘-’*40)

response.close()

print(“Fetching JSON data from %s”%JSON_GET_URL)

response = requests.get(JSON_GET_URL)

print(‘-’*40)

print(“JSON Response: ”, response.json())

print(‘-’*40)

response.close()

data = ‘31F’

print(“POSTing data to {0}: {1}”.format(JSON_POST_URL, data))

response = requests.post(JSON_POST_URL, data=data)

print(‘-’*40)

json_resp = response.json()

# Parse out the ‘data’ key from json_resp dict.

print(“Data received from server:”, json_resp[‘data’])

print(‘-’*40)

response.close()

json_data = {“Date” : “July 25, 2019”}

print(“POSTing data to {0}: {1}”.format(JSON_POST_URL, json_data))

response = requests.post(JSON_POST_URL, json=json_data)

print(‘-’*40)

json_resp = response.json()

# Parse out the ‘json’ key from json_resp dict.

print(“JSON Data received from server:”, json_resp[‘json’])

print(‘-’*40)

response.close()

對(duì)象初始化request對(duì)象。

下載:文件

復(fù)制代碼

socket esp

帶有請(qǐng)求的HTTP GET

代碼向Adafruit的WiFi測試網(wǎng)站-http:/發(fā)出HTTP GET請(qǐng)求/wifitest.adafruit.com/testwifi/index.html。

為此,我們會(huì)將URL傳遞到import board

import busio

from digitalio import DigitalInOut

import adafruit_esp32spi.adafruit_esp32spi_socket as socket

from adafruit_esp32spi import adafruit_esp32spi

import adafruit_requests as requests

# If you are using a board with pre-defined ESP32 Pins:

esp32_cs = DigitalInOut(board.ESP_CS)

esp32_ready = DigitalInOut(board.ESP_BUSY)

esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:

# esp32_cs = DigitalInOut(board.D9)

# esp32_ready = DigitalInOut(board.D10)

# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

print(“Connecting to AP.。.”)

while not esp.is_connected:

try:

esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)

except RuntimeError as e:

print(“could not connect to AP, retrying: ”,e)

continue

print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)

# Initialize a requests object with a socket and esp32spi interface

requests.set_socket(socket, esp)。我們還將將來自服務(wù)器的響應(yīng)保存到名為import board

import busio

from digitalio import DigitalInOut

import adafruit_esp32spi.adafruit_esp32spi_socket as socket

from adafruit_esp32spi import adafruit_esp32spi

import adafruit_requests as requests

# If you are using a board with pre-defined ESP32 Pins:

esp32_cs = DigitalInOut(board.ESP_CS)

esp32_ready = DigitalInOut(board.ESP_BUSY)

esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:

# esp32_cs = DigitalInOut(board.D9)

# esp32_ready = DigitalInOut(board.D10)

# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

print(“Connecting to AP.。.”)

while not esp.is_connected:

try:

esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)

except RuntimeError as e:

print(“could not connect to AP, retrying: ”,e)

continue

print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)

# Initialize a requests object with a socket and esp32spi interface

requests.set_socket(socket, esp)的變量。

盡管我們從服務(wù)器請(qǐng)求數(shù)據(jù),但我們還是希望服務(wù)器回應(yīng)。由于我們已經(jīng)保存了服務(wù)器的requests.get(),因此可以將其讀回。對(duì)我們來說幸運(yùn)的是,請(qǐng)求將服務(wù)器的響應(yīng)自動(dòng)解碼為人類可讀的文本,您可以通過調(diào)用response將其讀回。

最后,我們將執(zhí)行一些操作通過調(diào)用response進(jìn)行清理。這樣會(huì)關(guān)閉,刪除和收集響應(yīng)的數(shù)據(jù)。

下載:文件

復(fù)制代碼

response.text response.close()

一些服務(wù)器使用文本響應(yīng),而某些服務(wù)器則使用由屬性-值對(duì)組成的json格式的數(shù)據(jù)進(jìn)行響應(yīng)。/p》

CircuitPython_Requests可以將來自服務(wù)器的JSON格式的響應(yīng)轉(zhuǎn)換為CPython print(“Fetching text from %s”%TEXT_URL)

response = requests.get(TEXT_URL)

print(‘-’*40)

print(“Text Response: ”, response.text)

print(‘-’*40)

response.close()對(duì)象。

我們還可以獲取和解析 json 數(shù)據(jù)。我們將發(fā)送HTTP Get到一個(gè)我們知道的URL,該URL返回一個(gè)json格式的響應(yīng)(而不是文本數(shù)據(jù))。

然后,代碼調(diào)用print(“Fetching text from %s”%TEXT_URL)

response = requests.get(TEXT_URL)

print(‘-’*40)

print(“Text Response: ”, response.text)

print(‘-’*40)

response.close()將響應(yīng)轉(zhuǎn)換為一個(gè)CPython dict.。

下載:文件

復(fù)制代碼

response.json() dict

帶有請(qǐng)求的HTTP POST

請(qǐng)求還可以通過調(diào)用print(“Fetching JSON data from %s”%JSON_GET_URL)

response = requests.get(JSON_GET_URL)

print(‘-’*40)

print(“JSON Response: ”, response.json())

print(‘-’*40)

response.close()方法(向其傳遞一個(gè)print(“Fetching JSON data from %s”%JSON_GET_URL)

response = requests.get(JSON_GET_URL)

print(‘-’*40)

print(“JSON Response: ”, response.json())

print(‘-’*40)

response.close()值)將數(shù)據(jù)發(fā)布到服務(wù)器。

下載:文件

復(fù)制代碼

requests.post data

您還可以通過將data = ‘31F’

print(“POSTing data to {0}: {1}”.format(JSON_POST_URL, data))

response = requests.post(JSON_POST_URL, data=data)

print(‘-’*40)

json_resp = response.json()

# Parse out the ‘data’ key from json_resp dict.

print(“Data received from server:”, json_resp[‘data’])

print(‘-’*40)

response.close()傳遞到data = ‘31F’

print(“POSTing data to {0}: {1}”.format(JSON_POST_URL, data))

response = requests.post(JSON_POST_URL, data=data)

print(‘-’*40)

json_resp = response.json()

# Parse out the ‘data’ key from json_resp dict.

print(“Data received from server:”, json_resp[‘data’])

print(‘-’*40)

response.close()方法中,將json格式的數(shù)據(jù)發(fā)布到服務(wù)器。

下載:文件

復(fù)制代碼

json_data requests.post

高級(jí)請(qǐng)求使用情況

要發(fā)送自定義HTTP, aders,將響應(yīng)解析為原始字節(jié),還是在CircuitPython代碼中處理響應(yīng)的http狀態(tài)代碼?

我們已經(jīng)編寫了一個(gè)示例來顯示下面的請(qǐng)求模塊的高級(jí)用法。

下載:項(xiàng)目Zip 或 requests_advanced.py | 在Github上查看

復(fù)制代碼

json_data = {“Date” : “July 25, 2019”}

print(“POSTing data to {0}: {1}”.format(JSON_POST_URL, json_data))

response = requests.post(JSON_POST_URL, json=json_data)

print(‘-’*40)

json_resp = response.json()

# Parse out the ‘json’ key from json_resp dict.

print(“JSON Data received from server:”, json_resp[‘json’])

print(‘-’*40)

response.close()

json_data = {“Date” : “July 25, 2019”}

print(“POSTing data to {0}: {1}”.format(JSON_POST_URL, json_data))

response = requests.post(JSON_POST_URL, json=json_data)

print(‘-’*40)

json_resp = response.json()

# Parse out the ‘json’ key from json_resp dict.

print(“JSON Data received from server:”, json_resp[‘json’])

print(‘-’*40)

response.close()

WiFi Manager

這個(gè)最簡單的示例可行,但有點(diǎn)挑剔-您需要不斷檢查WiFi狀態(tài),并具有許多循環(huán)來管理連接和斷開連接。對(duì)于更高級(jí)的用途,我們建議使用WiFiManager對(duì)象。它將為您包裝連接/狀態(tài)/請(qǐng)求循環(huán)-如果WiFi掉線,則重新連接,如果ESP32進(jìn)入不良狀態(tài),則重置ESP32,等等。

這是一個(gè)更高級(jí)的示例,其中顯示了WiFi管理器以及如何使用一些額外的標(biāo)題發(fā)布數(shù)據(jù):

下載:Project Zip 或 esp32spi_aio_post.py | 在Github上查看

復(fù)制代碼

import board

import busio

from digitalio import DigitalInOut

import adafruit_esp32spi.adafruit_esp32spi_socket as socket

from adafruit_esp32spi import adafruit_esp32spi

import adafruit_requests as requests

# If you are using a board with pre-defined ESP32 Pins:

esp32_cs = DigitalInOut(board.ESP_CS)

esp32_ready = DigitalInOut(board.ESP_BUSY)

esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:

# esp32_cs = DigitalInOut(board.D9)

# esp32_ready = DigitalInOut(board.D10)

# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

print(“Connecting to AP.。.”)

while not esp.is_connected:

try:

esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)

except RuntimeError as e:

print(“could not connect to AP, retrying: ”,e)

continue

print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)

# Initialize a requests object with a socket and esp32spi interface

requests.set_socket(socket, esp)

JSON_GET_URL = “http://httpbin.org/get”

# Define a custom header as a dict.

headers = {“user-agent” : “blinka/1.0.0”}

print(“Fetching JSON data from %s.。.”%JSON_GET_URL)

response = requests.get(JSON_GET_URL, headers=headers)

print(‘-’*60)

json_data = response.json()

headers = json_data[‘headers’]

print(“Response‘s Custom User-Agent Header: {0}”.format(headers[’User-Agent‘]))

print(’-‘*60)

# Read Response’s HTTP status code

print(“Response HTTP Status Code: ”, response.status_code)

print(‘-’*60)

# Read Response, as raw bytes instead of pretty text

print(“Raw Response: ”, response.content)

# Close, delete and collect the response data

response.close()

import board

import busio

from digitalio import DigitalInOut

import adafruit_esp32spi.adafruit_esp32spi_socket as socket

from adafruit_esp32spi import adafruit_esp32spi

import adafruit_requests as requests

# If you are using a board with pre-defined ESP32 Pins:

esp32_cs = DigitalInOut(board.ESP_CS)

esp32_ready = DigitalInOut(board.ESP_BUSY)

esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:

# esp32_cs = DigitalInOut(board.D9)

# esp32_ready = DigitalInOut(board.D10)

# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

print(“Connecting to AP.。.”)

while not esp.is_connected:

try:

esp.connect_AP(b‘MY_SSID_NAME’, b‘MY_SSID_PASSWORD’)

except RuntimeError as e:

print(“could not connect to AP, retrying: ”,e)

continue

print(“Connected to”, str(esp.ssid, ‘utf-8’), “ RSSI:”, esp.rssi)

# Initialize a requests object with a socket and esp32spi interface

requests.set_socket(socket, esp)

JSON_GET_URL = “http://httpbin.org/get”

# Define a custom header as a dict.

headers = {“user-agent” : “blinka/1.0.0”}

print(“Fetching JSON data from %s.。.”%JSON_GET_URL)

response = requests.get(JSON_GET_URL, headers=headers)

print(‘-’*60)

json_data = response.json()

headers = json_data[‘headers’]

print(“Response‘s Custom User-Agent Header: {0}”.format(headers[’User-Agent‘]))

print(’-‘*60)

# Read Response’s HTTP status code

print(“Response HTTP Status Code: ”, response.status_code)

print(‘-’*60)

# Read Response, as raw bytes instead of pretty text

print(“Raw Response: ”, response.content)

# Close, delete and collect the response data

response.close()

您會(huì)在這里注意到,我們使用secrets.py文件來管理我們的SSID信息。 wifimanager被賦予了ESP32對(duì)象,密碼和一個(gè)用于指示狀態(tài)的新像素。

請(qǐng)注意,您需要在密碼文件中添加一些其他信息,以便代碼可以查詢Adafruit IO API:

import time

import board

import busio

from digitalio import DigitalInOut

import neopixel

from adafruit_esp32spi import adafruit_esp32spi

from adafruit_esp32spi import adafruit_esp32spi_wifimanager

print(“ESP32 SPI webclient test”)

# Get wifi details and more from a secrets.py file

try:

from secrets import secrets

except ImportError:

print(“WiFi secrets are kept in secrets.py, please add them there!”)

raise

# If you are using a board with pre-defined ESP32 Pins:

esp32_cs = DigitalInOut(board.ESP_CS)

esp32_ready = DigitalInOut(board.ESP_BUSY)

esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:

# esp32_cs = DigitalInOut(board.D9)

# esp32_ready = DigitalInOut(board.D10)

# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

“”“Use below for Most Boards”“”

status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards

“”“Uncomment below for ItsyBitsy M4”“”

# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)

# Uncomment below for an externally defined RGB LED

# import adafruit_rgbled

# from adafruit_esp32spi import PWMOut

# RED_LED = PWMOut.PWMOut(esp, 26)

# GREEN_LED = PWMOut.PWMOut(esp, 27)

# BLUE_LED = PWMOut.PWMOut(esp, 25)

# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)

wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)

counter = 0

while True:

try:

print(“Posting data.。.”, end=‘’)

data = counter

feed = ‘test’

payload = {‘value’:data}

response = wifi.post(

“https://io.adafruit.com/api/v2/”+secrets[‘a(chǎn)io_username’]+“/feeds/”+feed+“/data”,

json=payload,

headers={“X-AIO-KEY”:secrets[‘a(chǎn)io_key’]})

print(response.json())

response.close()

counter = counter + 1

print(“OK”)

except (ValueError, RuntimeError) as e:

print(“Failed to get data, retrying ”, e)

wifi.reset()

continue

response = None

time.sleep(15)

import time

import board

import busio

from digitalio import DigitalInOut

import neopixel

from adafruit_esp32spi import adafruit_esp32spi

from adafruit_esp32spi import adafruit_esp32spi_wifimanager

print(“ESP32 SPI webclient test”)

# Get wifi details and more from a secrets.py file

try:

from secrets import secrets

except ImportError:

print(“WiFi secrets are kept in secrets.py, please add them there!”)

raise

# If you are using a board with pre-defined ESP32 Pins:

esp32_cs = DigitalInOut(board.ESP_CS)

esp32_ready = DigitalInOut(board.ESP_BUSY)

esp32_reset = DigitalInOut(board.ESP_RESET)

# If you have an externally connected ESP32:

# esp32_cs = DigitalInOut(board.D9)

# esp32_ready = DigitalInOut(board.D10)

# esp32_reset = DigitalInOut(board.D5)

spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)

“”“Use below for Most Boards”“”

status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards

“”“Uncomment below for ItsyBitsy M4”“”

# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)

# Uncomment below for an externally defined RGB LED

# import adafruit_rgbled

# from adafruit_esp32spi import PWMOut

# RED_LED = PWMOut.PWMOut(esp, 26)

# GREEN_LED = PWMOut.PWMOut(esp, 27)

# BLUE_LED = PWMOut.PWMOut(esp, 25)

# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED)

wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)

counter = 0

while True:

try:

print(“Posting data.。.”, end=‘’)

data = counter

feed = ‘test’

payload = {‘value’:data}

response = wifi.post(

“https://io.adafruit.com/api/v2/”+secrets[‘a(chǎn)io_username’]+“/feeds/”+feed+“/data”,

json=payload,

headers={“X-AIO-KEY”:secrets[‘a(chǎn)io_key’]})

print(response.json())

response.close()

counter = counter + 1

print(“OK”)

except (ValueError, RuntimeError) as e:

print(“Failed to get data, retrying ”, e)

wifi.reset()

continue

response = None

time.sleep(15)

您可以轉(zhuǎn)到adafruit.io查看AIO密鑰鏈接獲取這兩個(gè)值并將它們添加到secrets文件中,該文件現(xiàn)在看起來像這樣:

下載:文件

復(fù)制代碼

aio_username aio_key

下一步,設(shè)置一個(gè)名為Adafruit IO提要# This file is where you keep secret settings, passwords, and tokens!

# If you put them in the code you risk committing that info or sharing it

secrets = {

‘ssid’ : ‘_your_ssid_’,

‘password’ : ‘_your_wifi_password_’,

‘timezone’ : “America/Los_Angeles”, # http://worldtimeapi.org/timezones

‘a(chǎn)io_username’ : ‘_your_aio_username_’,

‘a(chǎn)io_key’ : ‘_your_aio_key_’,

}

如果您不知道如何設(shè)置供稿,請(qǐng)遵循此頁面并在設(shè)置名為。

然后,我們可以有一個(gè)簡單的循環(huán),用于將數(shù)據(jù)發(fā)布到Adafruit IO,而無需處理連接或初始化硬件!

在Adafruit.io上查看您的測試數(shù)據(jù),每次Cir時(shí),您都會(huì)看到該值增加cuitPython板向其發(fā)布數(shù)據(jù)!

Twitter認(rèn)證密鑰

在使用Twitter API之前,我們需要注冊(cè)一個(gè)開發(fā)人員帳戶。

開始到https://developer.twitter.com/en.html。您應(yīng)該會(huì)看到類似以下頁面的頁面:

單擊應(yīng)用:

然后申請(qǐng)開發(fā)者帳戶:

選擇瀏覽API ,然后點(diǎn)擊下一步 。

填寫顯示的表格,然后點(diǎn)擊下一步。驗(yàn)證信息,然后單擊下一步。同意條款,然后點(diǎn)擊提交申請(qǐng)。您會(huì)在輸入的地址收到一封確認(rèn)電子郵件。相應(yīng)地進(jìn)行響應(yīng),您將可以創(chuàng)建您的 app 。

創(chuàng)建應(yīng)用程序

要獲取要使用的密鑰,您需要?jiǎng)?chuàng)建一個(gè)應(yīng)用程序。您將獲得該應(yīng)用程序的密鑰,在本例中為萬圣節(jié)倒計(jì)時(shí)應(yīng)用程序。

單擊創(chuàng)建應(yīng)用程序?qū)@示一個(gè)表格。如您所愿地將其填寫,總體上似乎不太挑剔。完成該操作后,您的應(yīng)用程序頁面將列出您的新應(yīng)用程序:

點(diǎn)擊應(yīng)用旁邊的詳細(xì)信息按鈕。這會(huì)提供您應(yīng)用程序上的所有信息。

您正在尋找的是應(yīng)用程序密鑰。在“密鑰和令牌”標(biāo)簽上找到它們:

將 API密鑰和 API秘密密鑰作為 secrets.py 文件中= 1》和twitter_api_key。

就是這樣。

獲取推文

OAuth徽標(biāo)作者:Chris Messina CC BY_SA 3.0

Authenticating

一旦擁有了Twitter密鑰,就可以在程序開始獲取Twitter OAuth 2.0 bearer令牌時(shí)使用它們。這涉及合并兩個(gè)密鑰,進(jìn)行base64編碼,調(diào)用Twitter API,以及從響應(yīng)中提取承載令牌。它有些牽連,即使我們只需要使用一次,它也是包裝函數(shù)的理想之選。

誰知道,這可能是Twitter API包裝庫的開始。

下載:文件

復(fù)制代碼

def get_bearer_token():

“”“Get the bearer authentication token from twitter.”“”

raw_key = secrets[‘twitter_api_key’] + ‘:’ + secrets[‘twitter_secret_key’]

encoded_key = binascii.b2a_base64(bytes(raw_key, ‘utf8’))

string_key = bytes.decode(encoded_key)

headers= {‘Authorization’: ‘Basic ’ + string_key,

‘Content-Type’: ‘a(chǎn)pplication/x-www-form-urlencoded;charset=UTF-8’}

response = requests.post(‘https://api.twitter.com/oauth2/token’,

headers=headers,

data=‘grant_type=client_credentials’)

response_dict = json.loads(response.content)

if response_dict[‘token_type’] != ‘bearer’:

halt_and_catch_fire(‘Wrong token type from twitter: %s’, response_dict[‘token_type’])

return response_dict[‘access_token’] def get_bearer_token():

“”“Get the bearer authentication token from twitter.”“”

raw_key = secrets[‘twitter_api_key’] + ‘:’ + secrets[‘twitter_secret_key’]

encoded_key = binascii.b2a_base64(bytes(raw_key, ‘utf8’))

string_key = bytes.decode(encoded_key)

headers= {‘Authorization’: ‘Basic ’ + string_key,

‘Content-Type’: ‘a(chǎn)pplication/x-www-form-urlencoded;charset=UTF-8’}

response = requests.post(‘https://api.twitter.com/oauth2/token’,

headers=headers,

data=‘grant_type=client_credentials’)

response_dict = json.loads(response.content)

if response_dict[‘token_type’] != ‘bearer’:

halt_and_catch_fire(‘Wrong token type from twitter: %s’, response_dict[‘token_type’])

return response_dict[‘a(chǎn)ccess_token’]

注意對(duì)函數(shù)halt_and_catch_fire的調(diào)用。該函數(shù)接受傳遞的參數(shù),將其組合并打印結(jié)果,然后停止(通過無限循環(huán))。該名稱是對(duì)AMC的致敬,該展覽與微型計(jì)算機(jī)行業(yè)的早期名稱相同。盡管并不完全準(zhǔn)確(相信我,我在那里),但它還是很有趣的。反過來,它是對(duì)(來自Wikipedia的)引用:

在計(jì)算機(jī)工程中, Halt and Catch Fire (由組裝助記符 HCF 已知) ,是計(jì)算機(jī)計(jì)算機(jī)代碼指令的慣用語,該指令導(dǎo)致計(jì)算機(jī)的中央處理單元(CPU)停止有意義的操作,通常需要重新啟動(dòng)計(jì)算機(jī)。

這似乎是適當(dāng)?shù)摹?/p>

下載:文件

復(fù)制代碼

def halt_and_catch_fire(message, *args):

“”“Log a critical error and stall the system.”“”

print(message % args)

while True:

pass def halt_and_catch_fire(message, *args):

“”“Log a critical error and stall the system.”“”

print(message % args)

while True:

pass

設(shè)置PyPortal對(duì)象

在真正發(fā)生任何事情之前,我們需要一個(gè)PyPortal的實(shí)例。這將設(shè)置URL,用于從該URL返回的json中提取推文文本的json路徑,以及文本區(qū)域特征。

下載:文件

復(fù)制代碼

cwd = (“/”+__file__).rsplit(‘/’, 1)[0]

url = ‘https://api.twitter.com/1.1/statuses/user_timeline.json?count=1&screen_name=’ + username

# Initialize the pyportal object and let us know what data to fetch and where

# to display it

pyportal = PyPortal(url=url,

json_path=(0, ‘text’),

status_neopixel=board.NEOPIXEL,

default_bg=cwd + ‘/twitter_background.bmp’,

text_font=cwd+‘/fonts/Helvetica-Bold-16.bdf’,

text_position=(20, 60),

text_color=0xFFFFFF,

text_wrap=35,

caption_text=‘@’ + username,

caption_font=cwd+‘/fonts/Helvetica-Bold-16.bdf’,

caption_position=(5, 210),

caption_color=0x808080) cwd = (“/”+__file__).rsplit(‘/’, 1)[0]

url = ‘https://api.twitter.com/1.1/statuses/user_timeline.json?count=1&screen_name=’ + username

# Initialize the pyportal object and let us know what data to fetch and where

# to display it

pyportal = PyPortal(url=url,

json_path=(0, ‘text’),

status_neopixel=board.NEOPIXEL,

default_bg=cwd + ‘/twitter_background.bmp’,

text_font=cwd+‘/fonts/Helvetica-Bold-16.bdf’,

text_position=(20, 60),

text_color=0xFFFFFF,

text_wrap=35,

caption_text=‘@’ + username,

caption_font=cwd+‘/fonts/Helvetica-Bold-16.bdf’,

caption_position=(5, 210),

caption_color=0x808080)

這也會(huì)初始化wifi堆棧,因此現(xiàn)在我們可以獲取身份驗(yàn)證令牌并構(gòu)造推文獲取所需的身份驗(yàn)證標(biāo)頭。

下載:文件

復(fù)制代碼

bearer_token = get_bearer_token()

pyportal.set_headers({‘Authorization’: ‘Bearer ’ + bearer_token}) bearer_token = get_bearer_token()

pyportal.set_headers({‘Authorization’: ‘Bearer ’ + bearer_token})

獲取推文

現(xiàn)在,承載令牌已被獲取并用于設(shè)置auth標(biāo)頭,可以調(diào)用API來獲取一些推文

主循環(huán)在下面。每小時(shí)都會(huì)獲取最新的推文。上面我們?cè)O(shè)置了PyPortal實(shí)例,其中包含從Twitter API中獲取數(shù)據(jù),提取推文的文本并顯示它所需的一切。所有需要做的就是告訴它使用fetch()方法來做到這一點(diǎn)。

下載:文件

復(fù)制代碼

while True:

pyportal.fetch()

time.sleep(3600) # check every hour while True:

pyportal.fetch()

time.sleep(3600) # check every hour

代碼

下載: Project Zip 或 code.py | 在Github上查看

復(fù)制代碼

“”“

Twitter API for PyPortal.

Adafruit invests time and resources providing this open source code.

Please support Adafruit and open source hardware by purchasing

products from Adafruit!

Written by Dave Astels for Adafruit Industries

Copyright (c) 2019 Adafruit Industries

Licensed under the MIT license.

All text above must be included in any redistribution.

”“”

#pylint:disable=invalid-name

import time

import binascii

import json

import board

from adafruit_pyportal import PyPortal

import adafruit_esp32spi.adafruit_esp32spi_requests as requests

username = ‘codewisdom’

try:

from secrets import secrets

except ImportError:

print(“”“WiFi settings are kept in secrets.py, please add them there!

the secrets dictionary must contain ‘ssid’ and ‘password’ at a minimum”“”)

raise

def halt_and_catch_fire(message, *args):

“”“Log a critical error and stall the system.”“”

print(message % args)

while True:

pass

def get_bearer_token():

“”“Get the bearer authentication token from twitter.”“”

raw_key = secrets[‘twitter_api_key’] + ‘:’ + secrets[‘twitter_secret_key’]

encoded_key = binascii.b2a_base64(bytes(raw_key, ‘utf8’))

string_key = bytes.decode(encoded_key)

headers = {‘Authorization’: ‘Basic ’ + string_key,

‘Content-Type’: ‘a(chǎn)pplication/x-www-form-urlencoded;charset=UTF-8’}

response = requests.post(‘https://api.twitter.com/oauth2/token’,

headers=headers,

data=‘grant_type=client_credentials’)

response_dict = json.loads(response.content)

if response_dict[‘token_type’] != ‘bearer’:

halt_and_catch_fire(‘Wrong token type from twitter: %s’, response_dict[‘token_type’])

return response_dict[‘a(chǎn)ccess_token’]

# determine the current working directory

# needed so we know where to find files

cwd = (“/”+__file__).rsplit(‘/’, 1)[0]

url = ‘https://api.twitter.com/1.1/statuses/user_timeline.json?count=1&screen_name=’ + username

# Initialize the pyportal object and let us know what data to fetch and where

# to display it

pyportal = PyPortal(url=url,

json_path=(0, ‘text’),

status_neopixel=board.NEOPIXEL,

default_bg=cwd + ‘/twitter_background.bmp’,

text_font=cwd+‘/fonts/Helvetica-Bold-16.bdf’,

text_position=(20, 60),

text_color=0xFFFFFF,

text_wrap=35,

caption_text=‘@’ + username,

caption_font=cwd+‘/fonts/Helvetica-Bold-16.bdf’,

caption_position=(5, 210),

caption_color=0x808080)

bearer_token = get_bearer_token()

pyportal.set_headers({‘Authorization’: ‘Bearer ’ + bearer_token})

while True:

pyportal.fetch()

time.sleep(3600) # check every hour

“”“

Twitter API for PyPortal.

Adafruit invests time and resources providing this open source code.

Please support Adafruit and open source hardware by purchasing

products from Adafruit!

Written by Dave Astels for Adafruit Industries

Copyright (c) 2019 Adafruit Industries

Licensed under the MIT license.

All text above must be included in any redistribution.

”“”

#pylint:disable=invalid-name

import time

import binascii

import json

import board

from adafruit_pyportal import PyPortal

import adafruit_esp32spi.adafruit_esp32spi_requests as requests

username = ‘codewisdom’

try:

from secrets import secrets

except ImportError:

print(“”“WiFi settings are kept in secrets.py, please add them there!

the secrets dictionary must contain ‘ssid’ and ‘password’ at a minimum”“”)

raise

def halt_and_catch_fire(message, *args):

“”“Log a critical error and stall the system.”“”

print(message % args)

while True:

pass

def get_bearer_token():

“”“Get the bearer authentication token from twitter.”“”

raw_key = secrets[‘twitter_api_key’] + ‘:’ + secrets[‘twitter_secret_key’]

encoded_key = binascii.b2a_base64(bytes(raw_key, ‘utf8’))

string_key = bytes.decode(encoded_key)

headers = {‘Authorization’: ‘Basic ’ + string_key,

‘Content-Type’: ‘a(chǎn)pplication/x-www-form-urlencoded;charset=UTF-8’}

response = requests.post(‘https://api.twitter.com/oauth2/token’,

headers=headers,

data=‘grant_type=client_credentials’)

response_dict = json.loads(response.content)

if response_dict[‘token_type’] != ‘bearer’:

halt_and_catch_fire(‘Wrong token type from twitter: %s’, response_dict[‘token_type’])

return response_dict[‘a(chǎn)ccess_token’]

# determine the current working directory

# needed so we know where to find files

cwd = (“/”+__file__).rsplit(‘/’, 1)[0]

url = ‘https://api.twitter.com/1.1/statuses/user_timeline.json?count=1&screen_name=’ + username

# Initialize the pyportal object and let us know what data to fetch and where

# to display it

pyportal = PyPortal(url=url,

json_path=(0, ‘text’),

status_neopixel=board.NEOPIXEL,

default_bg=cwd + ‘/twitter_background.bmp’,

text_font=cwd+‘/fonts/Helvetica-Bold-16.bdf’,

text_position=(20, 60),

text_color=0xFFFFFF,

text_wrap=35,

caption_text=‘@’ + username,

caption_font=cwd+‘/fonts/Helvetica-Bold-16.bdf’,

caption_position=(5, 210),

caption_color=0x808080)

bearer_token = get_bearer_token()

pyportal.set_headers({‘Authorization’: ‘Bearer ’ + bearer_token})

while True:

pyportal.fetch()

time.sleep(3600) # check every hour
責(zé)任編輯:wv

聲明:本文內(nèi)容及配圖由入駐作者撰寫或者入駐合作網(wǎng)站授權(quán)轉(zhuǎn)載。文章觀點(diǎn)僅代表作者本人,不代表電子發(fā)燒友網(wǎng)立場。文章及其配圖僅供工程師學(xué)習(xí)之用,如有內(nèi)容侵權(quán)或者其他違規(guī)問題,請(qǐng)聯(lián)系本站處理。 舉報(bào)投訴
  • python
    +關(guān)注

    關(guān)注

    56

    文章

    4827

    瀏覽量

    86761
收藏 人收藏
加入交流群
微信小助手二維碼

掃碼添加小助手

加入工程師交流群

    評(píng)論

    相關(guān)推薦
    熱點(diǎn)推薦

    API技術(shù)助力跨境電商破解物流困局

    ? 在跨境電商領(lǐng)域,物流效率直接影響用戶復(fù)購率與品牌口碑。傳統(tǒng)模式下, 多環(huán)節(jié)信息割裂 、 清關(guān)延誤 、 末端配送不可控 成為三大核心瓶頸。而API(應(yīng)用程序接口)技術(shù)通過 系統(tǒng)級(jí)數(shù)據(jù)聯(lián)通
    的頭像 發(fā)表于 07-17 14:26 ?69次閱讀
    <b class='flag-5'>API</b>技術(shù)助力跨境電商破解物流困局

    利用API提升電商用戶體驗(yàn):個(gè)性化推薦系統(tǒng)

    ? 在當(dāng)今競爭激烈的電商環(huán)境中,個(gè)性化推薦系統(tǒng)已成為提升用戶粘性和轉(zhuǎn)化率的核心工具。通過API(Application Programming Interface)集成,電商平臺(tái)能夠高效接入先進(jìn)
    的頭像 發(fā)表于 07-14 14:45 ?65次閱讀
    利用<b class='flag-5'>API</b>提升電商<b class='flag-5'>用戶</b>體驗(yàn):個(gè)性化推薦系統(tǒng)

    電商API安全最佳實(shí)踐:保護(hù)用戶數(shù)據(jù)免受攻擊

    ? 在電商領(lǐng)域,API(應(yīng)用程序編程接口)是連接用戶、商家和支付系統(tǒng)的核心樞紐。它們處理敏感數(shù)據(jù),如用戶個(gè)人信息、支付詳情和交易記錄。然而,API也常成為黑客攻擊的目標(biāo),導(dǎo)致數(shù)據(jù)泄露、
    的頭像 發(fā)表于 07-14 14:41 ?124次閱讀
    電商<b class='flag-5'>API</b>安全最佳實(shí)踐:保護(hù)<b class='flag-5'>用戶</b>數(shù)據(jù)免受攻擊

    淘寶 vs 京東電商 API 接口,誰才是數(shù)據(jù)王者?

    API進(jìn)行客觀比較,幫助您判斷誰才是真正的“數(shù)據(jù)王者”。 1.API功能覆蓋范圍 API的功能范圍決定了開發(fā)者能獲取的數(shù)據(jù)類型。淘寶API
    的頭像 發(fā)表于 07-08 15:51 ?174次閱讀
    淘寶 vs 京東電商 <b class='flag-5'>API</b> 接口,誰才是數(shù)據(jù)王者?

    小紅書電商 API 接口,種草效果評(píng)估實(shí)用秘籍!

    小紅書電商 API 接口,高效評(píng)估種草效果,并提供實(shí)用秘籍,助你輕松優(yōu)化策略。文章結(jié)構(gòu)清晰,基礎(chǔ)概念到實(shí)戰(zhàn)應(yīng)用,確保你學(xué)以致用。 一、小紅書電商 API 接口簡介 小紅書電商 API
    的頭像 發(fā)表于 07-07 14:27 ?183次閱讀
    小紅書電商 <b class='flag-5'>API</b> 接口,種草效果評(píng)估實(shí)用秘籍!

    鴻蒙NEXT-API19獲取上下文,在class中和ability中獲取上下文,API遷移示例-解決無法在EntryAbility中無法使用最新版

    摘要:隨著鴻蒙系統(tǒng)API升級(jí)至16版本(modelVersion5.1.1),多項(xiàng)API已廢棄。獲取上下文需使用UIContext,具體方法包括:在組件中使用getUIContext(),在類中使
    的頭像 發(fā)表于 07-01 10:57 ?209次閱讀
    鴻蒙NEXT-<b class='flag-5'>API</b>19<b class='flag-5'>獲取</b>上下文,在class中和ability中<b class='flag-5'>獲取</b>上下文,<b class='flag-5'>API</b>遷移示例-解決無法在EntryAbility中無法使用最新版

    如何獲取 OpenAI API Key?API 獲取與代碼調(diào)用示例 (詳解教程)

    OpenAI API Key 獲取與使用詳解:入門到精通 OpenAI 正以其 GPT 和 DALL-E 等先進(jìn)模型引領(lǐng)全球人工智能創(chuàng)新。其 API 為開發(fā)者和企業(yè)提供了強(qiáng)大的 AI
    的頭像 發(fā)表于 05-04 11:42 ?2158次閱讀
    如何<b class='flag-5'>獲取</b> OpenAI <b class='flag-5'>API</b> Key?<b class='flag-5'>API</b> <b class='flag-5'>獲取</b>與代碼調(diào)用示例 (詳解教程)

    MAXQ1050英用戶手冊(cè)

    MAXQ1050英用戶手冊(cè),網(wǎng)上很少有這類資料,國外網(wǎng)站下載回來的,分享給大家
    發(fā)表于 04-25 16:58 ?3次下載

    鴻蒙應(yīng)用元服務(wù)開發(fā)-Account Kit獲取手機(jī)號(hào)

    、Client Secret、Authorization Code華為服務(wù)器獲取Access Token,再使用Access Token請(qǐng)求獲取用戶信息。
    發(fā)表于 04-08 16:14

    爬蟲數(shù)據(jù)獲取實(shí)戰(zhàn)指南:入門到高效采集

    爬蟲數(shù)據(jù)獲取實(shí)戰(zhàn)指南:入門到高效采集 ? ? 在數(shù)字化浪潮中,數(shù)據(jù)已成為驅(qū)動(dòng)商業(yè)增長的核心引擎。無論是市場趨勢洞察、競品動(dòng)態(tài)追蹤,還是用戶行為分析,爬蟲技術(shù)都能助你快速捕獲目標(biāo)信息。然而,如何既
    的頭像 發(fā)表于 03-24 14:08 ?623次閱讀

    Claude 3.7:編碼助手首選,claude api key如何申請(qǐng)獲取與深度解析*

    核心看點(diǎn) 混合推理引擎 :Claude 3.7 融合快速代碼生成與深度問題解決能力,實(shí)現(xiàn)“快思考”與“深思考”的無縫切換。 便捷API訪問 :三步快速獲取Claude 3.7 API密鑰,安全、簡單
    的頭像 發(fā)表于 03-24 09:43 ?971次閱讀
    Claude 3.7:編碼助手首選,claude <b class='flag-5'>api</b> key如何申請(qǐng)<b class='flag-5'>獲取</b>與深度解析*

    openai api key獲取的三種方案(有一種可以白嫖到 api key)

    OpenAI API Key 全攻略:官方獲取、費(fèi)用詳解與“白嫖”實(shí)戰(zhàn) 引言: 想要體驗(yàn) OpenAI 強(qiáng)大的 GPT 模型,卻苦于沒有 API Key?別擔(dān)心,本文將為你提供一份詳盡
    的頭像 發(fā)表于 02-24 22:16 ?9829次閱讀
    openai <b class='flag-5'>api</b> key<b class='flag-5'>獲取</b>的三種方案(有一種可以白嫖到 <b class='flag-5'>api</b> key)

    OpenAI API Key 獲取全攻略:入門、精通與詳解教程(國內(nèi)開發(fā)者優(yōu)化版)

    帶來的現(xiàn)實(shí)。無論你是開發(fā)者、研究員、內(nèi)容創(chuàng)作者,還是 AI 愛好者,OpenAI 強(qiáng)大的語言模型都能為你的工作和生活帶來無限可能。 本指南將手把手教你獲取并使用 OpenAI API 密鑰,零基礎(chǔ)到高級(jí)應(yīng)用,全程無障礙!針對(duì)
    的頭像 發(fā)表于 02-15 17:26 ?3567次閱讀
    OpenAI <b class='flag-5'>API</b> Key <b class='flag-5'>獲取</b>全攻略:入門、精通與詳解教程(國內(nèi)開發(fā)者優(yōu)化版)

    API :軟件程序間溝通的橋梁

    或許我們不清楚API是什么,但在現(xiàn)實(shí)生活中,API的應(yīng)用場景卻遠(yuǎn)遠(yuǎn)超出了我們的想象。舉個(gè)例子來說,當(dāng)我們想要搜索某個(gè)IP地址時(shí),通常是利用API與離線庫兩種方式去獲取數(shù)據(jù)信息,那么或許
    的頭像 發(fā)表于 08-27 15:54 ?558次閱讀

    OpenAI api key獲取并可調(diào)用GPT-4.0、GPT-4o、GPT-4omini

    前言 在這篇文章中,我們將詳細(xì)介紹如何申請(qǐng)OpenAI的GPT-4.0 API Key。通過這個(gè)教程,你將能夠輕松獲取OpenAI API KEY并使用GPT-4.0的強(qiáng)大功能。 目錄 注冊(cè)
    的頭像 發(fā)表于 08-06 15:16 ?4557次閱讀
    OpenAI <b class='flag-5'>api</b> key<b class='flag-5'>獲取</b>并可調(diào)用GPT-4.0、GPT-4o、GPT-4omini