首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么从带有EAI_FAIL模块的Pycom WiPy板发送HTTP时会引发"[Errno 202] _urequest“异常?

为什么从带有EAI_FAIL模块的Pycom WiPy板发送HTTP时会引发"[Errno 202] _urequest“异常?
EN

Stack Overflow用户
提问于 2021-11-25 12:04:10
回答 1查看 217关注 0票数 1

上下文

我有一个Pycom WiPy板运行一些Python代码。代码使用.NET模块向_urequest web发出HTTP请求。

问题

发送HTTP请求时,将引发[Errno 202] EAI_FAIL异常。由于请求在循环中每10秒发送一次,这种情况在一次又一次发生。

代码

Wifi客户端,连接本地wifi并获得因特网接入。

代码语言:javascript
复制
import json
import time
from network import WLAN

# Wifi client singleton
wifiClient = None

def initWifiClient():
    global wifiClient
    wifiClient = WifiClient()

def getWifiClient():
    global wifiClient
    return wifiClient

class WifiClient:

    wifi = None
    lastWifiConnectAttempt = None

    def __init__(self):
        self.wifi = WLAN(mode=WLAN.STA)
        pass

    def connect(self):
        if not self.__readyForNewWifiConnectAttempt():
            print("Not ready yet for new WIFI connect attempt.")
            self.__printSecondsLeftToNextConnectAttempt()
            return

        print("Trying to connect WIFI.")
        try:
            self.lastWifiConnectAttempt = time.time()
            with open('wifi.json') as json_file:
                wifiJson = json.load(json_file)

                self.wifi.connect(ssid=wifiJson['ssid'], auth=(WLAN.WPA2, wifiJson['password']), timeout=30000)

                # Add connection timeout handler to prevent timeout exception crash.
                self.wifi.callback(WLAN.SMART_CONF_TIMEOUT, handler=self.__onWifiConnectTimeout)

                pass
        except Exception as e:
            self.lastWifiConnectAttempt = None
            print (e)
            pass

    def __readyForNewWifiConnectAttempt(self):
        if self.lastWifiConnectAttempt == None:
            return True
        
        return (time.time() - self.lastWifiConnectAttempt) > 42

    def __onWifiConnectTimeout(self, args):
        self.lastWifiConnectAttempt = None
        pass

    # For debugging
    def __printSecondsLeftToNextConnectAttempt(self):
        secondsLeft = 43 - (time.time() - self.lastWifiConnectAttempt)
        if secondsLeft < 0:
            secondsLeft = 0

        print("Seconds left to be ready for next WIFI connect attempt: " +  str(secondsLeft))

Web调用方/客户端代码,用于向web api发送不同调用的助手模块:

这个mdoule运行后台工作循环,它进行api调用并捕获[Errno 202] EAI_FAIL异常。

代码语言:javascript
复制
from machine import Timer
from hardware import web, unit
from events import commands as cmd
from util import weblog
import ujson
import pycom
import gc
from hardware.wifi_client import getWifiClient

# globals for this file
_background_timer = None
_background_app = None



def get_client():
  client = web.Client()
  client.base_url = "..."
  # client.base_url = "..."
  return client

def send_data(): 
  print ("sending data")
  client = get_client()

  client.headers['Content-Type'] = 'application/json'

  # client.headers['Accept'] = '*/*'
  # client.headers['User-Agent'] = 'PostmanRuntime/7.28.4'
  # client.headers['Host'] = '...'
  # client.headers['Connection'] = 'keep-alive'

  p = cmd.Measure()

  data = {
    'uuid' : unit.ID,
    'value' : round(p, 1),
    'measured': "1970-01-01T00:00:00.000Z"
  }

  response = client.post('ApiMethod', data)
  print (response.text)
  pass


def background_work(o):
  global _background_app
  global wifiClient

  try:
    pycom.rgbled(0)
    gc.collect()

    mfree = gc.mem_free()

    print ("Memfree: " + str(mfree))
    if (getWifiClient().wifi.isconnected()):

      if (mfree < 1000000):
        weblog.warning("Memory low: %d", mfree)
        print("Memory low: %d", mfree)

      send_data()
    
      app = _background_app
      fetch_data(app)
      pycom.rgbled(0x002f00)
       
    else:
      pycom.rgbled(0x2F)
      print ("Not connected to WIFI")
      getWifiClient().connect()

  except Exception as e:
    pycom.rgbled(0x2f0000)
    print("send exception")
    print(e)
    
    pass
  pass

def stop_background():
  global _background_timer
  
  if _background_timer:
    _background_timer.cancel()
    _background_timer = None

  pass

def start_background(app):
  global _background_timer, _background_app

  stop_background()

  _background_app = app
  _background_timer = Timer.Alarm(background_work, s=10, periodic=True)
  pass

HTTP客户端,对api进行HTTP调用:

代码语言:javascript
复制
import _urequest as ureq


class Client:

  def __init__(self):
    self.headers = {}
    self.base_url = ""
    pass

  ...

  def post(self, url, payload):
    print(self.base_url)
    print(self.base_url + url)
    return ureq.post(self.base_url + url, headers = self.headers, json = payload)

  ...

  def base(self, url):
    self.base_url = url

控制台输出

代码语言:javascript
复制
sending data
send exception
[Errno 202] EAI_FAIL
Memfree: 2527712
sending data
send exception
[Errno 202] EAI_FAIL
Memfree: 2527712
sending data

问题

为什么会引发[Errno 202] EAI_FAIL异常?

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2022-01-14 17:51:40

看起来它与DNS有关,如在论坛帖子中所述的在这个答案中

EAI_FAIL与无法解析DNS有关。

它看起来像是根植于getaddrinfo()函数(另一篇论坛帖子)中的特定于Pycom的错误代码。您还会发现在LTE博士中简短地提到了这个问题(请直说到"Pycom“部分)。

我猜这是在你设置client.base_url时调用的?我不认识你从Pycom文档里进口的一些东西。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70110801

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档