flask 邮件发送问题

发布于 2022-09-06 01:19:45 字数 5065 浏览 8 评论 0

python 代码:hello.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2017/10/16 13:23
# @Author  : mr.xu
# @Site    : 
# @File    : hello.py
# @Software: PyCharm Community Edition
from flask import Flask,render_template
from flask_script import  Manager
from flask_bootstrap import  Bootstrap
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField
from wtforms.validators import Required
from flask import session,redirect,url_for
from flask_sqlalchemy import SQLAlchemy
import os
from flask_migrate import Migrate,MigrateCommand
from flask_mail import  Mail,Message

app=Flask(__name__)
app.config['SECRET_KEY']='hard to guess string'
manager=Manager(app)
bootstrap=Bootstrap(app)

#配置数据库并初始化
basedir=os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///'+os.path.join(basedir,'data.sqlite')
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWW']=True
db=SQLAlchemy(app)
# 数据库迁移
migrate=Migrate(app,db)
manager.add_command('db',MigrateCommand)


# 配置Flask-mail并初始化
app.config['MAIL_SERVER']='stmp.163.com'
app.config['MAIL_PORT']=465
app.config['MAIL_USE_SSL']=True
app.config['MAIL_USERNAME']='xuhenglu0220@163.com'
app.config['MAIL_PASSWORD']='XULU0220'
mail=Mail(app)
# 邮件支持
app.config['FLASK_MAIL_SUBJECT_PREFIX']=['Flasky']
app.config['FLASK_MAIL_SENDER']='21533983@qq.com'
def send_email(to,subject,template,**kwargs):
    msg=Message(app.config['FLASK_MAIL_SUBJECT_PREFIX']+subject,sender=app.config['FLASK_MAIL_SENDER'],recipients=[to])
    msg.body=render_template(template+'.txt',**kwargs)
    msg.html=render_template(template+'.html',**kwargs)
    mail.send(msg)

class Role(db.Model):
    __tablename__='roles'
    id=db.Column(db.Integer,primary_key=True)
    name=db.Column(db.String(64),unique=True)
    users=db.relationship('User',backref='role',lazy='dynamic')
    def __repr__(self):
        return '<Role%r>'%self.name

class User(db.Model):
    __tablename__='users'
    id=db.Column(db.Integer,primary_key=True)
    username=db.Column(db.String(64),unique=True,index=True)
    role_id=db.Column(db.Integer,db.ForeignKey('roles.id'))
    def __repr__(self):
        return '<User%r>'%self.username

class NameForm(FlaskForm):
    name=StringField('what is your name?',validators=[Required()])
    submit=SubmitField('Submit')

@app.route('/',methods=['GET','POST'])
def index():
    form=NameForm()
    if form.validate_on_submit():
        user=User.query.filter_by(username=form.name.data).first()
        if user is None:
            user=User(username=form.name.data)
            db.session.add(user)
            session['known']=False
            if app.config['FLASK_ADMIN']:
                send_email(app.config['FLASK_ADMIN'],'New User','mail/new_user',user=user)
        else:
            session['known']=True
        session['name']=form.name.data
        return redirect(url_for('index'))
    return render_template('index.html',form=form,name=session.get('name'),
                           known=session.get('known',False))

if __name__=='__main__':
    app.run(debug=True)
    # manager.run()
  

这个是模板index.html

{%extends "base.html"%}
{%import"bootstrap/wtf.html" as wtf%}

{%block title%}Flasky-Index{%endblock%}

{%block page_content%}
<div class="page-header">
    <h1>Hello,{%if name%}{{name}}{% else %}Stranger{%endif%}!</h1>
    {%if not known%}
    <p>Pleased to meet you!</p>
    {%else%}
    <p>Happy to see you again!</p>
    {%endif%}
</div>
{{wtf.quick_form(form)}}
{%endblock%}

模板加载正常但是发送邮件部分不对
报错:

Traceback (most recent call last):
  File "D:\python\pythonObject\Flasky\venv\lib\site-packages\flask\app.py", line 1997, in __call__
    return self.wsgi_app(environ, start_response)
  File "D:\python\pythonObject\Flasky\venv\lib\site-packages\flask\app.py", line 1985, in wsgi_app
    response = self.handle_exception(e)
  File "D:\python\pythonObject\Flasky\venv\lib\site-packages\flask\app.py", line 1540, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "D:\python\pythonObject\Flasky\venv\lib\site-packages\flask\app.py", line 1982, in wsgi_app
    response = self.full_dispatch_request()
  File "D:\python\pythonObject\Flasky\venv\lib\site-packages\flask\app.py", line 1614, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "D:\python\pythonObject\Flasky\venv\lib\site-packages\flask\app.py", line 1517, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "D:\python\pythonObject\Flasky\venv\lib\site-packages\flask\app.py", line 1612, in full_dispatch_request
    rv = self.dispatch_request()
  File "D:\python\pythonObject\Flasky\venv\lib\site-packages\flask\app.py", line 1598, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "D:\python\pythonObject\Flasky\hello.py", line 80, in index
    if app.config['FLASK_ADMIN']:
KeyError: 'FLASK_ADMIN'

错误提示为:KeyError: 'FLASK_ADMIN'
哪里的错?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不如归去 2022-09-13 01:19:45

你需要定义app.config['FLASK_ADMIN']

暖心男生 2022-09-13 01:19:45

哦,这个配置是什么意思?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文