Skip to content

Commit

Permalink
update email functions, register template
Browse files Browse the repository at this point in the history
  • Loading branch information
NeoWzk committed Feb 17, 2019
1 parent 82fcb29 commit 3de146f
Show file tree
Hide file tree
Showing 26 changed files with 429 additions and 124 deletions.
10 changes: 10 additions & 0 deletions .idea/dataSources.local.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 14 additions & 0 deletions .idea/dataSources.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

246 changes: 142 additions & 104 deletions .idea/workspace.xml

Large diffs are not rendered by default.

Binary file modified __pycache__/config.cpython-35.pyc
Binary file not shown.
4 changes: 1 addition & 3 deletions app/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from flask_sqlalchemy import SQLAlchemy
from flask_bootstrap import Bootstrap
from flask_mail import Mail
from flask_login import LoginManager, LOGIN_MESSAGE_CATEGORY, LOGIN_MESSAGE
from flask_login import LoginManager
from config import config

moment = Moment()
Expand All @@ -20,8 +20,6 @@ def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
LOGIN_MESSAGE_CATEGORY = 'info'
LOGIN_MESSAGE = 'This page needs authentications'

moment.init_app(app)
db.init_app(app)
Expand Down
Binary file modified app/__pycache__/__init__.cpython-35.pyc
Binary file not shown.
Binary file added app/__pycache__/__init__.cpython-37.pyc
Binary file not shown.
Binary file added app/__pycache__/mails.cpython-35.pyc
Binary file not shown.
Binary file modified app/__pycache__/models.cpython-35.pyc
Binary file not shown.
5 changes: 3 additions & 2 deletions app/mails.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@
app = create_app(os.environ.get('FLASK_CONFIG') or 'default')


def async_mail(app, msg):
def async_mail(msg):
with app.app_context():
mail.send(msg)


def send_mail(subject, recipients, msg_template, **kwargs):
msg = Message(subject=subject, recipients=[recipients])
msg.html = render_template(msg_template + '.html', **kwargs)
th = Thread(target=async_mail, args=(app, msg))
th = Thread(target=async_mail, args=(msg,))
th.start()
return th

Binary file modified app/main/__pycache__/views.cpython-35.pyc
Binary file not shown.
20 changes: 11 additions & 9 deletions app/main/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
from flask import render_template, redirect, url_for, flash
from ..main import main
from ..forms import signupForm
from app.models import User, db
from .. import db
from ..models import User
from ..mails import send_mail


@main.route('/', methods=['GET', 'POST'])
Expand All @@ -13,18 +15,18 @@ def index():


@main.route('/register', methods=['GET', 'POST'])
def user_register():
def register():
form = signupForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.username.data).first()
if user:
flash('Username already taken!')
if user.email == form.email.data:
flash('Email Add already registered')
return render_template('register.html', form=form)
if user and user.email == form.email.data:
flash('Username and email already taken!')
return redirect(url_for('auth.sign_in'))
else:
user = User(username=form.username.data, email=form.email.data, password=form.password.data)
user = User(username=form.username.data, email=form.email.data, password=form.confirm.data)
db.session.add(user)
db.session.commit()
return redirect(url_for('auth.sign_in'))
send_mail('New User Just Joined', '[email protected]', 'mail/new_user', user=user.username)
flash('congrats! You\'re successfully registered')
return render_template('register.html', form=form)

2 changes: 1 addition & 1 deletion app/models.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# encoding:utf-8
# create db models here

from . import db,login_manager
from . import db, login_manager
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import UserMixin

