import csv import os from flask import flash, request, redirect, url_for # from flask.ext.admin import BaseView, expose # from flask_admin.contrib.sqla import filters # from wtforms import validators from flask.ext.security import login_required, current_user from flask_admin.contrib import sqla from werkzeug.utils import secure_filename import system as syt from app import app, admin, db from app.models import Question, Question_Type, Card, Card_Category, Card_Type, Feedback, Session, User admin.add_view(sqla.ModelView(Question, db.session)) admin.add_view(sqla.ModelView(Question_Type, db.session)) admin.add_view(sqla.ModelView(Card, db.session)) admin.add_view(sqla.ModelView(Card_Type, db.session)) admin.add_view(sqla.ModelView(Card_Category, db.session)) admin.add_view(sqla.ModelView(Feedback, db.session)) admin.add_view(sqla.ModelView(Session, db.session)) #admin.add_view(sqla.ModelView(Session_Player, db.session)) admin.add_view(sqla.ModelView(User, db.session)) class UserAdmin(sqla.ModelView): # Don't display the password on the list of Users column_exclude_list = ('password',) # Don't include the standard password field when creating or editing a User (but see below) form_excluded_columns = ('password',)
#!/usr/bin/env python3 ''' File: wsgi.py Authors: 2014-11-14 - C.Shaw <*****@*****.**> Description: Application entry point for uWSGI. ''' from app import app, admin, FileView app.config['SERVER_NAME'] = 'image-site.colinshaw.org' app.config['UPLOAD_FOLDER'] = \ '/home/colin/applications/image-site/app/static/uploads' admin.add_view(FileView(app.config["UPLOAD_FOLDER"], '/static/uploads/', name="Uploaded Files"))
from flask import render_template, redirect, url_for, flash from app import app from app import db from app import admin from app.forms import AddRepair, SelectReport from app.models import Repairs from flask.ext.admin.contrib.sqla import ModelView # Admin views for modifying records # need to make this available via log in only. admin.add_view(ModelView(Repairs, db.session)) #Home page route @app.route('/') @app.route('/index', methods=['GET', 'POST']) def index(): # Get repairs for display on home page repairs = Repairs.query.order_by('date desc').all() # Render the home page with list of repairs return render_template('index.html', repairs = repairs) # Route for data entry (Repairs) @app.route('/repairs', methods = ['GET', 'POST']) def addrepair(): form = AddRepair() # Logic for inserting data into repair.db if form.validate_on_submit(): new_repair = Repairs(date = form.date.data, pc_num = form.pc_num.data, franchise = form.franchise.data,
form_class = super(UserAdmin, self).scaffold_form() form_class.password = PasswordField() return form_class class PortfolioAdmin(ModelViewSecurity): """ Portfolio Override photo for create FileUpload """ form_overrides = {"photo": form.FileUploadField} file_path = os.path.join(BASEDIR, "static/upload/portfolio") form_args = {"photo": {"label": "File", "base_path": file_path, "allow_overwrite": False}} class SiteAdmin(ModelViewSecurity): """ Site Override photo for create FileUpload """ form_overrides = {"photo": form.FileUploadField} file_path = os.path.join(BASEDIR, "static/upload/site") form_args = {"photo": {"label": "File", "base_path": file_path, "allow_overwrite": False}} admin.add_view(UserAdmin(models.User, db.session)) admin.add_view(SiteAdmin(models.Site, db.session)) admin.add_view(PortfolioAdmin(models.Portfolio, db.session))
from app import matrix,DB as db, admin from models.user import User, Team, UserAccount from models.application import Service, Application, Version, Environment, CodeBase, Component, Feature, Datapoint, Datacollection from models.news import News from flask.ext.admin.contrib.sqlamodel import ModelView admin.add_view(ModelView(User, db.session)) admin.add_view(ModelView(Application, db.session, category='Application')) admin.add_view(ModelView(Version, db.session, category='Application')) admin.add_view(ModelView(Feature, db.session, category='Application')) admin.add_view(ModelView(Environment, db.session, category='Application')) admin.add_view(ModelView(Datapoint, db.session, category='Application')) admin.add_view(ModelView(Team, db.session)) admin.add_view(ModelView(News, db.session)) admin.add_view(ModelView(Datacollection, db.session)) admin.add_view(ModelView(Service, db.session))
from app import app, db, admin from flask import render_template, g, redirect, url_for, flash from app.forms import AddCall, SelectReport, SelectShop, SelectFranchise, SelectMachine from app.models import Calls from flask.ext.admin.contrib.sqla import ModelView # Admin views for modifying records # need to make this available via log in only. admin.add_view(ModelView(Calls, db.session)) @app.route('/') @app.route('/index', methods=['GET', 'POST']) def index(): calls = Calls.query.order_by('date desc').all() return render_template('index.html', calls = calls) @app.route('/calls', methods=['GET', 'POST']) def addcall(): form = AddCall() # #add logic to insert data into the database. # redirect('/') if form.validate_on_submit(): new_call = Calls(date = form.date.data, caller = form.caller.data, phone = form.phone.data, franchise = form.franchise.data, location = form.location.data, downtime = form.downtime.data,
super(UserView, self).__init__(User, session, **kwargs) # 2. Static view # Inherits BaseView class class StaticView(ApplicationBaseView, BaseView): @expose('/', methods=('GET', 'POST')) def static_view(self): return self.render('admin/static_template.html') @expose('/time', methods=('GET', 'POST')) def show_time(self): return self.render('admin/time.html', time=datetime.now()) # 3. Serving files # Exposing folder for add/rename/delete operations on static files class FileView(ApplicationBaseView, FileAdmin): can_mkdir = False can_delete = True can_upload = True #bind UserView object to admin object admin.add_view(UserView(db_session)) #register static view on admin object admin.add_view(StaticView(name="Static view")) #register FileView on admin object path = op.join(op.dirname(op.dirname(__file__)), 'static') admin.add_view(FileView(path, name="Files"))
#!/home/yayo/virtual_enviroment/bin/python import os from app import create_app, db, admin, models from app.models import User, Role from flask.ext.script import Manager, Shell from flask.ext.admin.menu import MenuLink app = create_app(os.getenv("FLASK_CONFIG") or "default") manager = Manager(app) admin.add_view(models.UserView(models.User, db.session)) admin.add_link(MenuLink(name="Back", category="", url="/home")) def make_shell_context(): return dict(app=app, db=db, User=User, Role=Role) manager.add_command("shell", Shell(make_context=make_shell_context)) if __name__ == "__main__": manager.run()
column_list = [ 'civilite', 'nom', 'prenom', 'telephone', 'email', 'adresse' ] admin.add_view( VueConducteurContact( modeles.Conducteur, db.session, endpoint='conducteur/contact', category='Conducteur', name='Contact', menu_icon_type='glyph', menu_icon_value ='glyphicon-earphone' ) ) class VueConducteurSituation(VueConducteur): ''' Informations sur la situation des conducteurs. ''' column_list = [ 'civilite', 'nom', 'prenom',
from flask_admin.contrib.sqla import ModelView from app import db, admin, utils from app.models import Event from flask.ext.login import current_user from flask import redirect, url_for, request class EventAdmin(ModelView): column_display_pk = True form_widget_args = { 'slug':{ 'disabled':True } } def is_accessible(self): return current_user.is_authenticated() def inaccessible_callback(self, name, **kwargs): # redirect to login page if user doesn't have access return redirect(url_for('login', next=request.url)) def on_model_change(self, form, instance, is_created): instance.slug = utils.slugify(form.title.data) super(EventAdmin, self).on_model_change(form, instance, is_created) admin.add_view(EventAdmin(Event, db.session))
from app import db, lm, app, admin from app.users.models import * from flask.ext.admin import Admin, BaseView, expose from flask.ext.admin.contrib.sqla import ModelView class MyView(BaseView): @expose('/') def index(self): print("ACCESSING") if (app.config['DEBUG']) or (current_user.is_authenticated() and current_user.email in app.config['ADMINS']): return self.render('index.html') else: abort(401) def is_accessible(self): return True #! this should obviously be changed before production. In fact a lot of this should be changed class DataAdmin(ModelView): def __init__(self, model, session, **kwargs): super(DataAdmin, self).__init__(model, session, **kwargs) def is_accessible(self): return 'chef' in session admin.add_view(DataAdmin(User, db.session)) admin.add_view(DataAdmin(Week, db.session)) admin.add_view(DataAdmin(Day, db.session)) admin.add_view(DataAdmin(Diet, db.session))
class SubjectModelView(ProtectedModelView): column_editable_list = ['name', 'max_score'] create_modal = True class Upload(BaseView): @expose('/', methods=['GET', 'POST']) def upload(self): if not current_user.is_authenticated: return redirect(url_for('login')) if request.method == 'GET': return self.render('admin/upload.html', form=UploadForm()) if request.method == 'POST': form = UploadForm(request.form) file_storage = request.files['file'] grade = form.grade df = get_df(file_storage) html_table = df.head().to_html(classes=['table', 'table-hover', 'table-condensed', 'table-bordered'], border=0, index=False) subjects = get_subjects(df) return self.render('admin/uploaded.html', df=html_table) admin.add_view(ProtectedModelView(Role, db.session)) admin.add_view(ProtectedModelView(User, db.session)) admin.add_view(SubjectModelView(Subject, db.session)) admin.add_view(ProtectedModelView(Student, db.session)) admin.add_view(ProtectedModelView(Result, db.session)) admin.add_view(Upload(name='Upload'))
from flask import render_template, flash, redirect, session, url_for, request, g from flask_admin.contrib.sqla import ModelView import datetime from app import app, db, admin from .models import Tasks, Finish from .forms import TaskForm admin.add_view(ModelView(Tasks, db.session)) @app.route("/") def homepage(): return render_template( 'index.html', title='homepage', ) @app.route('/create_task', methods=['GET', 'POST']) def create_task(): form = TaskForm() time = datetime.date.today() flash('Errors="%s"' % form.errors) if form.validate_on_submit(): t = Tasks(title=form.name.data, state=form.urgent.data, year=form.year.data) db.session.add(t) db.session.commit()
# -*- coding: utf-8 -*- from app import admin, db from app.models import User from flask.ext.admin.contrib.sqla import ModelView admin.add_view(ModelView(User, db.session))
from flask_admin.contrib.sqla import ModelView from app import db,admin from app.models.WeixinTexttemplate import WeixinTexttemplate class WeixinTexttemplateView(ModelView): column_labels={ 'addtime':'添加时间' ,'templatename':'模板名称','weixinaccount':'微信账号', 'accountname':'微信账号','content':'内容','weixin_autoresponse':'自动回复' } page_size =10 admin.add_view(WeixinTexttemplateView(WeixinTexttemplate,db.session,name='消息模板'))
from app import app, admin from db import db from flask_admin.contrib.sqla import ModelView from models.user import UserModel db.init_app(app) @app.before_first_request def create_tables(): db.create_all() admin.add_view(ModelView(UserModel, db.session))
# -*- coding:utf-8 -*- import json from app import admin, db, app from app.models import Category, Obj, Object_Property_Value, Property, Operation, Pattern, Knowledge, Interpretation, queue, Record from app.handlers import perform_operations, interpret_situation from flask import render_template, redirect, url_for, jsonify, Response from flask.ext.admin.contrib.sqlamodel import ModelView admin.add_view(ModelView(Category, db.session)) admin.add_view(ModelView(Obj, db.session)) admin.add_view(ModelView(Property, db.session)) admin.add_view(ModelView(Object_Property_Value, db.session)) admin.add_view(ModelView(Interpretation, db.session)) admin.add_view(ModelView(Operation, db.session)) admin.add_view(ModelView(Pattern, db.session)) admin.add_view(ModelView(Record, db.session)) admin.add_view(ModelView(Knowledge, db.session)) @app.route('/history/<subj>') def history(subj): subj = Obj.query.filter(Obj.name==subj).first() records = subj.records return render_template('history.html', records = records) @app.route('/start/<subj>/<operation>') @app.route('/start/<subj>/<operation>/<obj>') def start(subj, operation, obj=None): subj = Obj.query.filter(Obj.name==subj).first() op = Operation.query.filter(Operation.name==operation).first() if obj is not None:
print(e) flash("Could not remove " + img_path_abs, "danger") else: flash("Successfully removed " + os.path.basename(img_path_abs), "success") print(request.path) if request.args.get('redirect'): redirect_url = request.args.get('redirect') else: # Go to the product the image belonged to redirect_url = '/admin/product/edit?id=' + str(product_id) return redirect(redirect_url) @main.route('/admin/product/<pid>/options/add', methods=['POST', 'DELETE']) @auth.login_required def product_options(pid): option_value = request.form['option_value'] print("Adding option", option_value, "for product id", pid) return "" admin.add_view(ProductView(Product, db.session, name="Products")) admin.add_view(ModelView(Order, db.session, name="Orders")) admin.add_view(ModelView(ProductImage, db.session, name="Images")) # admin.add_view(AdminDashboardView(name="Dashboard"))
from flask_admin.contrib.sqla import ModelView from app import db,admin from app.models.WeixinAutoresponse import WeixinAutoresponse from app.models.WeixinAccount import WeixinAccount #微信自动回复模板页面 class WeixinAutoresponseView(ModelView): column_labels={ 'addtime':'添加时间' ,'keyword':'关键字' ,'msgtype':'消息类型' ,'templatename':'模板名称','weixinaccount':'微信账号','weixintexttemplate':"模板" , 'accountname':'微信账号','weixintexttemplate.templatename':"模板",'weixinaccount.accountname':'微信账号' } column_list=('weixinaccount.accountname','weixintexttemplate.templatename', 'addtime', 'keyword', 'templatename','msgtype') page_size =10 admin.add_view(WeixinAutoresponseView(WeixinAutoresponse,db.session,name='自动回复'))
return False def on_file_upload(self, directory, path, filename): db.session.add(ThemeSong(filename=filename)) db.session.commit() class UserModelView(ModelView): can_create=False form_overrides = dict(status=SelectField) form_args = dict( urole=dict( choices=[(0,"USER"), (1,"admin")])) def is_accessible(self): if g.user.is_authenticated and g.user.is_admin: return True else: return False admin.add_view(SoundModelView(Sound, db.session)) admin.add_view(ThemeSongModelView(ThemeSong, db.session, name="Theme Songs")) admin.add_view(ModelView(Tag, db.session)) admin.add_view(UserModelView(User, db.session)) admin.add_view(SoundFileAdmin(os.path.join(basedir, 'sounds'), '/sounds/', name = 'Upload Sounds')) admin.add_view(ThemeSongFileAdmin(os.path.join(basedir, 'themes'), '/themes/', name = 'Upload Theme Songs')) # # Midi control pad stuff goes here: # chromatic = range(36,81) # Values for the "Chromatic" preset, 36 through 80 PADMAP = chromatic # Eventually I'll implement a "favorites" in the model to replace this. For now, hardcoded favorite tags to use on the mpd.
can_edit = False can_delete = False #Colonnes pour chercher column_searchable_list = ['nom','prenom'] class VueAdresse(VueGeo) : # Rendre impossible la création, la modification et la suppression can_create = True can_edit = True can_delete = True # Adresses admin.add_view(VueAdresse(modeles.Adresse, db.session)) # Utilisateurs admin.add_view(VueUtilisateur(modeles.Utilisateur, db.session)) # Secteurs admin.add_view(VueSecteur(modeles.Secteur, db.session)) # Stations admin.add_view(VueStation(modeles.Station, db.session)) # Vehicules admin.add_view(VueVehicule(modeles.Vehicule, db.session)) # Conducteurs admin.add_view(VueConducteur(modeles.Conducteur, db.session))
from app.emails import send_email from werkzeug.utils import secure_filename from flask_admin.contrib.sqla import ModelView from flask_admin.contrib.fileadmin import FileAdmin from pygeocoder import Geocoder import os.path as op from config import ADMINS # file upload setting UPLOAD_AGENT_FOLDER = 'app/static/agent_photo' UPLOAD_HOUSE_FOLDER = 'app/static/house_photo' ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) MAX_CONTENT_LENGTH = 16 * 1024 * 1024 # admin management setup admin.add_view(ModelView(User, db.session)) admin.add_view(ModelView(Post, db.session)) path = op.join(os.path.abspath(__file__ + "/../../"), 'static') # need to get parent path of this code admin.add_view(FileAdmin(path, '/static/', name='Static Files')) @main_bp.before_app_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() @main_bp.route('/list_post', methods=['GET', 'POST'])
'civilite', 'nom', 'prenom', 'telephone', 'fax', 'email', 'adresse' ] admin.add_view( VueUtilisateurContact( modeles.Utilisateur, db.session, endpoint='utilisateur/contact', category='Utilisateur', name='Contact', menu_icon_type='glyph', menu_icon_value='glyphicon-earphone' ) ) class VueUtilisateurCompte(VueUtilisateur): ''' Informations sur le compte de l'utilisateur. ''' column_list = [ 'nom', 'prenom', 'telephone',
'REMOTE_USER') # workaround for Apache if not auth or (auth.username, auth.password) != app.config['ADMIN_CREDENTIALS']: raise HTTPException('', Response('Il faut rentrer les identifiants administrateur.', 401, {'WWW-Authenticate': 'Basic realm="Identifiants requis"'} )) return True class VueUtilisateur(VueModele): # Rendre impossible la création, la modification et la suppression can_create = False can_edit = False can_delete = False # Colonnes invisible column_exclude_list = ['_mdp'] # Colonnes pour chercher column_searchable_list = ['prenom', 'nom'] # Colonnes pour filtrer column_filters = ['categorie', 'inscription', 'confirmation'] # Utilisateurs admin.add_view(VueUtilisateur(modeles.Utilisateur, db.session)) # Fichiers de style path = op.join('/'.join(op.dirname(__file__).split('/')[:-1]), 'static') admin.add_view(FileAdmin(path, '/static/', name='Static'))
def __init__(self, session, **kwargs): # You can pass name and other parameters if you want to super(SettingsView, self).__init__(Settings, session, **kwargs) def is_accessible(self): if g.user.is_authenticated(): return g.user.role #ROLE_ADMIN == 1, user = 0 else: #anonymous user return 0 class EmailView(ModelView): def __init__(self, session, **kwargs): # You can pass name and other parameters if you want to super(EmailView, self).__init__(Email, session, **kwargs) def is_accessible(self): if g.user.is_authenticated(): return g.user.role #ROLE_ADMIN == 1, user = 0 else: #anonymous user return 0 #add flask admin views admin.add_view(UserView(db.session)) admin.add_view(ZoneView(db.session)) admin.add_view(ValidUsersView(db.session)) admin.add_view(SettingsView(db.session)) admin.add_view(EmailView(db.session)) admin.add_link(MenuLink(name='Clear History', url='/clearhistory')) admin.add_link(MenuLink(name='Exit Admin', url='/'))
from flask.ext.admin import BaseView, expose from flask import g from flask.ext.admin.contrib.sqla import ModelView, fields from flask.ext.admin.contrib.fileadmin import FileAdmin import os.path as op from config import SUPERUSERS from wtforms import validators path = op.join(op.dirname(__file__), 'static') class MyBase(ModelView): pass ## def is_accessible(self): ## return g.user.is_authenticated() and (g.user.net_id in SUPERUSERS) class Admin(MyBase): can_create = True class Member(MyBase): can_create = True class StaticFilesAdmin(FileAdmin): pass admin.add_view(Member(models.Member, db.session)) admin.add_view(Admin(models.Admin, db.session))
'conducteur', 'marque', 'modele', 'places', 'couleur', 'attelage', 'vbreak', 'voiture_basse' ] admin.add_view( VueVehiculeType( modeles.Vehicule, db.session, endpoint = 'VehiculeType', category = 'Vehicule', name = 'Types de Véhicule', menu_icon_type='glyph', menu_icon_value ='glyphicon-wrench' ) ) class VueVehiculeClient(VueVehicule) : column_list = [ 'immatriculation', 'conducteur', 'vip', 'mineur', 'animaux', 'anglais',
column_searchable_list = [ 'nom' ] form_columns = [ 'nom', 'adresse', 'distance_entree', 'distance_sortie' ] def _lien_adresse(view, context, model, name): ''' Renvoyer le lien d'édition de l'adresse. ''' lien = Markup( "<a href='{0}'>{1}</a>".format( url_for('adresse.edit_view', id=model.adresse), model.adresse ) ) return lien column_formatters = { 'adresse': _lien_adresse } admin.add_view( VueStation( modeles.Station, db.session ) )
form.youtube_channel.data = profile.youtube_channel form.blog_channel.data = profile.blog_channel return self.render('/admin/my_custom/settings.html', form=form, action_name='Edit Your Profile', settings='profile') def is_visible(self): return False class RestrictedAdminView(ModelView): def is_accessible(self): if hasattr(g, 'user') and g.user is not None and 'Admin' in g.user.roles: return True return False admin.add_view(ApprovalContentAdminView(Article, name='Article', endpoint='approval.article', category="Approvals")) #admin.add_view(ApprovalContentAdminView(Blog, name='Blog', endpoint='approval.blog', category="Approvals")) admin.add_view(ApprovalContentAdminView(Discussion, name='Discussion', endpoint='approval.discussion', category="Approvals")) admin.add_view(ProfileAdminView(Profile, category="Administration")) admin.add_view(ActivityAdminView(Activity, category="Administration")) admin.add_view(AdventureAdminView(Adventure, category="Administration")) admin.add_view(RestrictedAdminView(Advertisement, category="Administration")) admin.add_view(ContentAdminView(Article, category="Editorial")) #admin.add_view(ContentAdminView(Blog, category="Editorial")) admin.add_view(ContentAdminView(Discussion, category="Editorial")) admin.add_view(PostAdminView(Post, category="Editorial")) admin.add_view(PostForContentAdminView(Post, name="Posts on content", endpoint="content_post_admin_view")) admin.add_view(EventAdminView(Event, category="Organizers"))
from flask_admin.contrib.sqla import ModelView from app import db,admin from app.models.WeixinPlugins import WeixinPlugins from app.models.WeixinAccount import WeixinAccount import uuid #插件维护页面 class WeixinPluginsView(ModelView): page_size =10 def on_model_change(self, form, weixinplugins, is_created): weixinplugins.id =str(uuid.uuid1()).replace('-','') admin.add_view(WeixinPluginsView(WeixinPlugins,db.session,name='插件'))
app = Flask(__name__) app.config.from_object('config') # Setup SQL database and ORM db = SQLAlchemy(app) # Initialize Flask-Security from models import User, Role, Ticket, Invoice user_datastore = SQLAlchemyUserDatastore(db, User, Role) security = Security(app, user_datastore) mail = Mail(app) # Initialize Flask-Admin from app import admin admin = Admin(app, name='PacketCrypt', index_view=admin.AdminIndex()) admin.add_view(ModelView(User, db.session)) admin.add_view(ModelView(Ticket, db.session)) admin.add_view(ModelView(Invoice, db.session)) @app.before_first_request def initialize(): try: db.create_all() user = user_datastore.find_user(email='*****@*****.**') if not user: user = user_datastore.create_user(email='*****@*****.**', password='******') user_datastore.add_role_to_user(user, 'Admin') app.logger.info("First run, create default admin user") for role in ('Admin', 'User'): user_datastore.create_role(name=role) db.session.commit()
def post(): if request.method == 'GET': posts = [i.to_dict() for i in Post.query.all()] for i in posts: i['author'] = i['author'].username return jsonify(posts) elif request.method == 'POST': form = request.form body = form['body'] anonymous = form['anonymous'] if anonymous == 'false': post = Post(body=body, user_id=current_user.id, timestamp=datetime.now()) else: post = Post(body=body, user_id=0, timestamp=datetime.now()) try: db.session.add(post) db.session.commit() except BaseException as err: return jsonify({'code': '500', 'message': err}) return jsonify({'code': '200', 'message': 'Post Success!!'}) admin.add_view(ModelView(User, db.session)) admin.add_view(ModelView(Admins, db.session)) admin.add_view(ModelView(Phone, db.session)) admin.add_view(ModelView(Vote, db.session)) admin.add_view(ModelView(Post, db.session))