Skip to content

Commit

Permalink
Merge pull request pallets-eco#720 from pallets/flaskr
Browse files Browse the repository at this point in the history
adapt flaskr example to sqlalchemy
  • Loading branch information
davidism committed Apr 23, 2019
2 parents da6c7cc + 391c3b8 commit 0045123
Show file tree
Hide file tree
Showing 29 changed files with 982 additions and 0 deletions.
10 changes: 10 additions & 0 deletions examples/flaskr/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
venv/
*.pyc
instance/
.pytest_cache/
.coverage
htmlcov/
dist/
build/
*.egg-info/
.idea/
28 changes: 28 additions & 0 deletions examples/flaskr/LICENSE.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
Copyright 2010 Pallets

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
4 changes: 4 additions & 0 deletions examples/flaskr/MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
graft flaskr/static
graft flaskr/templates
graft tests
global-exclude *.pyc
90 changes: 90 additions & 0 deletions examples/flaskr/README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
Flaskr
======

The basic blog app built in the Flask `tutorial`_, modified to use
Flask-SQLAlchemy instead of plain SQL.

.. _tutorial: http://flask.pocoo.org/docs/tutorial/


Install
-------

**Be sure to use the same version of the code as the version of the docs
you're reading.** You probably want the latest tagged version, but the
default Git version is the master branch.

.. code-block:: text
# clone the repository
$ git clone https://github.com/pallets/flask-sqlalchemy
$ cd flask-sqlalchemy/examples/flaskr
# checkout the correct version
$ git checkout correct-version-tag
Create a virtualenv and activate it:

.. code-block:: text
$ python3 -m venv venv
$ . venv/bin/activate
Or on Windows cmd:

.. code-block:: text
$ py -3 -m venv venv
$ venv\Scripts\activate.bat
Install Flaskr:

.. code-block:: text
$ pip install -e .
Or if you are using the master branch, install Flask-SQLAlchemy from
source before installing Flaskr:

.. code-block:: text
$ pip install -e ../..
$ pip install -e .
Run
---

.. code-block:: text
$ export FLASK_APP=flaskr
$ export FLASK_ENV=development
$ flask init-db
$ flask run
Or on Windows cmd:

.. code-block:: text
> set FLASK_APP=flaskr
> set FLASK_ENV=development
> flask init-db
> flask run
Open http://127.0.0.1:5000 in a browser.


Test
----

.. code-block:: text
$ pip install -e '.[test]'
$ pytest
Run with coverage report:

.. code-block:: text
$ coverage run -m pytest
$ coverage report
$ coverage html # open htmlcov/index.html in a browser
66 changes: 66 additions & 0 deletions examples/flaskr/flaskr/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import os

import click
from flask import Flask
from flask.cli import with_appcontext
from flask_sqlalchemy import SQLAlchemy

__version__ = (1, 0, 0, "dev")

db = SQLAlchemy()


def create_app(test_config=None):
"""Create and configure an instance of the Flask application."""
app = Flask(__name__, instance_relative_config=True)

# some deploy systems set the database url in the environ
db_url = os.environ.get("DATABASE_URL")

if db_url is None:
# default to a sqlite database in the instance folder
db_url = "sqlite:///" + os.path.join(app.instance_path, "flaskr.sqlite")
# ensure the instance folder exists
os.makedirs(app.instance_path, exist_ok=True)

app.config.from_mapping(
# default secret that should be overridden in environ or config
SECRET_KEY=os.environ.get("SECRET_KEY", "dev"),
SQLALCHEMY_DATABASE_URI=db_url,
SQLALCHEMY_TRACK_MODIFICATIONS=False,
)

if test_config is None:
# load the instance config, if it exists, when not testing
app.config.from_pyfile("config.py", silent=True)
else:
# load the test config if passed in
app.config.update(test_config)

# initialize Flask-SQLAlchemy and the init-db command
db.init_app(app)
app.cli.add_command(init_db_command)

