Skip to content

Commit

Permalink
switch to a better structure
Browse files Browse the repository at this point in the history
  • Loading branch information
lesliebinbin committed Aug 22, 2018
1 parent 19af778 commit aac6423
Show file tree
Hide file tree
Showing 46 changed files with 670 additions and 73 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
My flasky project
just for fun
Binary file removed __pycache__/app.cpython-36.pyc
Binary file not shown.
Binary file added __pycache__/config.cpython-36.pyc
Binary file not shown.
Binary file added __pycache__/flasky.cpython-36.pyc
Binary file not shown.
37 changes: 0 additions & 37 deletions app.py

This file was deleted.

24 changes: 24 additions & 0 deletions app/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from flask import Flask, render_template
from flask_bootstrap import Bootstrap
from flask_mail import Mail
from flask_moment import Moment
from flask_sqlalchemy import SQLAlchemy
from config import config

bootstrap = Bootstrap()
mail = Mail()
moment = Moment()
db = SQLAlchemy()


def create_app(config_name):
app = Flask(__name__)
app.config.from_object(config[config_name])
config[config_name].init_app(app)
bootstrap.init_app(app)
mail.init_app(app)
moment.init_app(app)
db.init_app(app)
from .main import main as main_blueprint
app.register_blueprint(main_blueprint)
return app
Binary file added app/__pycache__/__init__.cpython-36.pyc
Binary file not shown.
Binary file added app/__pycache__/email.cpython-36.pyc
Binary file not shown.
Binary file added app/__pycache__/models.cpython-36.pyc
Binary file not shown.
Binary file added app/__pycache__/something_fuck.cpython-36.pyc
Binary file not shown.
Empty file added app/email.py
Empty file.
3 changes: 3 additions & 0 deletions app/main/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from flask import Blueprint
main = Blueprint('main', __name__)
from . import views, forms
Binary file added app/main/__pycache__/__init__.cpython-36.pyc
Binary file not shown.
Binary file added app/main/__pycache__/forms.cpython-36.pyc
Binary file not shown.
Binary file added app/main/__pycache__/views.cpython-36.pyc
Binary file not shown.
10 changes: 10 additions & 0 deletions app/main/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from flask import render_template
from . import main

@main.app_errorhandler(404)
def page_not_found(e):
render_template('404.html'), 404

@main.app_errorhandler(500)
def internal_server_error(500):
return render_template('500.html'), 500
8 changes: 8 additions & 0 deletions app/main/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired


class NameForm(FlaskForm):
name = StringField('What is your name?', validators=[DataRequired()])
submit = SubmitField('submit')
49 changes: 49 additions & 0 deletions app/main/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from datetime import datetime
from flask import render_template, session, redirect, url_for
from . import main
from .forms import NameForm
from .. import db, mail
from ..models import User
from flask_mail import Message
from threading import Thread


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


def send_mail(to, subject, template, **kwargs):
msg = Message(
main.config['MAIL_SUBJECT_PREFIX'] + subject,
sender=main.config['FLASKY_MAIL_SENDER'],
recipients=to)
msg.body = render_template(template + '.txt', **kwargs)
msg.html = render_template(template + '.html', **kwargs)
thr = Thread(target=send_async_email, args=[main, msg])
thr.start()
return thr


@main.route("/", methods=['GET', 'POST'])
def index():
name = None
form = NameForm()
if form.validate_on_submit():
user = User.query.filter_by(username=form.name.data).first()
if not user:
user = User(username=form.name.data)
db.session.add(user)
db.session.commit()
session['known'] = False
else:
session['known'] = True
session['name'] = form.name.data
form.name.data = ''
return redirect(url_for('.index'))
return render_template(
"index.html",
current_time=datetime.utcnow(),
form=form,
name=session.get('name'),
known=session.get('known', False))
19 changes: 19 additions & 0 deletions app/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from . import db
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 f"<Role {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 f"<User {self.username}>"
File renamed without changes.
File renamed without changes.
File renamed without changes.
48 changes: 48 additions & 0 deletions app/templates/base.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
{% extends "bootstrap/base.html" %}

{% block title %}Flasky{% endblock %}

