Skip to content

Commit

Permalink
Chapter 13: I18n and L10n (v0.13)
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelgrinberg committed Nov 11, 2022
1 parent a650e6f commit 8a56c34
Show file tree
Hide file tree
Showing 20 changed files with 402 additions and 79 deletions.
11 changes: 10 additions & 1 deletion app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import logging
from logging.handlers import SMTPHandler, RotatingFileHandler
import os
from flask import Flask
from flask import Flask, request
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_mail import Mail
from flask_bootstrap import Bootstrap
from flask_moment import Moment
from flask_babel import Babel, lazy_gettext as _l
from config import Config

app = Flask(__name__)
Expand All @@ -16,9 +17,11 @@
migrate = Migrate(app, db)
login = LoginManager(app)
login.login_view = 'login'
login.login_message = _l('Please log in to access this page.')
mail = Mail(app)
bootstrap = Bootstrap(app)
moment = Moment(app)
babel = Babel(app)

if not app.debug:
if app.config['MAIL_SERVER']:
Expand Down Expand Up @@ -48,4 +51,10 @@
app.logger.setLevel(logging.INFO)
app.logger.info('Microblog startup')


@babel.localeselector
def get_locale():
return request.accept_languages.best_match(app.config['LANGUAGES'])


from app import routes, models, errors
38 changes: 38 additions & 0 deletions app/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import os
import click
from app import app


@app.cli.group()
def translate():
"""Translation and localization commands."""
pass


@translate.command()
@click.argument('lang')
def init(lang):
"""Initialize a new language."""
if os.system('pybabel extract -F babel.cfg -k _l -o messages.pot .'):
raise RuntimeError('extract command failed')
if os.system(
'pybabel init -i messages.pot -d app/translations -l ' + lang):
raise RuntimeError('init command failed')
os.remove('messages.pot')


@translate.command()
def update():
"""Update all languages."""
if os.system('pybabel extract -F babel.cfg -k _l -o messages.pot .'):
raise RuntimeError('extract command failed')
if os.system('pybabel update -i messages.pot -d app/translations'):
raise RuntimeError('update command failed')
os.remove('messages.pot')


@translate.command()
def compile():
"""Compile all languages."""
if os.system('pybabel compile -d app/translations'):
raise RuntimeError('compile command failed')
3 changes: 2 additions & 1 deletion app/email.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from threading import Thread
from flask import render_template
from flask_mail import Message
from flask_babel import _
from app import app, mail


Expand All @@ -18,7 +19,7 @@ def send_email(subject, sender, recipients, text_body, html_body):

