首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python 云函数显示调用失败,无法正常运行?

Python 云函数显示调用失败,无法正常运行?

提问于 2022-02-07 15:44:03
回答 0关注 0查看 270
代码语言:python
复制
#!/usr/bin/env python3.8
# -*- encoding: utf-8 -*-

import requests
from requests import exceptions
import json
import time



class NcovReport:
    def __init__(self, token, keys=None):
    # def main(self, token, keys=None):
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.110 Safari/537.36",
            "Content-Type": "application/json;charset=utf-8",
            "ncov-access-token": token
        }
        self.keys = keys
        self.data = self.getLast()
        try:
            self.codeId = self.data["address"].pop("_id", None)
        except TypeError as e:
            print("打卡失败,请登录再重试!," +
                  time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            if keys is not None:
                self.sendMsg("今日打卡失败,请登录小程序打卡")
        else:
            reportStatus = self.dailyReport()
            if keys is not None:
                self.sendMsg(reportStatus)


    def getLast(self):
        """
        通过上一次打卡提交的数据来获取这次该提交的数据
        """
        # 上一次的报告情况
        lastReport = 'https://www.ioteams.com/ncov/api/users/last-report'
        try:
            response = requests.get(lastReport, headers=self.headers)
        except exceptions.HTTPError as e:
            return e
        else:
            try:
                req = response.json()["data"]["data"]
            except ValueError as e:
                return e
            else:
                unneceInfo = ["_id", "user", "company",
                              "created_at", "updated_at", "__v"]
                for i in unneceInfo:
                    req.pop(i, None)
                return req

    def dailyReport(self):
        """
        每天的第一次日报,每日仅一次
        之后再请求就会403
        """
        link = 'https://www.ioteams.com/ncov/api/users/dailyReport'
        response = requests.post(
            link, headers=self.headers, data=json.dumps(self.data))
        req = response.json()
        if req['code'] == 403:
            print(req['msg'].split(',')[0], end=",")
            print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            return req['msg']
        else:
            try:
                self.codeId = req['data']['data']['_id']
            except KeyError:
                print(req['msg'], end=",")
                return req['msg']
            except Exception as E:
                print(E, "打卡失败,请登录小程序检查", end=",")
                return "打卡失败,请登录小程序检查打卡"
            else:
                print(req['msg'], end=",")
                return req['msg']
            finally:
                print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

    def sendMsg(self, status):
        """
        通过Server酱推送至WeChat
        """
        if status == 'success':
            status = "今日打卡成功"
        payload = {
            'text': status,
            'desp': """
        """}
        reqUrl = 'https://sc.ftqq.com/' + self.keys + ".send"
        push = requests.post(reqUrl, data=payload)

def main_handler(event, context):
    usersInfo = open('./conf.ini',
                     encoding='UTF-8').read().split()
    for info in usersInfo:
        spread = info.split(':')
        print(spread[1], end=',')
        if spread[2] == '':
            NcovReport(spread[0])
        else:
            NcovReport(spread[0], spread[2])




以上程序运行之后,测试失败,但是再本地运行正常,不知道出现了什么问题,麻烦各位不吝赐教

以下为执行日志:

START RequestId: 6b0e9c9f-14ac-43a4-a3a5-d85d9450c45b

Init Report RequestId: 6b0e9c9f-14ac-43a4-a3a5-d85d9450c45b Coldstart: 893ms (PullCode: 96ms InitRuntime: 12ms InitFunction: 785ms) Memory: 128MB MemUsage: 16.27MB

wyh,Starting new HTTPS connection (1): www.ioteams.com:443

ERROR RequestId:6b0e9c9f-14ac-43a4-a3a5-d85d9450c45b Result:{"errorCode":1,"errorMessage":"user code exception caught","stackTrace":"Traceback (most recent call last):\n  File \"/var/lang/python3/lib/python3.6/site-packages/urllib3/util/connection.py\", line 80, in create_connection\n    raise err\n  File \"/var/lang/python3/lib/python3.6/site-packages/urllib3/util/connection.py\", line 70, in create_connection\n    sock.connect(sa)\nOSError: [Errno 101] Network is unreachable\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File \"/var/lang/python3/lib/python3.6/site-packages/urllib3/connectionpool.py\", line 600, in urlopen\n    chunked=chunked)\n  File \"/var/lang/python3/lib/python3.6/site-packages/urllib3/connectionpool.py\", line 343, in _make_request\n    self._validate_conn(conn)\n  File \"/var/lang/python3/lib/python3.6/site-packages/urllib3/connectionpool.py\", line 839, in _validate_conn\n    conn.connect()\n  File \"/var/lang/python3/lib/python3.6/site-packages/urllib3/connection.py\", line 301, in connect\n    conn = self._new_conn()\n  File \"/var/lang/python3/lib/python3.6/site-packages/urllib3/connection.py\", line 168, in _new_conn\n    self, \"Failed to establish a new connection: %s\" % e)\nurllib3.exceptions.NewConnectionError: \u003curllib3.connection.VerifiedHTTPSConnection object at 0x7f5ca1e4bfd0\u003e: Failed to establish a new connection: [Errno 101] Network is unreachable\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File \"/var/lang/python3/lib/python3.6/site-packages/requests/adapters.py\", line 449, in send\n    timeout=timeout\n  File \"/var/lang/python3/lib/python3.6/site-packages/urllib3/connectionpool.py\", line 638, in urlopen\n    _stacktrace=sys.exc_info()[2])\n  File \"/var/lang/python3/lib/python3.6/site-packages/urllib3/util/retry.py\", line 399, in increment\n    raise MaxRetryError(_pool, url, error or ResponseError(cause))\nurllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='www.ioteams.com', port=443): Max retries exceeded with url: /ncov/api/users/last-report (Caused by NewConnectionError('\u003curllib3.connection.VerifiedHTTPSConnection object at 0x7f5ca1e4bfd0\u003e: Failed to establish a new connection: [Errno 101] Network is unreachable',))\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File \"/var/runtime/python3/bootstrap.py\", line 176, in handle\n    ret = self.real_handler(event, context)\n  File \"/var/user/index.py\", line 16, in main_handler\n    NcovReport(spread[0])\n  File \"/var/user/index.py\", line 30, in __init__\n    self.data = self.getLast()\n  File \"/var/user/index.py\", line 51, in getLast\n    response = requests.get(lastReport, headers=self.headers)\n  File \"/var/lang/python3/lib/python3.6/site-packages/requests/api.py\", line 75, in get\n    return request('get', url, params=params, **kwargs)\n  File \"/var/lang/python3/lib/python3.6/site-packages/requests/api.py\", line 60, in request\n    return session.request(method=method, url=url, **kwargs)\n  File \"/var/lang/python3/lib/python3.6/site-packages/requests/sessions.py\", line 533, in request\n    resp = self.send(prep, **send_kwargs)\n  File \"/var/lang/python3/lib/python3.6/site-packages/requests/sessions.py\", line 646, in send\n    r = adapter.send(request, **kwargs)\n  File \"/var/lang/python3/lib/python3.6/site-packages/requests/adapters.py\", line 516, in send\n    raise ConnectionError(e, request=request)\nrequests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.ioteams.com', port=443): Max retries exceeded with url: /ncov/api/users/last-report (Caused by NewConnectionError('\u003curllib3.connection.VerifiedHTTPSConnection object at 0x7f5ca1e4bfd0\u003e: Failed to establish a new connection: [Errno 101] Network is unreachable',))","statusCode":430}

END RequestId:6b0e9c9f-14ac-43a4-a3a5-d85d9450c45b

Report RequestId:6b0e9c9f-14ac-43a4-a3a5-d85d9450c45b Duration:129755ms Memory:128MB MemUsage:16.530800MB

回答

和开发者交流更多问题细节吧,去 写回答
相关文章

相似问题

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