Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adapt flaskr example to sqlalchemy #720

Merged
merged 2 commits into from Apr 23, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions examples/flaskr/.gitignore
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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.")
121 changes: 121 additions & 0 deletions examples/flaskr/flaskr/auth.py
@@ -0,0 +1,121 @@
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 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):
davidism marked this conversation as resolved.
Show resolved Hide resolved
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)


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"))