def send_password_reset_email(user):
token = user.get_reset_password_token()
send_email('[Microblog] Reset Your Password',
send_email(_('[Microblog] Reset Your Password'),
sender=app.config['ADMINS'][0],
recipients=[user.email],
text_body=render_template('email/reset_password.txt',
Expand Down
48 changes: 26 additions & 22 deletions app/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,51 +3,55 @@
TextAreaField
from wtforms.validators import ValidationError, DataRequired, Email, EqualTo, \
Length
from flask_babel import _, lazy_gettext as _l
from app.models import User


class LoginForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
password = PasswordField('Password', validators=[DataRequired()])
remember_me = BooleanField('Remember Me')
submit = SubmitField('Sign In')
username = StringField(_l('Username'), validators=[DataRequired()])
password = PasswordField(_l('Password'), validators=[DataRequired()])
remember_me = BooleanField(_l('Remember Me'))
submit = SubmitField(_l('Sign In'))


class RegistrationForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
email = StringField('Email', validators=[DataRequired(), Email()])
password = PasswordField('Password', validators=[DataRequired()])
username = StringField(_l('Username'), validators=[DataRequired()])
email = StringField(_l('Email'), validators=[DataRequired(), Email()])
password = PasswordField(_l('Password'), validators=[DataRequired()])
password2 = PasswordField(
'Repeat Password', validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Register')
_l('Repeat Password'), validators=[DataRequired(),
EqualTo('password')])
submit = SubmitField(_l('Register'))

def validate_username(self, username):
user = User.query.filter_by(username=username.data).first()
if user is not None:
raise ValidationError('Please use a different username.')
raise ValidationError(_('Please use a different username.'))

def validate_email(self, email):
user = User.query.filter_by(email=email.data).first()
if user is not None:
raise ValidationError('Please use a different email address.')
raise ValidationError(_('Please use a different email address.'))


class ResetPasswordRequestForm(FlaskForm):
email = StringField('Email', validators=[DataRequired(), Email()])
submit = SubmitField('Request Password Reset')
email = StringField(_l('Email'), validators=[DataRequired(), Email()])
submit = SubmitField(_l('Request Password Reset'))


class ResetPasswordForm(FlaskForm):
password = PasswordField('Password', validators=[DataRequired()])
password = PasswordField(_l('Password'), validators=[DataRequired()])
password2 = PasswordField(
'Repeat Password', validators=[DataRequired(), EqualTo('password')])
submit = SubmitField('Request Password Reset')
_l('Repeat Password'), validators=[DataRequired(),
EqualTo('password')])
submit = SubmitField(_l('Request Password Reset'))


class EditProfileForm(FlaskForm):
username = StringField('Username', validators=[DataRequired()])
about_me = TextAreaField('About me', validators=[Length(min=0, max=140)])
submit = SubmitField('Submit')
username = StringField(_l('Username'), validators=[DataRequired()])
about_me = TextAreaField(_l('About me'),
validators=[Length(min=0, max=140)])
submit = SubmitField(_l('Submit'))

def __init__(self, original_username, *args, **kwargs):
super(EditProfileForm, self).__init__(*args, **kwargs)
Expand All @@ -57,13 +61,13 @@ 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.')
raise ValidationError(_('Please use a different username.'))


class EmptyForm(FlaskForm):
submit = SubmitField('Submit')


class PostForm(FlaskForm):
post = TextAreaField('Say something', validators=[DataRequired()])
submit = SubmitField('Submit')
post = TextAreaField(_l('Say something'), validators=[DataRequired()])
submit = SubmitField(_l('Submit'))
44 changes: 24 additions & 20 deletions app/routes.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from datetime import datetime
from flask import render_template, flash, redirect, url_for, request
from flask import render_template, flash, redirect, url_for, request, g
from flask_login import login_user, logout_user, current_user, login_required
from werkzeug.urls import url_parse
from flask_babel import _, get_locale
from app import app, db
from app.forms import LoginForm, RegistrationForm, EditProfileForm, \
EmptyForm, PostForm, ResetPasswordRequestForm, ResetPasswordForm
Expand All @@ -14,6 +15,7 @@ def before_request():
if current_user.is_authenticated:
current_user.last_seen = datetime.utcnow()
db.session.commit()
g.locale = str(get_locale())


@app.route('/', methods=['GET', 'POST'])
Expand All @@ -25,7 +27,7 @@ def index():
post = Post(body=form.post.data, author=current_user)
db.session.add(post)
db.session.commit()
flash('Your post is now live!')
flash(_('Your post is now live!'))
return redirect(url_for('index'))
page = request.args.get('page', 1, type=int)
posts = current_user.followed_posts().paginate(
Expand All @@ -34,7 +36,7 @@ def index():
if posts.has_next else None
prev_url = url_for('index', page=posts.prev_num) \
if posts.has_prev else None
return render_template('index.html', title='Home', form=form,
return render_template('index.html', title=_('Home'), form=form,
posts=posts.items, next_url=next_url,
prev_url=prev_url)

Expand All @@ -49,8 +51,9 @@ def explore():
if posts.has_next else None
prev_url = url_for('explore', page=posts.prev_num) \
if posts.has_prev else None
return render_template('index.html', title='Explore', posts=posts.items,
next_url=next_url, prev_url=prev_url)
return render_template('index.html', title=_('Explore'),
posts=posts.items, next_url=next_url,
prev_url=prev_url)


@app.route('/login', methods=['GET', 'POST'])
Expand All @@ -61,14 +64,14 @@ def login():
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user is None or not user.check_password(form.password.data):
flash('Invalid username or password')
flash(_('Invalid username or password'))
return redirect(url_for('login'))
login_user(user, remember=form.remember_me.data)
next_page = request.args.get('next')
if not next_page or url_parse(next_page).netloc != '':
next_page = url_for('index')
return redirect(next_page)
return render_template('login.html', title='Sign In', form=form)
return render_template('login.html', title=_('Sign In'), form=form)


@app.route('/logout')
Expand All @@ -87,9 +90,9 @@ def register():
user.set_password(form.password.data)
db.session.add(user)
db.session.commit()
flash('Congratulations, you are now a registered user!')
flash(_('Congratulations, you are now a registered user!'))
return redirect(url_for('login'))
return render_template('register.html', title='Register', form=form)
return render_template('register.html', title=_('Register'), form=form)


@app.route('/reset_password_request', methods=['GET', 'POST'])
Expand All @@ -101,10 +104,11 @@ def reset_password_request():
user = User.query.filter_by(email=form.email.data).first()
if user:
send_password_reset_email(user)
flash('Check your email for the instructions to reset your password')
flash(
_('Check your email for the instructions to reset your password'))
return redirect(url_for('login'))
return render_template('reset_password_request.html',
title='Reset Password', form=form)
title=_('Reset Password'), form=form)


@app.route('/reset_password/<token>', methods=['GET', 'POST'])
Expand All @@ -118,7 +122,7 @@ def reset_password(token):
if form.validate_on_submit():
user.set_password(form.password.data)
db.session.commit()
flash('Your password has been reset.')
flash(_('Your password has been reset.'))
return redirect(url_for('login'))
return render_template('reset_password.html', form=form)

Expand Down Expand Up @@ -147,12 +151,12 @@ def edit_profile():
current_user.username = form.username.data
current_user.about_me = form.about_me.data
db.session.commit()
flash('Your changes have been saved.')
flash(_('Your changes have been saved.'))
return redirect(url_for('edit_profile'))
elif request.method == 'GET':
form.username.data = current_user.username
form.about_me.data = current_user.about_me
return render_template('edit_profile.html', title='Edit Profile',
return render_template('edit_profile.html', title=_('Edit Profile'),
form=form)


Expand All @@ -163,14 +167,14 @@ def follow(username):
if form.validate_on_submit():
user = User.query.filter_by(username=username).first()
if user is None:
flash('User {} not found.'.format(username))
flash(_('User %(username)s not found.', username=username))
return redirect(url_for('index'))
if user == current_user:
flash('You cannot follow yourself!')
flash(_('You cannot follow yourself!'))
return redirect(url_for('user', username=username))
current_user.follow(user)
db.session.commit()
flash('You are following {}!'.format(username))
flash(_('You are following %(username)s!', username=username))
return redirect(url_for('user', username=username))
else:
return redirect(url_for('index'))
Expand All @@ -183,14 +187,14 @@ def unfollow(username):
if form.validate_on_submit():
user = User.query.filter_by(username=username).first()
if user is None:
flash('User {} not found.'.format(username))
flash(_('User %(username)s not found.', username=username))
return redirect(url_for('index'))
if user == current_user:
flash('You cannot unfollow yourself!')
flash(_('You cannot unfollow yourself!'))
return redirect(url_for('user', username=username))
current_user.unfollow(user)
db.session.commit()
flash('You are not following {}.'.format(username))
flash(_('You are not following %(username)s.', username=username))
return redirect(url_for('user', username=username))
else:
return redirect(url_for('index'))
4 changes: 2 additions & 2 deletions app/templates/404.html
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{% extends "base.html" %}

{% block app_content %}
<h1>Not Found</h1>
<p><a href="{{ url_for('index') }}">Back</a></p>
<h1>{{ _('Not Found') }}</h1>
<p><a href="{{ url_for('index') }}">{{ _('Back') }}</a></p>
{% endblock %}
6 changes: 3 additions & 3 deletions app/templates/500.html
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{% extends "base.html" %}

{% block app_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>
<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 %}
11 changes: 7 additions & 4 deletions app/templates/_post.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@
</a>
</td>
<td>
<a href="{{ url_for('user', username=post.author.username) }}">
{{ post.author.username }}
</a>
said {{ moment(post.timestamp).fromNow() }}:
{% set user_link %}
<a href="{{ url_for('user', username=post.author.username) }}">
{{ post.author.username }}
</a>
{% endset %}
{{ _('%(username)s said %(when)s',
username=user_link, when=moment(post.timestamp).fromNow()) }}
<br>
{{ post.body }}
</td>
Expand Down
Loading

0 comments on commit 8a56c34

Please sign in to comment.