flash('To find books you need set title or author') else: finds = book.find_books_or_authors() return render_template('home.html', form=form, title='What are you looking for', finds=finds) # Initialize flask-login init_login() # Create admin admin = admin.Admin(app, 'Book Search', index_view=MyAdminIndexView(), base_template='admin-base.html') # Add view admin.add_link(MenuLink(name='Back Home', url='/')) admin.add_view(MyModelView(User, db.session, category='Edit')) admin.add_view(MyModelView(Author, db.session, category='Edit')) admin.add_view(MyModelView(Book, db.session, category='Edit')) def build_sample_db(): """ Populate a small db with some example entries. """ import string import random db.drop_all() db.create_all()
""" import flask.ext.admin as admin from werkzeug.security import generate_password_hash from app import app, db from .models import User, Role from .views import CustomAdminIndexView from .views import NotAuthenticatedMenuLink from .views import AuthenticatedMenuLink from .views import UserView from .views import RoleView from .views import BackupLogView from .views import CleanCacheMenuLink admin = admin.Admin(app, name=u'管理后台', index_view=CustomAdminIndexView(name=u'首页')) # 登陆链接 admin.add_link(NotAuthenticatedMenuLink(name=u'登录', endpoint='admin.login_view')) admin.add_link(AuthenticatedMenuLink(name=u'退出', endpoint='admin.logout_view')) # 管理员 admin.add_view(UserView(category=u'系统信息', name=u'用户设置')) admin.add_view(RoleView(category=u'系统信息', name=u'角色设置')) admin.add_view(BackupLogView(category=u'系统信息', name=u'备份记录')) admin.add_link(CleanCacheMenuLink(category=u'系统信息', name=u'更新缓存', endpoint='admin.clear_cache')) @app.before_first_request def init_admin(): super_role = db.session.query(Role).filter_by(name=u'Administrator').first() if not super_role: super_role = Role(name=u'Administrator') db.session.add(super_role)
for m in auto_model.__all__: m = getattr(auto_model, m) c = m.category() n = m.name() desc = m.desc() if c != 'Other': if desc != 'None': admin.add_view(MyModelView(m, db.session, name=n, category=c, desc=desc)) else: admin.add_view(MyModelView(m, db.session, name=n, category=c)) admin.add_view(RoleView(User, db.session, name=u'用户')) admin.add_view(CartView(name=u'购物车')) # Add username link admin.add_link(UsernameMenuLink(url='#')) # Add register link by endpoint admin.add_link(NotAuthenticatedMenuLink(name=u'注册', endpoint='register_view')) # Add login link by endpoint admin.add_link(NotAuthenticatedMenuLink(name=u'登录', endpoint='login_view')) # Add logout link by endpoint admin.add_link(AuthenticatedMenuLink(name=u'登出', endpoint='logout_view')) # Create DB db.create_all()
# -*- encoding:utf-8 -*- # from .admin import admin import flask.ext.admin as admin from flask.ext.security import SQLAlchemyUserDatastore from flask.ext.security.utils import encrypt_password from app import db, security, app from app.admin.views import CustomAdminIndexView, AuthenticatedMenuLink, UserView, RoleView, BackupLogView, \ CleanCacheMenuLink from .models import User, Role admin = admin.Admin(app, name=u'管理后台', index_view=CustomAdminIndexView(name=u'首页')) user_data_store = SQLAlchemyUserDatastore(db, User, Role) security.init_app(app, user_data_store) admin.add_link(AuthenticatedMenuLink(name=u'退出', endpoint='security.logout')) admin.add_view(UserView(category=u'系统信息', name=u'用户设置')) admin.add_view(RoleView(category=u'系统信息', name=u'角色设置')) admin.add_view(BackupLogView(category=u'系统信息', name=u'备份记录')) admin.add_link(CleanCacheMenuLink(category=u'系统信息', name=u'更新缓存', endpoint='admin.clear_cache')) @app.before_first_request def auto_insert_super_user(): """ 自动创建第一个管理员账户 :return: """ db.create_all() manager = user_data_store.find_or_create_role(name=u'Administrator', description=u'Administrator')
def create_app(): app = Flask(__name__, static_url_path='') app.config.from_object('true_config') admin = Admin(app, index_view = CustomAdminIndexView()) db.init_app(app) with app.app_context(): db.create_all() # Import modules from app.mod_invoice.controllers import mod_invoice as invoice_module from app.mod_reporting.controllers import mod_reporting as reporting_module from app.mod_api.api import api_mod as api_module app.register_blueprint(invoice_module) app.register_blueprint(reporting_module) app.register_blueprint(api_module) Bootstrap(app) app.extensions['bootstrap']['cdns']["select2.js"] = WebCDN("//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js") app.extensions['bootstrap']['cdns']["select2.css"] = WebCDN("//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css") app.extensions['bootstrap']['cdns']['cosmo'] = WebCDN("https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.5/cosmo/") app.extensions['bootstrap']['cdns']['simplex'] = WebCDN("https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.5/simplex/") app.extensions['bootstrap']['cdns']['cyborg'] = WebCDN("https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.5/cyborg/") app.extensions['bootstrap']['cdns']['paper'] = WebCDN("https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.5/paper/") app.extensions['bootstrap']['cdns']['sandstone'] = WebCDN("https://cdnjs.cloudflare.com/ajax/libs/bootswatch/3.3.5/sandstone/") admin.add_view(CustomModelView(Contact,db.session)) admin.add_view(CustomModelView(TimeEntry,db.session)) admin.add_view(CustomModelView(Project,db.session)) admin.add_view(CustomModelView(Invoice,db.session)) admin.add_view(CustomModelView(InvoiceLine,db.session)) admin.add_view(CustomModelView(User,db.session)) admin.add_link(MenuLink('TBiller',endpoint='home')) login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' class TabsUser(UserMixin): def __init__(self, user_id): self.id = 1 def get_name(self): return user.name @login_manager.user_loader def load_user(user_id): return User.query.get(user_id) @app.route('/login',methods=['GET','POST']) def login(): form = LoginForm(request.form) if form.validate_on_submit(): user = User.query.filter(User.email == form.email.data).first() if user and check_password_hash(user.password, form.password.data) and user.status == 0: print(user) print('User exists') login_user(user) next = request.args.get('next') flash('Logged in') return redirect(next or url_for('home')) return render_template('auth/login.html', form=form) @app.route('/register', methods=['GET','POST']) def register(): form = RegisterForm(request.form) if form.validate_on_submit(): user = User.query.filter( or_(User.email==form.email.data, User.username==form.username.data) ).first() if user: flash('Username or email taken.') return render_template("register.html", form = form) new_user = User('','','') form.populate_obj(new_user) new_user.username = form.username.data new_user.status = 0 new_user.password = generate_password_hash(new_user.password) db.session.add(new_user) db.session.commit() flash('Success: User Registered') return redirect(url_for('home')) return render_template("auth/register.html", form = form) @app.route('/logout', methods=['GET']) def logout(): logout_user() return redirect('/login') @app.before_request def check_for_maintenance(): if app.config["MAINTENANCE"] == True: return 'Under Maintenance', 503 #return redirect(url_for('maintenance')) @app.route('/new_appointment', methods=['GET','POST']) @login_required def new_contact(): ContactForm = model_form(Contact, Form, field_args = { 'notes' : { 'widget': widgets.TextArea() } }) model = Contact() form = ContactForm(request.form, model) if request.method == 'POST': if form.validate(): form.populate_obj(model) #model.created = datetime.now() db.session.add(model) db.session.commit() return 'success' return render_template('new_contact.html', form=form) @app.route('/tabs_admin', methods=['GET']) @login_required def tabs_admin(): from datetime import datetime return render_template('tabs_admin.html', dtime = datetime.now().time()) @app.route('/tabs_admin_ng', methods=['GET']) @login_required def tabs_admin_ng(): from datetime import datetime return render_template('tabs_admin_ng.html', dtime = datetime.now().time()) @app.route('/', methods=['GET','POST']) @login_required def home(): TimeEntryForm = model_form(TimeEntry, db_session=db.session, field_args = { 'project' : { #'widget': Select2Widget(multiple = False), 'widget': Select2Widget(), } }) time_entry_model = TimeEntry() start_or_stop = 'Start' if request.method == 'POST': time_entry_form = TimeEntryForm(request.form, time_entry_model) time_entry_form.populate_obj(time_entry_model) if TimeEntry.query.filter_by(stop=None).first() == None: time_entry_model.start = datetime.now().replace(second=0, microsecond=0) time_entry_model.project_id = int(request.form['project']) time_entry_model.project = Project.query.filter_by(id=int(request.form['project'])).first() db.session.add(time_entry_model) db.session.commit() else: time_entry_model = TimeEntry.query.filter_by(stop=None).first() #TimeEntry.query.filter_by(project=time_entry_model.project).filter_by(stop=None).first().stop \ #= datetime.now().replace(second=0, microsecond=0) time_entry_model.stop = datetime.now().replace(second = 0 , microsecond = 0) temp_delta = time_entry_model.stop - time_entry_model.start #temp_delta = temp_delta / timedelta(seconds=60) time_entry_model.delta = round(float(float(temp_delta.seconds/60)/60),2) db.session.flush() db.session.commit() time_entry_form = TimeEntryForm(request.form, time_entry_model) #raise ValueError('test') if TimeEntry.query.filter_by(stop=None).first() != None: TimeEntryForm.project = TextField() time_entry_form = TimeEntryForm(request.form, time_entry_model) time_entry_form.project.data = TimeEntry.query.filter_by(stop=None).first().project start_or_stop = 'Stop' monday = datetime.today() while monday.weekday() != 0: monday += timedelta(days=-1) monday = monday.replace(hour=0, minute=0, second=0, microsecond=0) sunday = monday + timedelta(days = 6) #raise ValueError(monday.strftime('%x %I:%m %p')+' '+sunday.strftime('%x %I:%m %p')) entries = TimeEntry.query.filter(TimeEntry.start >= monday).filter(TimeEntry.start < sunday + timedelta(days=1) ).all() week_total = db.session.query( #func.max(Score.score).label("max_score"), func.sum(TimeEntry.delta).label("Total") ).filter(TimeEntry.start >= monday).filter(TimeEntry.start < sunday + timedelta(days=1) ).filter(TimeEntry.delta != None).first() if week_total.Total == None: week_total = "%0.2f" % (0) else: week_total = "%0.2f" % (week_total.Total) total_today = db.session.query(func.sum(TimeEntry.delta).label("Total")) total_today = total_today.filter(TimeEntry.start >= datetime.combine(datetime.today(), time.min)) total_today = total_today.filter(TimeEntry.start <= datetime.combine(datetime.today(), time.max)) total_today = total_today.filter(TimeEntry.delta != None).first() if total_today.Total == None: total_today = "%0.2f" % (0) else: total_today = "%0.2f" % (total_today.Total) #qry = qry.group_by(Score.some_group_column) #for _res in qry.all(): # print _res #raise ValueError(entries) #total = db.session.query(TimeEntry) return render_template('home.html', time_entry_form=time_entry_form, entries = entries, start_or_stop = start_or_stop, monday = monday, sunday= sunday, week_total = week_total, total_today = total_today) @app.route('/totals') @login_required def totals(): projects = Project.query.all() the_data = [] for project in projects: entries = TimeEntry.query.filter_by(project_id = project.id).all() the_sum = 0 for entry in entries: the_sum += entry.delta the_data.append((project.name, '% 3.2f'%the_sum)) return render_template('totals.html', the_data = the_data) @app.route('/robots.txt') def robots(): return '''User-agent: * Disallow: /''' @app.route('/admin') @login_required def admin(): return redirect('/admin') @app.route('/settings') @login_required def settings(): return render_template('settings.html') return app
class UserPageAdmin(PageAdmin): column_labels = dict(email='E-Mail', password='******', first_name='Имя', second_name='Фамилия', last_name='Отчество', phone='Телефон', discont='Номер ДК', role='Права') class NewsPageAdmin(PageAdmin): form_overrides = dict(text=CKTextAreaField, description=CKTextAreaField) column_labels = dict(title='Заголовок', active='Активно', description='Краткий текст', text='Текст', creation_date='Дата публикации') class PartnersPageAdmin(PageAdmin): column_exclude_list = ['logo', 'description'] form_overrides = dict(logo=CKTextAreaField, description=CKTextAreaField) column_labels = dict(title='Заголовок', active='Активно', logo='Логитип', name='Наименование', description='Описание') admin = Admin(app) admin.add_view(UserPageAdmin(User, db.session, name="Пользователи")) admin.add_view(NewsPageAdmin(News, db.session, name="Новости")) admin.add_view(PartnersPageAdmin(Partner, db.session, name="Партнеры")) path = op.join(op.dirname(__file__), 'static/upload') admin.add_view(FileAdmin(path, '/upload/', name='Файлы')) # Add home link by url admin.add_link(MenuLink(name='Вернуться на сайт', url='/'))