Commits

Empanado committed 8cf7f3a

Added mongoalchemy example

  • Participants
  • Parent commits 20e7b1e

Comments (0)

Files changed (2)

File examples/mongoalchemy_model.py

+import datetime
+from flask import Flask, request, redirect, url_for
+from flaskext.mongoalchemy import MongoAlchemy
+from flaskext.auth import Auth, AuthUser, login_required, logout
+
+app = Flask(__name__)
+app.config['MONGOALCHEMY_DATABASE'] = 'library'
+db = MongoAlchemy(app)
+auth = Auth(app, login_url_name='index')
+
+def now():
+    return datetime.datetime.utcnow()
+
+class User(db.Document, AuthUser):
+    """
+    Implementation of User for SQLAlchemy.
+    """
+    username = db.StringField()
+    password = db.StringField()
+    salt = db.StringField()
+    role = db.StringField(required=False)
+    created = db.DateTimeField(default=now())
+    modified = db.DateTimeField(default=now())
+
+    def save(self):
+        self.modified = now()
+        super(User, self).save()
+
+@login_required()
+def admin():
+    return 'Admin! Excellent!'
+
+def index():
+    if request.method == 'POST':
+        username = request.form['username']
+        user = User.query.filter(User.username==username).first()
+        if user is not None:
+            # Authenticate and log in!
+            if user.authenticate(request.form['password']):
+                return redirect(url_for('admin'))
+        return 'Failure :('
+    return '''
+            <form method="POST">
+                Username: <input type="text" name="username"/><br/>
+                Password: <input type="password" name="password"/><br/>
+                <input type="submit" value="Log in"/>
+            </form>
+        '''
+
+def user_create():
+    if request.method == 'POST':
+        username = request.form['username']
+        if User.query.filter(User.username==username).first():
+            return 'User already exists.'
+        password = request.form['password']
+        user = User(username=username)
+        user.set_and_encrypt_password(password)
+        user.save()
+        return redirect(url_for('index'))
+    return '''
+            <form method="POST">
+                Username: <input type="text" name="username"/><br/>
+                Password: <input type="password" name="password"/><br/>
+                <input type="submit" value="Create"/>
+            </form>
+        '''
+
+def logout_view():
+    user = logout()
+    if user is None:
+        return 'No user to log out.'
+    return 'Logged out user {0}.'.format(user.username)
+
+# URLs
+app.add_url_rule('/', 'index', index, methods=['GET', 'POST'])
+app.add_url_rule('/admin/', 'admin', admin)
+app.add_url_rule('/users/create/', 'user_create', user_create, methods=['GET', 'POST'])
+app.add_url_rule('/logout/', 'logout', logout_view)
+
+# Secret key needed to use sessions.
+app.secret_key = 'N4BUdSXUzHxNoO8g'
+
+if __name__ == '__main__':
+    app.run(debug=True)

File examples/sqlalchemy_model.py

 auth = Auth(app, login_url_name='index')
 
 def now():
-    return datetime.datetime.now()
+    return datetime.datetime.utcnow()
 
 class User(db.Model, AuthUser):
     """