标签:
from app import app app.run(debug=False)
from app import app,db,lm,models from flask import render_template,flash,redirect,url_for,session,request,g from .forms import LoginForm, EditForm from .models import User from flask.ext.login import login_user,logout_user,current_user,login_required from datetime import datetime @lm.user_loader def load_user(id): return User.query.get(int(id)) @app.before_request def before_request(): g.user = current_user if g.user.is_authenticated: g.user.last_seen=datetime.utcnow() db.session.add(g.user) db.session.commit() @app.route('/') @app.route('/index') @login_required def index (): user=g.user posts=[ {'author':{'nickname':'John'}, 'body':'Beautiful day in Portland!'}, {'author':{'nickname':'Susan'}, 'body':'The Avengers movie was so cool!'} ] return render_template("index.html", title="Home", user=user, posts=posts) @app.route('/login', methods = ['GET', 'POST']) def login(): if g.user is not None and g.user.is_authenticated: return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): if models.User.query.filter_by(nickname=form.openid.data).first(): user = User.query.filter_by(nickname=form.openid.data).first_or_404() login_user(user) return redirect(url_for('index')) else: return render_template('login.html', title = 'Sign In', error='[NO]', form = form) return render_template('login.html', title = 'Sign In', form = form) @app.route('/logout') @login_required def logout(): logout_user() return redirect(url_for('index')) @app.route('/user/<nickname>') @login_required def user(nickname): user=User.query.filter_by(nickname=nickname).first() if user==None: flash('user'+nickname+'not found!') return redirect(url_for('index')) posts=[ {'author':user,'body':'Test post #1 !!!'}, {'author':user,'body':'Test post #2 !!!'} ] return render_template('user.html', user=user, posts=posts ) @app.route('/edit',methods=["POST","GET"]) @login_required def edit(): form=EditForm() if form.validate_on_submit(): g.user.nickname=form.nickname.data g.user.about_me=form.about_me.data db.session.add(g.user) db.session.commit() flash('Your changes have been saved!') return redirect(url_for('user',nickname=g.user.nickname)) else: form.nickname.data=g.user.nickname form.about_me.data=g.user.about_me return render_template('edit.html',form=form) @app.errorhandler(404) def internal_error(error): return render_template('404.html'),404 @app.errorhandler(500) def internal_error(error): db.session.rollback() return render_template('500.html'),500 #errorhandler装饰器,处理错误 #session.rollback( )回滚数据,发现错误就将数据回滚到错误之前的状态
{% extends "base.html" %} {% block content %} <h1>File Not Found</h1> <p><<a href="{{url_for('index')}}">Back</a></p> {% endblock %}
{% extends "base.html" %} {% block content %} <h1>An unexpected error has occurred</h1> <p>The administrator has been notified. Sorry for the inconvenience!</p> <p><a href="{{url_for('index')}}">Back</a></p> {% endblock %}
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy import os from flask.ext.login import LoginManager app=Flask(__name__) app.config.from_object("config") db=SQLAlchemy(app) lm=LoginManager() lm.init_app(app) lm.login_view='login' if not app.debug: import logging from logging.handlers import RotatingFileHandler file_handler = RotatingFileHandler('tmp/microblog.log', 'a', 1 * 1024*1024, 10) file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')) app.logger.setLevel(logging.INFO) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.info('microblog startup') from app import views,models
from app import app,db,lm,models from flask import render_template,flash,redirect,url_for,session,request,g from .forms import LoginForm, EditForm from .models import User from flask.ext.login import login_user,logout_user,current_user,login_required from datetime import datetime @lm.user_loader def load_user(id): return User.query.get(int(id)) @app.before_request def before_request(): g.user = current_user if g.user.is_authenticated: g.user.last_seen=datetime.utcnow() db.session.add(g.user) db.session.commit() @app.route('/') @app.route('/index') @login_required def index (): user=g.user posts=[ {'author':{'nickname':'John'}, 'body':'Beautiful day in Portland!'}, {'author':{'nickname':'Susan'}, 'body':'The Avengers movie was so cool!'} ] return render_template("index.html", title="Home", user=user, posts=posts) @app.route('/login', methods = ['GET', 'POST']) def login(): if g.user is not None and g.user.is_authenticated: return redirect(url_for('index')) form = LoginForm() if form.validate_on_submit(): if models.User.query.filter_by(nickname=form.openid.data).first(): user = User.query.filter_by(nickname=form.openid.data).first_or_404() login_user(user) return redirect(url_for('index')) else: return render_template('login.html', title = 'Sign In', error='[NO]', form = form) return render_template('login.html', title = 'Sign In', form = form) @app.route('/logout') @login_required def logout(): logout_user() return redirect(url_for('index')) @app.route('/user/<nickname>') @login_required def user(nickname): user=User.query.filter_by(nickname=nickname).first() if user==None: flash('user'+nickname+'not found!') return redirect(url_for('index')) posts=[ {'author':user,'body':'Test post #1 !!!'}, {'author':user,'body':'Test post #2 !!!'} ] return render_template('user.html', user=user, posts=posts ) @app.route('/edit',methods=["POST","GET"]) @login_required def edit(): form=EditForm() if form.validate_on_submit(): if g.user.nickname!=form.nickname.data and User.query.filter_by(nickname = form.nickname.data).first() != None: version = 2 while True: new_nickname = form.nickname.data + str(version) if User.query.filter_by(nickname = new_nickname).first() == None: break version += 1 flash('username already exists! Recommendation:'+form.nickname.data+str(version)) return redirect(url_for('edit')) g.user.nickname=form.nickname.data g.user.about_me=form.about_me.data db.session.add(g.user) db.session.commit() flash('Your changes have been saved!') return redirect(url_for('user',nickname=g.user.nickname)) else: form.nickname.data=g.user.nickname form.about_me.data=g.user.about_me return render_template('edit.html',form=form) @app.errorhandler(404) def internal_error(error): return render_template('404.html'),404 @app.errorhandler(500) def internal_error(error): db.session.rollback() return render_template('500.html'),500
import os import unittest from config import basedir from app import app, db from app.models import User def jc_nickname(nick): if User.query.filter_by(nickname = nick).first() != None: version = 2 while True: new_nickname = nick + str(version) if User.query.filter_by(nickname = new_nickname).first() == None: break version += 1 return new_nickname else: return nick class TestCase(unittest.TestCase): def setUp(self): app.config['TESTING'] = True app.config['WTF_CSRF_ENABLED'] = False app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'test.db') self.app = app.test_client() db.create_all() def tearDown(self): db.session.remove() db.drop_all() def test_make_unique_nickname(self): u = User(nickname='john', email='john@example.com') db.session.add(u) db.session.commit() nickname=jc_nickname('john') assert nickname != 'john' u = User(nickname=nickname, email='susan@example.com') db.session.add(u) db.session.commit() nickname2=jc_nickname('john') assert nickname2 != 'john' assert nickname2 != nickname if __name__ == '__main__': unittest.main()
标签:
原文地址:http://blog.csdn.net/u013055678/article/details/51366133