Expand Down
2 changes: 1 addition & 1 deletion app/templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
<a class="nav-link" href="{{ url_for('main.index') }}">HOME</a>
</li>
<li class="nav-item">
<a class="nav-link" href="{{ url_for('main.user_register') }}">REGISTER</a>
<a class="nav-link" href="{{ url_for('main.register') }}">REGISTER</a>
</li>
{% if current_user.is_authenticated %}
<li class="nav-item">
Expand Down
33 changes: 32 additions & 1 deletion app/templates/macro/wtf.html
Original file line number Diff line number Diff line change
@@ -1,17 +1,48 @@
{% macro signupForm(form) %}
<form action="{{ url_for('main.user_register') }}", method="POST">
<form action="{{ url_for('main.register') }}", method="POST">
{{ form.hidden_tag() }}
{% if form.email.errors %}
{% for err in form.email.errors %}
<span class="bg-warning h3">{{ err }}</span>
{% endfor %}
{% endif %}
{{ form.email(class='form-control', placeholder='Email Address') }}
{% if form.username.errors %}
{% for err in form.username.errors %}
<span class="bg-warning h3">{{ err }}</span>
{% endfor %}
{% endif %}
{{ form.username(class='form-control', placeholder='Username') }}
{% if form.password.errors %}
{% for err in form.password.errors %}
<span class="bg-warning h3">{{ err }}</span>
{% endfor %}
{% endif %}
{{ form.password(class='form-control', placeholder='Password') }}
{% if form.confirm.errors %}
{% for err in form.confirm.errors %}
<span class="bg-warning h3">{{ err }}</span>
{% endfor %}
{% endif %}
{{ form.confirm(class='form-control', placeholder='Password') }}
{{ form.submit(class='btn btn-primary btn-block') }}
</form>
{% endmacro %}

{% macro loginForm(form) %}
<form action="{{ url_for('auth.sign_in') }}", method='POST'>
{{ form.hidden_tag() }}
{% if form.email.errors %}
{% for err in form.email.errors %}
<span class="bg-warning h3">{{ err }}</span>
{% endfor %}
{% endif %}
{{ form.email(class='form-control', placeholder='Your registered email') }}
{% if form.password.errors %}
{% for err in form.password.errors %}
<span class="bg-warning h3">{{ err }}</span>
{% endfor %}
{% endif %}
{{ form.password(class='form-control', placeholder='Password') }}
{{ form.submit(class='btn btn-primary btn-block') }}
</form>
Expand Down
10 changes: 10 additions & 0 deletions app/templates/mail/new_user.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>new user template</title>
</head>
<body>
<h1>New user {{ user }} just joined</h1>
</body>
</html>
3 changes: 3 additions & 0 deletions app/templates/register.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
{% import 'macro/wtf.html' as wtf %}
{% block main %}
<div class="signup-form">
{% for msg in get_flashed_messages() %}
<span class="display-4 bg-danger">{{ msg }}</span>
{% endfor %}
<div class="container">
{{ wtf.signupForm(form) }}
</div>
Expand Down
6 changes: 3 additions & 3 deletions config.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,12 @@ class config:
SECRET_KEY = os.environ.get('SECRET_KEY') or os.urandom(16)
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
SQLALCHEMY_TRACK_MODIFICATIONS = False
MAIL_DEFAULT_SENDER = os.environ.get('MAILD_DEFAULT_SENDER')
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
MAIL_SERVER = os.environ.get('MAIL_SERVER')
MAIL_PORT = os.environ.get('MAIL_PORT')
MAIL_USE_SSL = True
MAIL_DEFAULT_SENDER = os.environ.get('MAIL_DEFAULT_SENDER')
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')

@staticmethod
def init_app(app):
Expand Down
Binary file modified dev.db
Binary file not shown.
1 change: 1 addition & 0 deletions migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
Binary file added migrations/__pycache__/env.cpython-35.pyc
Binary file not shown.
45 changes: 45 additions & 0 deletions migrations/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# A generic, single database configuration.

[alembic]
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false


# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
90 changes: 90 additions & 0 deletions migrations/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
from __future__ import with_statement
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
import logging

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from flask import current_app
config.set_main_option('sqlalchemy.url',
current_app.config.get('SQLALCHEMY_DATABASE_URI'))
target_metadata = current_app.extensions['migrate'].db.metadata

# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.


def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(url=url)

with context.begin_transaction():
context.run_migrations()


def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""

# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
def process_revision_directives(context, revision, directives):
if getattr(config.cmd_opts, 'autogenerate', False):
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
logger.info('No changes in schema detected.')

engine = engine_from_config(config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool)

connection = engine.connect()
context.configure(connection=connection,
target_metadata=target_metadata,
process_revision_directives=process_revision_directives,
**current_app.extensions['migrate'].configure_args)

try:
with context.begin_transaction():
context.run_migrations()
except Exception as exception:
logger.error(exception)
raise exception
finally:
connection.close()

if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
24 changes: 24 additions & 0 deletions migrations/script.py.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}

"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}

# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}


def upgrade():
${upgrades if upgrades else "pass"}


def downgrade():
${downgrades if downgrades else "pass"}
Loading

0 comments on commit 3de146f

Please sign in to comment.