← flask-blog

fixed

48bb466e11ec32eede65af35206ec3390a46db0a · ovidiucs · May 20, 2015 20:10

+71 −82 · 11 files changed

  • app/__init__.py +1 −1
  • app/main/forms.py +10 −0
  • app/main/routes.py +8 −36
  • app/models.py +2 −18
  • app/templates/base.html +22 −2
  • app/templates/index.html +10 −22
  • app/templates/protected.html +1 −1
  • config/config.py +1 −1
  • config/development.py +7 −0
  • config/testing.py +8 −0
  • run.py +1 −1
diff --git a/app/__init__.py b/app/__init__.py
index 3f9ec31..647a6c4 100644
--- a/app/__init__.py
+++ b/app/__init__.py
@@ -1,6 +1,6 @@
 import os
 from flask import Flask
-from flask.ext.bootsrap import Bootstrap
+from flask.ext.bootstrap import Bootstrap
 from flask.ext.sqlalchemy import SQLAlchemy
 from flask.ext.login import LoginManager
 
diff --git a/app/main/forms.py b/app/main/forms.py
new file mode 100644
index 0000000..efaa941
--- /dev/null
+++ b/app/main/forms.py
@@ -0,0 +1,10 @@
+from flask.ext.wtf import Form
+from wtforms import StringField, PasswordField, BooleanField, SubmitField
+from wtforms.validators import Required, Length
+
+
+class LoginForm(Form):
+    username = StringField('Username', validators=[Required(), Length(1, 16)])
+    password = PasswordField('Password', validators=[Required()])
+    remember_me = BooleanField('Remember me')
+    submit = SubmitField('Submit')
diff --git a/app/main/routes.py b/app/main/routes.py
index 86d8683..1b15569 100644
--- a/app/main/routes.py
+++ b/app/main/routes.py
@@ -1,43 +1,15 @@
-from flask import render_template, request, url_for, redirect
+from flask import render_template, redirect, url_for, request
 from flask.ext.login import login_required, login_user, logout_user
 from ..models import User
 from . import main
 from .forms import LoginForm
 
-"""
-POST request > wtf run all the validators and if
-they validate they get in the if body
-ser.query.filter_by(username=form.username.data)
---if user is None
-1 or None (user is valid, user invalid return None
-Never get more than one. Username is unique
-
---user.verify_password(form.password.data):
-    we need to let the user try again, redirect to login page
-    a redirect to itself
---login_user(user, form.remember_me.data)
-    function that comes with flask.login,
-    login the user pass the user object and tell it if
-    we want it that it should be a user to be remembered
---return redirect(request.args.get('next') or url_for('index'))
-    redirect to home page or protected page while being logged out
-    intercepted and sent to the login
---request.args
-    python dictionary will have all the elements
-    next is used in arguments if user tried to access restricted page
-    if user will login ok then it will use the next parameter, which in
-    turn it will go to protected page
---args.get('next'
-    none > redirect to index page or protected page
---
-"""
-
 
 @main.route('/login', methods=['GET', 'POST'])
 def login():
     form = LoginForm()
     if form.validate_on_submit():
-        user = User.query.filter_by(username=form.username.data).first
+        user = User.query.filter_by(username=form.username.data).first()
         if user is None or not user.verify_password(form.password.data):
             return redirect(url_for('main.login', **request.args))
         login_user(user, form.remember_me.data)
@@ -52,12 +24,12 @@ def logout():
     return redirect(url_for('main.index'))
 
 
+@main.route('/')
+def index():
+    return render_template('index.html')
+
+
 @main.route('/protected')
 @login_required
 def protected():
-    return render_template('protected.html')
-
-
-@app.route('/')
-def hello_world():
-    return render_template('index.html')
+    return render_template('protected.html')
\ No newline at end of file
diff --git a/app/models.py b/app/models.py
index e1f59e2..6e10c44 100644
--- a/app/models.py
+++ b/app/models.py
@@ -1,26 +1,11 @@
-from flask.ext.login import UserMixin
 from werkzeug.security import generate_password_hash, check_password_hash
 from . import db, lm
+from flask.ext.login import UserMixin
 
 
-
-
-# Define a class that represents our users in the database
-# This class inherits from  a base model classes
-# Models > Classes > Associated with entities within a database.
-# The hardest part was finding the right SQLAlchemy data types and picking a
-# length for our String fields in the database. Using our models is also extremely
-# simple, thanks to the SQLAlchemy query syntax
-
 class User(UserMixin, db.Model):
-    """
-    Inherit from a user mixin class.
-    Methods > or implement your own methods
-    """
     __tablename__ = 'users'
     id = db.Column(db.Integer, primary_key=True)
-    name = db.Column(db.String(16), index=True, unique=True)
-
     username = db.Column(db.String(16), index=True, unique=True)
     password_hash = db.Column(db.String(64))
 
@@ -36,7 +21,6 @@ class User(UserMixin, db.Model):
         user.set_password(password)
         db.session.add(user)
         db.session.commit()
-        return user
 
     def __repr__(self):
         return '<User {0}>'.format(self.username)
@@ -44,4 +28,4 @@ class User(UserMixin, db.Model):
 
 @lm.user_loader
 def load_user(id):
