Chapter 7: Error Handling (v0.7)
This commit is contained in:
parent
f898236240
commit
9ab5c4a3b3
|
@ -1,3 +1,6 @@
|
|||
import logging
|
||||
from logging.handlers import SMTPHandler, RotatingFileHandler
|
||||
import os
|
||||
from flask import Flask
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
|
@ -11,4 +14,32 @@ migrate = Migrate(app, db)
|
|||
login = LoginManager(app)
|
||||
login.login_view = 'login'
|
||||
|
||||
from app import routes, models
|
||||
if not app.debug:
|
||||
if app.config['MAIL_SERVER']:
|
||||
auth = None
|
||||
if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
|
||||
auth = (app.config['MAIL_USERNAME'], app.config['MAIL_PASSWORD'])
|
||||
secure = None
|
||||
if app.config['MAIL_USE_TLS']:
|
||||
secure = ()
|
||||
mail_handler = SMTPHandler(
|
||||
mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
|
||||
fromaddr='no-reply@' + app.config['MAIL_SERVER'],
|
||||
toaddrs=app.config['ADMINS'], subject='Microblog Failure',
|
||||
credentials=auth, secure=secure)
|
||||
mail_handler.setLevel(logging.ERROR)
|
||||
app.logger.addHandler(mail_handler)
|
||||
|
||||
if not os.path.exists('logs'):
|
||||
os.mkdir('logs')
|
||||
file_handler = RotatingFileHandler('logs/microblog.log', maxBytes=10240,
|
||||
backupCount=10)
|
||||
file_handler.setFormatter(logging.Formatter(
|
||||
'%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
|
||||
file_handler.setLevel(logging.INFO)
|
||||
app.logger.addHandler(file_handler)
|
||||
|
||||
app.logger.setLevel(logging.INFO)
|
||||
app.logger.info('Microblog startup')
|
||||
|
||||
from app import routes, models, errors
|
||||
|
|
|
@ -0,0 +1,13 @@
|
|||
from flask import render_template
|
||||
from app import app, db
|
||||
|
||||
|
||||
@app.errorhandler(404)
|
||||
def not_found_error(error):
|
||||
return render_template('404.html'), 404
|
||||
|
||||
|
||||
@app.errorhandler(500)
|
||||
def internal_error(error):
|
||||
db.session.rollback()
|
||||
return render_template('500.html'), 500
|
10
app/forms.py
10
app/forms.py
|
@ -36,3 +36,13 @@ class EditProfileForm(FlaskForm):
|
|||
username = StringField('Username', validators=[DataRequired()])
|
||||
about_me = TextAreaField('About me', validators=[Length(min=0, max=140)])
|
||||
submit = SubmitField('Submit')
|
||||
|
||||
def __init__(self, original_username, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
self.original_username = original_username
|
||||
|
||||
def validate_username(self, username):
|
||||
if username.data != self.original_username:
|
||||
user = User.query.filter_by(username=self.username.data).first()
|
||||
if user is not None:
|
||||
raise ValidationError('Please use a different username.')
|
||||
|
|
|
@ -84,7 +84,7 @@ def user(username):
|
|||
@app.route('/edit_profile', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def edit_profile():
|
||||
form = EditProfileForm()
|
||||
form = EditProfileForm(current_user.username)
|
||||
if form.validate_on_submit():
|
||||
current_user.username = form.username.data
|
||||
current_user.about_me = form.about_me.data
|
||||
|
|
|
@ -0,0 +1,6 @@
|
|||
{% extends "base.html" %}
|
||||
|
||||
{% block content %}
|
||||
<h1>Not Found</h1>
|
||||
<p><a href="{{ url_for('index') }}">Back</a></p>
|
||||
{% endblock %}
|
|
@ -0,0 +1,7 @@
|
|||
{% extends "base.html" %}
|
||||
|
||||
{% block content %}
|
||||
<h1>An unexpected error has occurred</h1>
|
||||
<p>The administrator has been notified. Sorry for the inconvenience!</p>
|
||||
<p><a href="{{ url_for('index') }}">Back</a></p>
|
||||
{% endblock %}
|
|
@ -6,3 +6,9 @@ class Config(object):
|
|||
SECRET_KEY = os.environ.get('SECRET_KEY') or 'you-will-never-guess'
|
||||
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
|
||||
'sqlite:///' + os.path.join(basedir, 'app.db')
|
||||
MAIL_SERVER = os.environ.get('MAIL_SERVER')
|
||||
MAIL_PORT = int(os.environ.get('MAIL_PORT') or 25)
|
||||
MAIL_USE_TLS = os.environ.get('MAIL_USE_TLS') is not None
|
||||
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
|
||||
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
|
||||
ADMINS = ['your-email@example.com']
|
||||
|
|
Loading…
Reference in New Issue