# apply the blueprints to the app
from flaskr import auth, blog

app.register_blueprint(auth.bp)
app.register_blueprint(blog.bp)

# make "index" point at "/", which is handled by "blog.index"
app.add_url_rule("/", endpoint="index")

return app


def init_db():
db.drop_all()
db.create_all()


@click.command("init-db")
@with_appcontext
def init_db_command():
"""Clear existing data and create new tables."""
init_db()
click.echo("Initialized the database.")
1 change: 1 addition & 0 deletions examples/flaskr/flaskr/auth/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .views import bp
23 changes: 23 additions & 0 deletions examples/flaskr/flaskr/auth/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from sqlalchemy.ext.hybrid import hybrid_property
from werkzeug.security import check_password_hash
from werkzeug.security import generate_password_hash

from flaskr import db


class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String, unique=True, nullable=False)
_password = db.Column("password", db.String, nullable=False)

@hybrid_property
def password(self):
return self._password

@password.setter
def password(self, value):
"""Store the password as a hash for security."""
self._password = generate_password_hash(value)

def check_password(self, value):
return check_password_hash(self.password, value)
100 changes: 100 additions & 0 deletions examples/flaskr/flaskr/auth/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import functools

from flask import Blueprint
from flask import flash
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from flaskr import db
from flaskr.auth.models import User

bp = Blueprint("auth", __name__, url_prefix="/auth")


def login_required(view):
"""View decorator that redirects anonymous users to the login page."""

@functools.wraps(view)
def wrapped_view(**kwargs):
if g.user is None:
return redirect(url_for("auth.login"))

return view(**kwargs)

return wrapped_view


@bp.before_app_request
def load_logged_in_user():
"""If a user id is stored in the session, load the user object from
the database into ``g.user``."""
user_id = session.get("user_id")
g.user = User.query.get(user_id) if user_id is not None else None


@bp.route("/register", methods=("GET", "POST"))
def register():
"""Register a new user.
Validates that the username is not already taken. Hashes the
password for security.
"""
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
error = None

if not username:
error = "Username is required."
elif not password:
error = "Password is required."
elif db.session.query(
User.query.filter_by(username=username).exists()
).scalar():
error = f"User {username} is already registered."

if error is None:
# the name is available, create the user and go to the login page
db.session.add(User(username=username, password=password))
db.session.commit()
return redirect(url_for("auth.login"))

flash(error)

return render_template("auth/register.html")


@bp.route("/login", methods=("GET", "POST"))
def login():
"""Log in a registered user by adding the user id to the session."""
if request.method == "POST":
username = request.form["username"]
password = request.form["password"]
error = None
user = User.query.filter_by(username=username).first()

if user is None:
error = "Incorrect username."
elif not user.check_password(password):
error = "Incorrect password."

if error is None:
# store the user id in a new session and return to the index
session.clear()
session["user_id"] = user.id
return redirect(url_for("index"))

flash(error)

return render_template("auth/login.html")


@bp.route("/logout")
def logout():
"""Clear the current session, including the stored user id."""
session.clear()
return redirect(url_for("index"))
1 change: 1 addition & 0 deletions examples/flaskr/flaskr/blog/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .views import bp
26 changes: 26 additions & 0 deletions examples/flaskr/flaskr/blog/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from flask import url_for

from flaskr import db
from flaskr.auth.models import User


class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
author_id = db.Column(db.ForeignKey(User.id), nullable=False)
created = db.Column(
db.DateTime, nullable=False, server_default=db.func.current_timestamp()
)
title = db.Column(db.String, nullable=False)
body = db.Column(db.String, nullable=False)

# User object backed by author_id
# lazy="joined" means the user is returned with the post in one query
author = db.relationship(User, lazy="joined", backref="posts")

@property
def update_url(self):
return url_for("blog.update", id=self.id)

@property
def delete_url(self):
return url_for("blog.delete", id=self.id)
Loading

0 comments on commit 0045123

Please sign in to comment.