-    return User.query.get(int(id))
+    return User.query.get(int(id))
\ No newline at end of file
diff --git a/app/templates/base.html b/app/templates/base.html
index af4b320..d2fabaa 100644
--- a/app/templates/base.html
+++ b/app/templates/base.html
@@ -1,9 +1,29 @@
-{% extends 'bootstrap/base.html' %}
+{% extends "bootstrap/base.html" %}
+{% import "bootstrap/wtf.html" as wtf %}
+
+{% block title %}Login Example{% endblock %}
 
 {% block navbar %}
     <nav class="navbar navbar-inverse" role="navigation">
         <div class="container">
-            <a class="navbar-brand" href="{{ url_for("index") }}">Weather</a>
+            <a class="navbar-brand" href="{{ url_for('main.index') }}">
+                Login Example
+            </a>
+            <ul class="nav navbar-nav">
+                <li><a href="{{ url_for('main.index') }}">Home</a></li>
+                <li><a href="{{ url_for('main.protected') }}">Protected</a>
+                </li>
+            </ul>
+            >
+            <ul class="nav navbar-nav navbar-right">
+                <li>
+                    {% if current_user.is_authenticated() %}
+                        <a href="{{ url_for('main.logout') }}">Logout</a>
+                    {% else %}
+                        <a href="{{ url_for('main.login') }}">Login</a>
+                    {% endif %}
+                </li>
+            </ul>
         </div>
     </nav>
 {% endblock %}
diff --git a/app/templates/index.html b/app/templates/index.html
index 0d9a761..48f7318 100644
--- a/app/templates/index.html
+++ b/app/templates/index.html
@@ -1,22 +1,10 @@
-<h1>This page containes HTML</h1>
-<p>
-    Cookie:
-    {% if 'cookie' in request.cookies %}
-        <b>{{ request.cookies['cookie'] }}</b>
-    {% else %}
-        not set
-    {% endif %}
-</p>
-<p><a href="{{ url_for('text') }}">Click here</a> to view a page that
-    contains plain text</p>
-<p><a href="{{ url_for('xml') }}">Click here</a> to view a page that
-    contains XML data</p>
-<p><a href="{{ url_for('json') }}">Click here</a> to view a page that
-    contains JSON data </p>
-<p><a href="{{ url_for('redir') }}">Click here</a> to view a page that
-    redirect to the plain text page</p>
-<p><a href="{{ url_for('cookie') }}">Click here</a> to view a page that sets
-    a cookie and then redirect back to this page
-</p>
-<p><a href="{{ url_for('response') }}">Click here</a> to view a page
-    that shows plain text through a response object.</p>
\ No newline at end of file
+{% extends "base.html" %}
+
+{% block title %}Login Example{% endblock %}
+
+{% block page_content %}
+	<h1>Home page</h1>
+	<p>This page can be viewed by all users.</p>
+	<p>You are {% if not current_user.is_authenticated() %}not {% endif %}
+		logged in.</p>
+{% endblock %}
\ No newline at end of file
diff --git a/app/templates/protected.html b/app/templates/protected.html
index 76a5f95..0f4f49d 100644
--- a/app/templates/protected.html
+++ b/app/templates/protected.html
@@ -3,6 +3,6 @@
 
 {% block page_content %}
     <h1>Protected page</h1>
-    <p>This page can only be viewerd by logged in users</p>
+    <p>This page can only be viewed by logged in users</p>
     <p>You are logged in as <b>{{ current_user.username }}</b></p>
 {% endblock %}
\ No newline at end of file
diff --git a/config/config.py b/config/config.py
index 358246a..99b66d7 100644
--- a/config/config.py
+++ b/config/config.py
@@ -3,5 +3,5 @@ import os
 
 DEBUG = True
 SECRET_KEY = 'top secret'
-SQLALHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(
+SQLALCHEMY_DATABASE_URI = 'sqllite:///' + os.path.join(
     os.path.dirname(__file__), '../data-dev.sqlite3')
diff --git a/config/development.py b/config/development.py
new file mode 100644
index 0000000..cd9b5e3
--- /dev/null
+++ b/config/development.py
@@ -0,0 +1,7 @@
+import os
+
+DEBUG = False
+TESTING = True
+SECRET_KEY = 'top secret'
+SQLALHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(
+    os.path.dirname(__file__), '../data-dev.sqlite3')
diff --git a/config/testing.py b/config/testing.py
new file mode 100644
index 0000000..3874a53
--- /dev/null
+++ b/config/testing.py
@@ -0,0 +1,8 @@
+import os
+
+DEBUG = False
+TESTING = True
+SECRET_KEY = 'top secret'
+WTF_CSRF_ENABLED = False
+SQLALHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(
+    os.path.dirname(__file__), '../data-test.sqlite3')
diff --git a/run.py b/run.py
index c7a903a..11f2e9c 100644
--- a/run.py
+++ b/run.py
@@ -8,4 +8,4 @@ if __name__ == '__main__':
         db.create_all()
         if User.query.filter_by(username='john').first() is None:
             User.register('john', 'cat')
-    app.run()
+    app.run()
\ No newline at end of file