我是Python的新手,也是新手。我正在尝试编写一个程序,该程序使用请求模块向Dark Sky API请求天气预报,然后使用smtplib将电子邮件中的预测发送给我自己。我已将我的代码截断为仅显示相关部分。到目前为止,我一直无法找到任何答案,所以如果这是重复,我会道歉。下面的代码将函数打印到控制台没有任何问题,但当我尝试将它分配给“body”变量并通过电子邮件发送时,电子邮件是空白的。或者如果我使用str(ds.current)),电子邮件只有“无”作为正文。
如何使其工作,以便电子邮件的正文包含已从API请求的预测?非常感谢,对任何菜鸟错误感到抱歉。
import requests
import json
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
class Darksky():
r = requests.get('https://api.darksky.net/forecast/e01635ccacb5548e3d1fa40403bbb3a5/-45.0312,168.6626?units=ca')
wx_json = r.json()
def __init__(self, source):
self.source = source
print "\n", "-" * 20, source, "-" * 20, "\n"
def current(self):
def summary():
return "CURRENT WEATHER:"
x = self.wx_json['currently']['summary']
return x
# I have tried using print instead of return but that did not work either.
def temp():
return "TEMPERATURE:"
y = self.wx_json['currently']['temperature']
return y
summary()
temp()
ds = Darksky("DARKSKY WX")
fromaddr = "watsonthevirtualbutler@gmail.com"
toaddr = "matt@peakpixel.nz"
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = "YOUR DAILY WEATHER, SIR."
body = ds.current()
# This is where I am trying to save the function result as a string that can be emailed.
# I have tried using "str(ds.current())" but that just returns "none".
print body
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, "virtualbutler")
text = msg.as_string()
msg = "CAN YOU HEAR ME, SIR?"
server.sendmail(fromaddr, toaddr, text)
server.quit()
答案 0 :(得分:0)
您的summary()
和temp()
有两个return
运营商,而只有一个return
可以接受。如果您希望your_function()
返回少量值,则可以执行以下操作:return {"first_parameter": "first_value", "second_parameter": "second_value"}
,然后将每个值调用为your_function()["first_parameter"]
或your_function()["second_parameter"]
尝试以下代码并告诉我结果:
class Darksky():
r = requests.get('https://api.darksky.net/forecast/e01635ccacb5548e3d1fa40403bbb3a5/-45.0312,168.6626?units=ca')
wx_json = r.json()
def __init__(self, source):
self.source = source
print "\n", "-" * 20, source, "-" * 20, "\n"
def current(self):
return "CURRENT WEATHER: {0}. TEMPERATURE: {1}".format(self.wx_json['currently']['summary'], self.wx_json['currently']['temperature'])
ds = Darksky("DARKSKY WX")
body = ds.current()