Отправка электронной почты с помощью колбы на Rasbian (Sensor Sensing API) - PullRequest
0 голосов
/ 13 марта 2019

Сценарий прерывается, когда я добавляю send_mail () и пытаюсь его запустить, но он просто возвращает «внутренняя ошибка сервера»

Следующий файл python используется для получения температуры от устройства на макете, подключенного к Raspberry Pi, и проверки, если температура выше 50 градусов по Фаренгейту, если true, тогда он отправляет электронное письмо.

Температурная часть работает нормально (woo), но часть, которая отправляет электронное письмо "sendemail ()", нарушает работу сценария. Кажется, я не могу найти ошибку, за исключением внутренней ошибки сервера и журнала gunicorn.

Команда, которую я использую для запуска колбы:

температура sudo gunicorn: 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 Ответ

1 голос
/ 13 марта 2019

Ваш 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...