python - 在 Rasbian 上使用烧瓶发送电子邮件(温度传感 API)
问题描述
当我添加 send_mail() 并尝试运行它时脚本中断,但它只返回“内部服务器错误”
以下 python 文件用于从连接到树莓派的面包板上的设备中提取温度,并检查温度是否高于华氏 50 度,如果为真则发送电子邮件。
温度部分工作正常(woo),但发送电子邮件“sendemail()”的部分正在破坏脚本。除了内部服务器错误和 gunicorn 日志外,我似乎找不到错误。
我用来运行烧瓶的命令:
sudo gunicorn 温度:app -b 0.0.0.0:80 --error-logfile /error.log --access-logfile /access.log --log-level info
温度.py
"""
Copyright (c) 2016, Tim Fernando
All rights reserved.
Licensed under the BSD 2 Clause License
- https://opensource.org/licenses/BSD-2-Clause
"""
import logging
import sys
import time
from datetime import datetime
import os
from os import listdir, system
from flask import Flask, jsonify
from flask.ext.cors import CORS
from flask_mail import Mail, Message
#####################################
DEVICE_FOLDER = "/sys/bus/w1/devices/"
DEVICE_SUFFIX = "/w1_slave"
WAIT_INTERVAL = 45
ALLOWABLE_ORIGINS = ["https://freeboard.io"]
system('modprobe w1-gpio')
system('modprobe w1-therm')
app = Flask(__name__)
cors_app = CORS(app, resources={r"/*": {"origins": ALLOWABLE_ORIGINS}})
# Mail
mail_settings = {
"MAIL_SERVER": 'smtp.gmail.com',
"MAIL_PORT": 587,
"MAIL_USE_TLS": False,
"MAIL_USE_SSL": True,
"MAIL_USERNAME": 'removed',
"MAIL_PASSWORD": 'removed'
#"MAIL_USERNAME": os.environ.get('EMAIL'),
#"MAIL_PASSWORD": os.environ.get('EMAIL_PASSWORD')
}
app.config.update(mail_settings)
mail = Mail(app)
@app.route("/")
def temperature():
device = guess_temperature_sensor()
print datetime.now(), "Request received"
return jsonify(read_temperature(device))
def send_mail():
with app.app_context():
msg = Message(subject="Hello",
sender=app.config.get("hello"),
recipients=["removed@gmail.com"], # replace with your email for testing
body="This is a test email I sent with Gmail and Python!")
mail.send(msg)
def guess_temperature_sensor():
"""
Try guessing the location of the installed temperature sensor
"""
devices = listdir(DEVICE_FOLDER)
devices = [device for device in devices if device.startswith('28-')]
if devices:
# print "Found", len(devices), "devices which maybe temperature sensors."
return DEVICE_FOLDER + devices[0] + DEVICE_SUFFIX
else:
sys.exit("Sorry, no temperature sensors found")
def raw_temperature(device):
"""
Get a raw temperature reading from the temperature sensor
"""
raw_reading = None
with open(device, 'r') as sensor:
raw_reading = sensor.readlines()
return raw_reading
def read_temperature(device):
lines = raw_temperature(device)
# Keep retrying till we get a YES from the thermometer
# 1. Make sure that the response is not blank
# 2. Make sure the response has at least 2 lines
# 3. Make sure the first line has a "YES" at the end
while not lines and len(lines) < 2 and lines[0].strip()[-3:] != 'YES':
# If we haven't got a valid response, wait for the WAIT_INTERVAL
# (seconds) and try again.
time.sleep(WAIT_INTERVAL)
lines = raw_temperature()
# Split out the raw temperature number
temperature = lines[1].split('t=')[1]
# Check that the temperature is not invalid
if temperature != -1:
temperature_celsius = round(float(temperature) / 1000.0, 1)
temperature_fahrenheit = round((temperature_celsius * 1.8) + 32.0, 1)
""" this is causing the issue,
If i remove this statement the temperature updates fine. """
if temperature_fahrenheit >= 50:
send_mail()
response = {'celsius': temperature_celsius,
'fahrenheit': temperature_fahrenheit}
return response
if __name__ == "__main__":
cors_app.run()
解决方案
您mail.send(msg)
的缩进似乎错误。它需要在with
循环内。
def send_mail():
with app.app_context():
msg = Message(subject="Hello",
sender=app.config.get("hello"),
recipients=["removed@gmail.com"], # replace with your email for testing
body="This is a test email I sent with Gmail and Python!")
mail.send(msg)
推荐阅读
- slurm - 如何限制slurm的cpu使用率?
- javascript - javascript async/await 输出顺序
- java - 摆脱可选 [] 字符串?
- c - MPI_SendRecv 时序
- flutter - Flutter web集成测试CORS XMLHttpRequest报错
- node.js - 每次我运行配置文件时它都不起作用
- apache - 重写规则问题/图像重写 htaccess
- video - 如何在 FFMPEG 中将“简单”不透明度应用于组合(分层)mp4
- ruby-on-rails - 来自键值对的 Json JBuilder 数组
- reactjs - Material UI 覆盖 Accordion CSS