from flask import Flask from flask_admin import Admin from flask_admin import BaseView from flask_admin import expose from flask_babelex import Babel from flask_sqlalchemy import SQLAlchemy from flask_admin.contrib.sqla import ModelView
from flask import url_for, redirect, render_template, request from wtforms import form, fields, validators import flask_admin as admin import flask_login as login from flask_admin.contrib import sqla from flask_admin import helpers from werkzeug.security import generate_password_hash, check_password_hash
db = SQLAlchemy() app = Flask(__name__) babel = Babel(app)
app.config['BABEL_DEFAULT_LOCALE'] = 'zh_CN' app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:myweb@localhost:3306/myweb?charset=utf8' app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = '123456790'
db.init_app(app)
class User(db.Model): __tablename__ = 'user' id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(100)) last_name = db.Column(db.String(100)) login = db.Column(db.String(80), unique=True) email = db.Column(db.String(120)) password = db.Column(db.String(64))
@property def is_authenticated(self): return True
@property def is_active(self): return True
@property def is_anonymous(self): return False
def get_id(self): return self.id
def __unicode__(self): return self.username
class LoginForm(form.Form): login = fields.StringField(validators=[validators.required()]) password = fields.PasswordField(validators=[validators.required()])
def validate_login(self, field): user = self.get_user()
if user is None: raise validators.ValidationError('Invalid user')
if user.password != self.password.data: raise validators.ValidationError('Invalid password')
def get_user(self): return db.session.query(User).filter_by(login=self.login.data).first()
class RegistrationForm(form.Form): login = fields.StringField(validators=[validators.required()]) email = fields.StringField() password = fields.PasswordField(validators=[validators.required()])
def validate_login(self, field): if db.session.query(User).filter_by(login=self.login.data).count() > 0: raise validators.ValidationError('Duplicate username')
def init_login(): login_manager = login.LoginManager() login_manager.init_app(app)
@login_manager.user_loader def load_user(user_id): return db.session.query(User).get(user_id)
class MyModelView(sqla.ModelView):
def is_accessible(self): return login.current_user.is_authenticated column_list = ('first_name','last_name','login') column_labels = { 'first_name':u'名', 'last_name':u'姓', 'login':u'用户名' } column_sortable_list = ('login',) can_view_details = True
class MyAdminIndexView(admin.AdminIndexView):
@expose('/') def index(self): if not login.current_user.is_authenticated: return redirect(url_for('.login_view')) return super(MyAdminIndexView, self).index()
@expose('/login/', methods=('GET', 'POST')) def login_view(self): form = LoginForm(request.form) if helpers.validate_form_on_submit(form): user = form.get_user() login.login_user(user)
if login.current_user.is_authenticated: return redirect(url_for('.index')) link = '<p>Don\'t have an account? <a href="' + url_for('.register_view') + '">Click here to register.</a></p>' self._template_args['form'] = form self._template_args['link'] = link return super(MyAdminIndexView, self).index()
@expose('/register/', methods=('GET', 'POST')) def register_view(self): form = RegistrationForm(request.form) if helpers.validate_form_on_submit(form): user = User()
form.populate_obj(user)
db.session.add(user) db.session.commit()
login.login_user(user) return redirect(url_for('.index')) link = '<p>Already have an account? <a href="' + url_for('.login_view') + '">Click here to log in.</a></p>' self._template_args['form'] = form self._template_args['link'] = link return super(MyAdminIndexView, self).index()
@expose('/logout/') def logout_view(self): login.logout_user() return redirect(url_for('.index'))
class Happy(BaseView): @expose('/') def index(self): return self.render('happy.html')
class Birthday(BaseView): @expose('/') def index(self): return self.render('birthday.html')
@app.route('/') def index(): return render_template('index.html')
init_login()
admin = Admin(app, name='PonyTail', index_view=MyAdminIndexView(), base_template='my_master.html', template_mode='bootstrap3') admin.add_view(Happy(name=u'工作之愉')) admin.add_view(Birthday(name=u'年年有今日岁岁有今朝')) admin.add_view(MyModelView(User,db.session,name=u'用户管理'))
if __name__ == "__main__": app.run(debug=True,host='0.0.0.0',port=5000)
|