首页 > 解决方案 > 使用 os.getenv 时“函数”对象不可下标

问题描述

我再次提出另一个(可能)愚蠢的问题。

我目前正在完成一项课程作业,并被要求在满足条件时通过 Twilio 发送短信。

这个想法是当满足条件时它会发送一条短信:

(仅显示相关的代码片段,因为我已将其缩小到导致问题的这部分)

from notification_manager import NotificationManager

nm = NotificationManager()

    if flight.price <= destination["lowestPrice"]:
        nm.send_sms(
            message = f"LOW PRICE ALERT! ONLY €{flight.price} to fly from {flight.origin_city}-{flight.origin_airport} to {flight.destination_city}-{flight.destination_airport}, from {flight.out_date} to {flight.return_date}." 
        )

在 NotificationManager 类上是我遇到问题的地方,但是,当我点击运行时,它告诉我这个错误:

  File "c:\Users\Speakr\Desktop\Py101\Day31-40\Day39&40 - Flight club & deal finder\flight-deals-start\notification_manager.py", line 11, in <module>
    SID = os.getenv["TWILIO_SID"]
TypeError: 'function' object is not subscriptable

这是我的通知管理器代码:

#----IMPORTS----#

import os
from dotenv import load_dotenv
from twilio.rest import Client

#----CONSTANTS & FUNCTIONS----#

load_dotenv()

SID = os.getenv["TWILIO_SID"]
AUTH_TOKEN = os.getenv["TWILIO_AUTH_TOKEN"]
VIRTUAL_NUMBER = os.getenv["TWILIO_VIRTUAL_NUMBER"]
VERIFIED_NUMBER = os.getenv["TWILIO_VERIFIED_NUMBER"]

class NotificationManager:
    #This class will be used to send the SMS when the conditions are met. 
    def __init__(self) -> None:
        #This is us logging into the client with our credentials
        self.client = Client(SID, AUTH_TOKEN)

    def send_SMS(self, message):
        #This method will send the message, the message will be created with our client credentials
        #as stated above, the message itself is defined in main.py and passed here as an argument
        #and then the message is sent from our TWILIO_VIRTUAL to our REAL number
        message = self.client.messages.create(
            body = message,
            from_=VIRTUAL_NUMBER,
            to=VERIFIED_NUMBER,
        )
        #Error handling, will print if successfully sent
        print(message.sid)

起初我认为可以,一定是常量使用与 os.getenv[""] 部分相同的名称。因为那是错误指向的地方。但即使在改变它们之后:

Twilio_SID = os.getenv["Twilio_SID"] is now just SID = os.getenv["Twilio_SID"]

我仍然遇到错误。任何新鲜的眼睛都想在这里帮助我。我真的很难过。

标签: python-3.xfunction

解决方案


推荐阅读