{% block head %}
{{ super() }}
<link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
<link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
{% endblock %}

{% block navbar %}
<div class="navbar navbar-inverse" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Flasky</a>
</div>
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="/">Home</a></li>
</ul>
</div>
</div>
</div>
{% endblock %}

{% block content %}
<div class="container">
{% for message in get_flashed_messages() %}
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert">&times;</button>
{{ message }}
</div>
{% endfor %}

{% block page_content %}{% endblock %}
</div>
{% endblock %}

{% block scripts %}
{{ super() }}
{{ moment.include_moment() }}
{% endblock %}
29 changes: 29 additions & 0 deletions app/templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf%}
{% block title %}
Flasky
{% endblock title %}
{% block content %}
{{super()}}
<div class="page-header">
<h1>
Hello, {%if name%} {{name}} {%else%} Stranger {%endif%}!
</h1>
{%if not known%}
<p>Please to meet you!</p>
{%else%}
<p>Happy to see you again!</p>
{%endif%}
</div>
{{wtf.quick_form(form)}}
<p>
The local date and time is {{moment(current_time).format('LLL')}}
</p>
<p>
That was {{moment(current_time).fromNow(refresh=True)}}
</p>
{% endblock content %}
{% block scripts %}
{{super()}}
{{moment.locale('es')}}
{% endblock scripts %}
File renamed without changes.
4 changes: 4 additions & 0 deletions app/templates/mail/new_user.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<h1>
<p>New user Add.</p>
{{user}}
</h1>
1 change: 1 addition & 0 deletions app/templates/mail/new_user.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
There is a new user been added: {{user}}
File renamed without changes.
44 changes: 44 additions & 0 deletions config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import os

basedir = os.path.abspath(os.path.dirname(__file__))


class Config:
SECRET_KEY = os.environ.get('SECRET_KEY', 'hard to guess string')
MAIL_SERVER = os.environ.get('MAIL_SERVER', 'stmp.googlemail.com')
MAIL_PORT = int(os.environ.get('MAIL_PORT', '587'))
MAIL_USE_TLS = os.environ.get('MAIL_USE_TLS',
'true').lower() in ['true', 'on', '1']
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
FLASKY_MAIL_SUBJECT_PREFIX = '[Flasky]'
FLASKY_MAIL_SENDER = 'Flasky Admin <[email protected]>'
FLASKY_ADMIN = os.environ.get('FLASKY_ADMIN')
SQLALCHEMY_TRACK_MODIFICATIONS = False

@staticmethod
def init_app(app):
pass


class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(
basedir, 'data-dev.sqlite')


class ProductionConfig(Config):
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://root:woainvren1@localhost/python"


class TestingConfig(Config):
TESTING = True
SQLALCHEMY_DATABASE_URI = 'sqlite://'


config = {
'development': DevelopmentConfig,
'testing': TestingConfig,
'production': ProductionConfig,
'default': DevelopmentConfig,
}
Binary file added data-dev.sqlite
Binary file not shown.
34 changes: 34 additions & 0 deletions flasky.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#!/usr/bin/env python3
# coding:utf-8
import os

from flask_migrate import Migrate

from app import create_app, db
from app.models import Role, User

app = create_app(os.environ.get('FLASK_CONFIG', 'default'))
migrate = Migrate(app, db)


@app.shell_context_processor
def make_shell_context():
return dict(db=db, User=User, Role=Role)


@app.cli.command()
def test():
"""
Run the unit tests.
"""
import unittest
tests = unittest.TestLoader().discover('tests')
unittest.TextTestRunner(verbosity=2).run(tests)


def main():
app.run(host='0.0.0.0', port=8080, debug=True)


if __name__ == "__main__":
main()
9 changes: 9 additions & 0 deletions gmail_demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/usr/bin/env python3
# coding:utf-8
from flask_mail import Message
from app import mail, app
msg = Message('test mail', sender='[email protected]', recipients=['[email protected]'])
msg.body = 'This is the plain text body'
msg.html = 'This is the <b>HTML</b> body'
with app.app_context():
mail.send(msg)
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-36.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
Loading

0 comments on commit aac6423

Please sign in to comment.