在Rasbian上使用烧瓶发送电子邮件(温度传感API)

时间:2019-03-13 02:09:08

标签: python flask

当我添加send_mail()并尝试运行它时,脚本会中断,但它只会返回“内部服务器错误”

以下python文件用于从连接到树莓派的面包板上的设备获取温度,并检查温度是否高于50华氏度(如果为true则发送电子邮件)。

温度部分可以正常工作(woo),但是发送电子邮件“ sendemail()”的部分正在破坏脚本。除了内部服务器错误和Gunicorn日志外,我似乎找不到该错误。

我用来运行flask的命令:

  

sudo gunicorn temperature:app -b 0.0.0.0:80 --error-logfile /error.log   --access-logfile /access.log-日志级别信息

temperature.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()

1 个答案:

答案 0 :(得分:1)

您的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)