SHARE
TWEET

views.py

a guest Jan 15th, 2014 527 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from flask import render_template, flash, redirect, session, url_for, request, g
  2. from flask.ext.login import login_user, logout_user, current_user, login_required
  3. from app import app, db, lm, oid
  4. from forms import LoginForm
  5. from models import User, ROLE_USER, ROLE_ADMIN
  6.  
  7. @lm.user_loader
  8. def load_user(id):
  9.     return User.query.get(int(id))
  10.  
  11. @app.before_request
  12. def before_request():
  13.     g.user = current_user
  14.    
  15. @app.route('/')
  16. @app.route('/index')
  17. @login_required
  18. def index():
  19.     user = g.user
  20.     posts = [
  21.         {
  22.             'author': { 'nickname': 'John' },
  23.             'body': 'Beautiful day in Portland!'
  24.         },
  25.         {
  26.             'author': { 'nickname': 'Susan' },
  27.             'body': 'The Avengers movie was so cool!'
  28.         }
  29.     ]
  30.     return render_template('index.html',
  31.         title = 'Home',
  32.         user = user,
  33.         posts = posts)
  34.  
  35. @app.route('/login', methods = ['GET', 'POST'])
  36. @oid.loginhandler
  37. def login():
  38.     if g.user is not None and g.user.is_authenticated():
  39.         return redirect(url_for('index'))
  40.     form = LoginForm()
  41.     if form.validate_on_submit():
  42.         session['remember_me'] = form.remember_me.data
  43.         return oid.try_login(form.openid.data, ask_for = ['nickname', 'email'])
  44.     return render_template('login.html',
  45.         title = 'Sign In',
  46.         form = form,
  47.         providers = app.config['OPENID_PROVIDERS'])
  48.  
  49. @oid.after_login
  50. def after_login(resp):
  51.     if resp.email is None or resp.email == "":
  52.         flash('Invalid login. Please try again.')
  53.         return redirect(url_for('login'))
  54.     user = User.query.filter_by(email = resp.email).first()
  55.     if user is None:
  56.         nickname = resp.nickname
  57.         if nickname is None or nickname == "":
  58.             nickname = resp.email.split('@')[0]
  59.         user = User(nickname = nickname, email = resp.email, role = ROLE_USER)
  60.         db.session.add(user)
  61.         db.session.commit()
  62.     remember_me = False
  63.     if 'remember_me' in session:
  64.         remember_me = session['remember_me']
  65.         session.pop('remember_me', None)
  66.     login_user(user, remember = remember_me)
  67.     return redirect(request.args.get('next') or url_for('index'))
  68.  
  69. @app.route('/logout')
  70. def logout():
  71.     logout_user()
  72.     return redirect(url_for('index'))
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top