コード例 #1
0
def SetupAdmin(app):
    class CustomView(ModelView):
        form_excluded_columns = ['created_at', 'updated_at']

    # class HomeView(AdminIndexView):
    #     @expose('/admin')
    #     def index(self):
    #         return self.render('file_upload.html')

    # class MyView(BaseView):
    #     @expose('/admin')
    #     def index(self):
    #         return self.render('file_upload.html')

    admin = Admin(app, name='Poker Society', template_mode='bootstrap3')

    # admin = Admin(app, name='Poker Society', template_mode='bootstrap3',
    #     index_view=AdminIndexView(
    #         name='File Upload',
    #         template='file_upload.html',
    #         url='/admin'
    #     )
    # )

    admin.add_views(CustomView(Users, db.session),
                    CustomView(Casinos, db.session),
                    CustomView(Tournaments, db.session),
                    CustomView(Flights, db.session),
                    CustomView(Results, db.session),
                    CustomView(Subscribers, db.session))

    return admin
コード例 #2
0
class PyXwordAdmin:
    def __init__(self, db):
        self.admin = None
        self.db = db

    def init_app(self, app):
        session = self.db.session

        # inline imports to prevent circular import
        from pyxword_contest.user.models import User
        from pyxword_contest.crossword.models import Crossword
        import pyxword_contest.contest.models as contest_models

        self.admin = Admin(template_mode='bootstrap3',
                           index_view=ProtectedAdminIndex(url='/funadmin', ),
                           app=app)
        self.admin.add_views(*[
            UserView(User, session, endpoint='users'),
            ProtectedModelView(Crossword, session, endpoint='crosswords'),
            ContestView(contest_models.Contest, session, endpoint='contents'),
            ProtectedModelView(contest_models.ContestInitialCrosswords,
                               session),
            ProtectedModelView(contest_models.ContestStage, session),
            ProtectedModelView(contest_models.ContestStageWinner, session),
            ProtectedModelView(contest_models.UserStats, session),
            ProtectedModelView(contest_models.UserCrossword, session),
        ])
コード例 #3
0
def create_app(config='settings'):
    warnings.filterwarnings('ignore', message='Fields missing from ruleset')

    app = Flask(__name__)
    app.config.from_object(config)

    if 'STATIC_FOLDER' in app.config:
        app.static_folder = app.config['STATIC_FOLDER']

    db.init_app(app)
    babel.init_app(app)
    mail.init_app(app)
    from application.models import User, Role
    security.init_app(app, datastore=SQLAlchemyUserDatastore(db, User, Role))

    from application.admin import admin_views, FileAdmin
    os.makedirs(app.config['UPLOAD_DIR'], exist_ok=True)
    FileAdminView = FileAdmin(app.config['UPLOAD_DIR'],
                              app.config['UPLOAD_URL'],
                              name='Файлы',
                              url='/admin',
                              endpoint='admin')
    admin = Admin(app, index_view=FileAdminView)
    admin.add_link(MenuLink(name='Вернуться на сайт', category='', url='/'))
    admin.add_views(*admin_views)

    from application.templatetags import EntryRenderExtension
    app.jinja_env.add_extension(EntryRenderExtension)

    from application.views import main
    app.register_blueprint(main, url_prefix='')

    return app
コード例 #4
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    db.init_app(app)
    ckeditor.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)

    # Admin

    from .models import User, Post

    admin = Admin(app, 'FlaskyApp', url='/', index_view=HomeAdminView())
    admin.add_views(UserAdminView(User, db.session), PostAdminView(Post, db.session))

    # Blueprints

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .auth import auth as auth_blueprint
    app.register_blueprint(auth_blueprint, url_prefix='/auth')

    return app
コード例 #5
0
def create_app():
    app = Flask(__name__)
    app.secret_key = 'bdb92dbe238008edfac05e92412b0c23'  # Another bad practice in security is
    # when you embed security keys in your code like this
    # app.config['PERMANENT_SESSION_LIFETIME'] = 120  # session lifetime disabled for showing bad security practice
    app.config['FLASK_ADMIN_SWATCH'] = 'united'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///info.db'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    admin = Admin(app, name='Admin-Panel', template_mode='bootstrap3')
    db.init_app(app)
    # csrf.init_app(app)

    with app.app_context():
        from application.views import main_bp
        from application.model import db_init, User, Comments
        app.register_blueprint(main_bp)

        # admin.add_views(MyModelView(User, db.session), MyModelView(Comments, db.session))  #  For the custom model above
        admin.add_views(ModelView(User, db.session), ModelView(Comments, db.session))
        db.drop_all()
        db_init()  # initialize sql injection db for part 1
        db.create_all()  # initialize db for logins, comments
        db.session.add(Comments(comment=' 🤘🏾🤘🏾 Spaces in code is the way to go. Who uses Tabs 😂😂?'))
        db.session.add(User(username='******', password='******'))
        db.session.add(User(username='******', password='******'))
        db.session.commit()
        return app
コード例 #6
0
ファイル: admin.py プロジェクト: limeiralucas/dbmonit
def init_app(app):
    admin = Admin(index_view=HomeView())
    admin.name = app.config.TITLE
    admin.template_mode = "bootstrap3"
    admin.base_template = "layout.html"
    admin.init_app(app)
    admin.add_view(OperationView(Operation, db.session))
    admin.add_view(UserAdmin(User, db.session))
    admin.add_views(ClientAdmin(Client, db.session))
コード例 #7
0
ファイル: admin_page.py プロジェクト: Simple2B/vaa.dash
def init_admin(app, db):
    admin = Admin(
        app,
        template_mode="bootstrap3",
    )
    admin.add_views(UserModelView(User, db.session))
    admin.add_views(RoleModelView(Role, db.session))
    admin.add_views(DashboardModelView(Dashboard, db.session))
    return admin
コード例 #8
0
def init_app(app):
    url = os.environ["FLASK_ADMIN_URL"]
    admin = Admin(app=app,
                  name="negros.dev",
                  url=url,
                  index_view=AdminView(url=url))

    admin.add_view(UserAdmin(User, db.session))
    admin.add_view(ContentAdmin(Content, db.session))
    admin.add_views(ModelView(Source, db.session))
コード例 #9
0
def register_admin(app):
    admin = Admin(app=app, template_mode='bootstrap3')
    admin.add_link(MenuLink(name='Voltar', url=('/')))
    admin.add_views(
        ProtectedModelView(User, db.session),
        ProtectedModelView(Role, db.session),
        ProtectedModelView(PreAllowedUser, db.session),
        ProtectedModelView(Product, db.session),
        ProtectedModelView(Specification, db.session),
        ProtectedModelView(StockProduct, db.session),
        ProtectedModelView(Stock, db.session),
        ProtectedModelView(Order, db.session),
        ProtectedModelView(OrderItem, db.session),
        ProtectedModelView(Transaction, db.session),
    )
コード例 #10
0
def init_app(app):
    login_manager.init_app(app)

    from . import hydra_oauth2, user, member, institution, role, scope
    app.register_blueprint(hydra_oauth2.bp, url_prefix='/oauth2')

    home = AdminIndexView(
        url='/',
    )
    users = user.UserModelView(
        User, db_session,
        name='Users',
        endpoint='users',
    )
    privileges = member.MemberModelView(
        Member, db_session,
        name='Privileges',
        endpoint='privileges',
    )
    institutions = institution.InstitutionModelView(
        Institution, db_session,
        name='Institutions',
        endpoint='institutions',
    )
    roles = role.RoleModelView(
        Role, db_session,
        name='Roles',
        category='System Configuration',
        endpoint='roles',
    )
    scopes = scope.ScopeModelView(
        Scope, db_session,
        name='Scopes',
        category='System Configuration',
        endpoint='scopes',
    )

    admin_views = Admin(app, name='ODP Admin', index_view=home, base_template='admin_base.html')
    admin_views.add_views(
        institutions,
        users,
        privileges,
        roles,
        scopes,
    )
コード例 #11
0
def initialize_app(app, home_endpoint=None):
    models.connect()

    @app.before_request
    def _db_connect():
        models.database.connect()

    @app.teardown_request
    def _db_close(exc):
        if not models.database.is_closed():
            models.database.commit()
            models.database.close()

    admin = Admin(app, name='Raw Table Admin', template_mode='bootstrap3')

    if home_endpoint:
        admin.add_link(
            MenuLink("Devtest Main", url="/", endpoint=home_endpoint))

    admin.add_views(TestBedView(), EquipmentModelView(), EquipmentView(),
                    NetworksView(), InterfacesView(), ConnectionView(),
                    AccountIdsView(), TestequipmentView())
    admin.add_views(SoftwareView(), SoftwareVariantView(), FunctionView())
    admin.add_views(ScenarioView(), TestSuiteView(), TestCaseView(),
                    TestResultsView())
    admin.add_view(RadarComponentView())
コード例 #12
0
ファイル: admin.py プロジェクト: KazakovDenis/flask-blog
def create_admin(app, db):
    admin = Admin(app,
                  'Admin panel',
                  url='/admin',
                  index_view=HomeAdminView(),
                  template_mode='bootstrap3')
    admin.add_views(
        # Content
        PostAdminView(Post, db.session, category='Content'),
        TagAdminView(Tag, db.session, category='Content'),

        # Management
        UserAdminView(User, db.session, category='Management'),
        RoleAdminView(Role, db.session, category='Management'),
        ParameterAdminView(Parameter,
                           db.session,
                           name='Settings',
                           category='Management'),
        FilesAdminView(PUBLIC_DIR, name='Files', url='/admin/files/'),
    )
    admin.add_links(MenuLink('Back to app', endpoint='main.get_notes'), )
    return admin
コード例 #13
0
ファイル: __init__.py プロジェクト: motet-a/obs-matcher
def setup_admin(app):
    admin = Admin(base_template='admin_master.html')
    admin.add_views(
        PlatformView(Platform,
                     db.session,
                     name='Platform',
                     category='Platforms'),
        PlatformGroupView(PlatformGroup,
                          db.session,
                          name='Group',
                          category='Platforms'),
        ScrapView(Scrap, db.session, name='Scrap', category='Platforms'),
        ValueView(Value, db.session, name='Value', category='Values'),
        ValueSourceView(ValueSource,
                        db.session,
                        name='Source',
                        category='Values'),
        ObjectLinkView(ObjectLink, db.session),
        AllObjectView(db.session, name='All'),
        PersonObjectView(db.session, name='Persons'),
        MovieObjectView(db.session, name='Movies'),
    )
    admin.init_app(app, endpoint='admin', url='/admin')
コード例 #14
0
ファイル: __init__.py プロジェクト: MayarKarkout/fantasy-app
def create_app():
    app = Flask(__name__)

    app.config.from_object(Config())

    # blueprint for routes in our app
    from app.routes.auth import auth as auth_blueprint
    from app.routes.main import main as main_blueprint
    from app.routes.api import api as api_blueprint

    app.register_blueprint(auth_blueprint)
    app.register_blueprint(main_blueprint)
    app.register_blueprint(api_blueprint)

    db.init_app(app)

    admin = Admin(app, template_mode='bootstrap3')
    admin.add_views(AppModelView(User, db.session))
    admin.add_view(AppModelView(Profile, db.session))
    admin.add_view(AppModelView(FantasyTeam, db.session))
    admin.add_view(AppModelView(Team, db.session))
    admin.add_view(AppModelView(Player, db.session))

    admin.add_view(AppModelView(Goal, db.session))
    admin.add_view(AppModelView(Match, db.session))
    admin.add_view(AppModelView(RoundScore, db.session))

    # print(config.SQLALCHEMY_DATABASE_URI)
    # print(db.app)

    login_manager.init_app(app)
    migrate = Migrate(app, db, render_as_batch=True)
    print('hi')
    # app.config['SECRET_KEY'] = 'secret!'

    return app
コード例 #15
0
from py_market.models import *
from .admin_views import *
from os import path

admin = Admin(app,
              template_mode='bootstrap3',
              index_view=MyHomeView(name="Главная"))
admin.add_view(
    UserView(User, db.session, category="Пользователи", name="Пользователь"))
admin.add_view(RoleView(Role, db.session, category="Пользователи",
                        name="Роли"))
admin.add_view(ProductView(Product, db.session, category="Товар",
                           name="Товар"))
admin.add_views(
    DefaultView(Material,
                db.session,
                category="Товар",
                name="Материалы/состав товара"),
    DefaultView(Category,
                db.session,
                category="Товар",
                name="Категории товара "))
admin.add_view(NewsEditor(endpoint="news", name="Добавить новость"))

bp_admin = Blueprint('bp_admin',
                     __name__,
                     url_prefix='/admin',
                     template_folder="templates",
                     static_folder="static",
                     static_url_path="my_admin/static")
コード例 #16
0

@app.after_request
def after_request(response):
    if g:
        username = g.get("username")
    if get_jwt_identity():
        username = get_jwt_identity().get("username")

    if username:
        user = db.session.query(
            models.User).filter_by(username=username).first()
        log_entry = models.UserLogEntry(
            user_id=user.id,
            method=request.method,
            url=str(request.url_rule),
            timestamp=datetime.utcnow(),
        )
        db.session.add(log_entry)
        db.session.commit()

    return response


with app.app_context():
    from app import models
    db.create_all()

    admin.add_views(ModelView(models.Post, db.session),
                    ModelView(models.User, db.session))
コード例 #17
0
app.register_blueprint(kpi_blueprint, url_prefix='/kpi')


class KPIAdminModel(ModelView):
    can_create = True
    column_list = ('id', 'created_by', 'created_at', 'updated_at',
                   'updated_by', 'name')


from events import event_bp as event_blueprint

app.register_blueprint(event_blueprint, url_prefix='/events')

from models import KPI

admin.add_views(KPIAdminModel(KPI, db.session, category='KPI'))

from studs import studbp as stud_blueprint

app.register_blueprint(stud_blueprint, url_prefix='/stud')

from food import foodbp as food_blueprint

app.register_blueprint(food_blueprint, url_prefix='/food')
from food.models import (Person, Farm, Produce, PesticideTest, BactTest,
                         ParasiteTest)

admin.add_views(ModelView(Person, db.session, category='Food'))
admin.add_views(ModelView(Farm, db.session, category='Food'))
admin.add_views(ModelView(Produce, db.session, category='Food'))
admin.add_views(ModelView(PesticideTest, db.session, category='Food'))
コード例 #18
0
                h=admin_helpers,
                get_url=url_for)


# admin views
if app.config.production:
    # use to switch between secure view and unsecure view if developing
    secure = True
    print("Admin Secure")
else:
    secure = False
    print("Admin not secure")

if secure:
    admin.add_views(SecureMovieView(Movie, db.session, category="Movies"),
                    SecureModelView(Director, db.session, category="Movies"),
                    SecureModelView(Actor, db.session, category="Movies"),
                    SecureModelView(Genre, db.session, category="Movies"))
    admin.add_views(
        SecureModelView(Auditorium, db.session, category="Theater"),
        SecureModelView(Seat, db.session, category="Theater"),
    )
    admin.add_views(
        SecureModelView(Show, db.session, category="booking"),
        SecureModelView(Reservation, db.session, category="booking"),
    )
    admin.add_views(SecureModelView(User, db.session, category="Accounts"),
                    SecureModelView(Role, db.session, category="Accounts"))
else:
    admin.add_views(UnsecureMovieView(Movie, db.session, category="Movies"),
                    UnsecureModelView(Director, db.session, category="Movies"),
                    UnsecureModelView(Actor, db.session, category="Movies"),
コード例 #19
0
ファイル: main.py プロジェクト: arsaizdihar/arsa-blog
    column_formatters = {
        'file': _file_url,
        "preview": _file_embed,
    }

    @expose('/new', methods=["POST", "GET"])
    def create_view(self):
        return upload_file()


admin = Admin(app=app, index_view=HomeView())
admin.add_views(
    UserModelView(User, db.session),
    UserModelView(BlogPost, db.session),
    UserModelView(Comment, db.session),
    UserModelView(Contact, db.session),
    ImageView(Image, db.session),
    FileView(File, db.session),
    UserModelView(PortfolioData, db.session)
)

# add function to jinja
app.jinja_env.globals.update(check_admin=check_admin)

login_manager = LoginManager()
login_manager.init_app(app)

gravatar = Gravatar(app, size=100, rating='g', default='retro', force_default=False, force_lower=False, use_ssl=False, base_url=None)


@login_manager.user_loader
コード例 #20
0
try:
    app.config.update(**settings.as_dict())
except:
    app.config.from_pyfile(
        path.join(path.dirname(temp_dir), 'configs', 'common_deploy.py'))
    print("Сonfiguration has been installed as \'common_deploy\'")

#services declarations
api = Api(app)
db = SQLAlchemy(app)
migrate = Migrate(app, db)
bcrypt = Bcrypt(app)

from src.database.admin_view import AdminIndexView
admin = Admin(app, index_view=AdminIndexView(), template_mode='bootstrap3')

from src.database.models import User, Department, Role, UserDepartmentRole
from src.database.admin_view import UserModelView, DepartmentModelView
admin.add_views(UserModelView(User, db.session, category="model"),
                DepartmentModelView(Department, db.session, category="model"),
                ModelView(Role, db.session, category="model"),
                ModelView(UserDepartmentRole, db.session, category="model"))

#logging customization
if not app.config['DEBUG']:
    file_error_handler = FileHandler('logs/errorlog.txt')
    file_error_handler.setLevel(WARNING)
    app.logger.addHandler(file_error_handler)

from src import routes
from src.database import models
コード例 #21
0
class AlphaFlask(Flask, Requests):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.pid = None
        self.conf = None
        self.config_path = ""

        self.log = None
        self.log_requests = None
        self.db = None
        self.admin_db = None

        self.cache_dir = ""

        # need to put it here to avoid warnings
        #self.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True  # TODO modify

        self.ma = Marshmallow(self)

        self.routes_objects = {}

    def get_parameters(self, not_none=False) -> Dict[str, object]:
        """Get non private route parameters values as a dict.

        Returns:
            Dict[str, object]: [description]
        """
        route = self.get_current_route()
        parameters = route.parameters
        parameters_values = {
            x: y.value
            for x, y in parameters.items()
            if not y.private and (not not_none or y.value is not None)
        }
        return parameters_values

    def set_data(self, data):
        self.get_current_route().set_data(data)

    def set_file(self, directory, filename):
        self.get_current_route().set_file(directory, filename)

    def get_file(self, directory, filename, attached=False):
        self.get_current_route().get_file(directory, filename, attached)

    def set_html(self, page, parameters={}):
        self.get_current_route().set_html(page, parameters)

    def set_databases(self, db_cnx):
        if not "main" in db_cnx:
            self.log.error("You must define a <main> database")
            exit()

        uri = db_cnx["main"]["cnx"]
        if ":///" in uri:
            io_lib.ensure_file(uri.split(":///")[1])
        db_type = db_cnx["main"]["type"]
        self.config["SQLALCHEMY_DATABASE_URI"] = uri

        for key, cf_db in db_cnx.items():
            self.config["SQLALCHEMY_BINDS"] = {
                x: y["cnx"]
                for x, y in db_cnx.items()
            }

        # self.api.config["MYSQL_DATABASE_CHARSET"]           = "utf8mb4"
        # self.api.config["QLALCHEMY_TRACK_MODIFICATIONS"]    = True
        # self.api.config["EXPLAIN_TEMPLATE_LOADING"]         = True
        self.config["UPLOAD_FOLDER"] = self.root_path

    def init(self, encode_rules={}):
        routes = self.conf.get("routes")
        if routes is not None:
            for route in routes:
                module = importlib.import_module(route)
        self.cache_dir = self.conf.get("directories/cache")

        # check request
        # ! freeze - dont know why
        """db              = core.get_database("main")
        request_model    = database_lib.get_table("main", "request")
        try:
            self.log.debug("Check <request> table")
            obj = db.exist(request_model)
        except:
            self.log.info("Creating <request> table")
            request_model.__table__.create(db.engine)"""

        # Flask configuration
        # todo: check JWT_SECRET_KEY: mandatory
        confs = self.conf.get("config")
        if confs is not None:
            for key, value in confs.items():
                self.config[key] = value

        self.json_encoder = AlphaJSONEncoder
        for key_rule, fct in encode_rules.items():
            AlphaJSONEncoder.rules[key_rule] = fct

        self.config["SECRET_KEY"] = b'_5#y2L"F4Q8z\n\xec]/'

        # MAILS
        mail_config = self.get_config("mails/mail_server")

        if mail_config is not None:
            self.config.update(
                MAIL_USE_TLS=mail_config["tls"],
                MAIL_USE_SSL=mail_config["ssl"],
                MAIL_SERVER=mail_config["server"],
                MAIL_PORT=mail_config["port"],
                MAIL_USERNAME=mail_config["mail"],
                MAIL_PASSWORD=mail_config["password"],
            )
            self.mail = Mail(self)
        else:
            self.log.error(
                'Mail configuration is not defined ("mails/mail_server" parameter)'
            )

        if self.conf.get("toolbar"):
            self.log("Loading debug toolbar")
            toolbar = DebugToolbarExtension(self)

        if self.conf.get("dashboard/dashboard/active"):
            self.log.info("Loading dashboard")
            filepath = config_lib.write_flask_dashboard_configuration()
            if filepath is not None:
                self.log.info("Dashboard configured from %s" % filepath)
                flask_monitoringdashboard.config.init_from(file=filepath)
                flask_monitoringdashboard.bind(self)

        if self.conf.get("admin_databases"):
            self.log.info("Loading admin databases interface")
            self.init_admin_view()

        # Base.prepare(self.db.engine, reflect=True)

    def set_config(self, name, configuration=None, root=None):
        self.log.debug("Set <%s> configuration for API from %s in %s" %
                       (configuration, name, root))
        self.config_path = root + os.sep + name + ".json"
        self.configuration = configuration

        self.conf = AlphaConfig(
            name=name,
            configuration=configuration,
            root=root,
            log=self.log,
            required=['directories/cache'
                      ])  # root=os.path.dirname(os.path.realpath(__file__))

        if self.conf.get("routes_no_log"):
            _colorations.WerkzeugColorFilter.routes_exceptions = self.conf.get(
                "routes_no_log")

    def init_admin_view(self):
        views = flask_lib.load_views(self.log)
        endpoints = [x.endpoint for x in views]

        from ..database.views import views as alpha_views

        for view in alpha_views:
            if view.endpoint not in endpoints:
                views.append(view)

        self.admin_db = Admin(self,
                              name=self.get_config("name"),
                              template_mode="bootstrap3")
        self.admin_db.add_views(*views)

    def start(self):
        if self.pid is not None:
            return

        ssl_context = None
        if self.conf.get("ssl"):
            ssl_context = (self.conf.get("ssl_cert"), self.conf.get("ssl_key"))

        host = self.conf.get("host")
        port = self.conf.get("port")
        threaded = self.conf.get("threaded")

        self.debug = self.conf.get(
            "debug") if not "ALPHA_DEBUG" in os.environ else (
                "y" in os.environ["ALPHA_DEBUG"].lower()
                or "t" in os.environ["ALPHA_DEBUG"].lower())
        if self.debug:
            sys.dont_write_bytecode = True

        self.log.info("Run api on host %s port %s %s" %
                      (host, port, "DEBUG MODE" if self.debug else ""))

        mode = self.conf.get("mode")
        if 'ALPHA_API' in os.environ:
            mode = os.environ['ALPHA_API']

        # try:
        if mode == "wsgi":
            application = DebuggedApplication(self,
                                              True) if self.debug else self

            if host == "0.0.0.0" or host == "localhost" and os_lib.is_linux():
                host = ""
            self.log.info("Running %sWSGI mode on host <%s> and port %s" %
                          ("debug " if self.debug else "", host, port))

            server = WSGIServer((host, port),
                                application,
                                log=self.log_requests.logger)
            server.serve_forever()
        else:
            # Get werkzueg logger
            log = logging.getLogger("werkzeug")
            log.addFilter(_colorations.WerkzeugColorFilter()
                          )  # TODO: set in configuration
            log.disabled = self.conf.get("log") is None

            self.run(
                host=host,
                port=port,
                debug=self.debug,
                threaded=threaded,
                ssl_context=ssl_context,
            )

        # except SystemExit:
        #    self.info("API stopped")

    def stop(self, config_path=None):
        if config_path is None:
            config_path = self.config_path
        if self.config_path is None:
            return

        #self.set_config(config_path=config_path, configuration=self.configuration)

        pid = self.get_config(["tmp", "process"])

        os.kill(pid, 9)

        self.log.info("Process n°%s killed" % pid)

    def get_config(self, name=""):
        if "/" in name:
            name = name.split("/")
        conf = self.conf.get(name)
        return conf

    def get_url(self, local=False):
        if local:
            return "http://localhost:%s" % self.conf.get("port")
        ssl = self.get_config("ssl")
        pref = "https://" if ssl else "http://"
        return pref + self.get_config("host_public")

    def access_denied(self):
        self.get_current_route().access_denied()

    def get(self, name):
        route = self.get_current_route()
        if route is None:
            return None
        return route.get(name)

    def __getitem__(self, key):
        return self.get(key)

    def error(self, message):
        if self.log is not None:
            self.log.error(message, level=4)

    def info(self, message):
        if self.log is not None:
            self.log.info(message, level=4)

    def warning(self, message):
        if self.log is not None:
            self.log.warning(message, level=4)

    def send_mail(self, mail_config, parameters_list, db, sender=None):
        # Configuration
        main_mail_config = self.get_config(["mails"])
        config = self.get_config(["mails", "configurations", mail_config])
        if config is None or type(config) != dict:
            self.log.error('Missing "%s" mail configuration in "%s"' %
                           (config, self.config_path))
            return False

        # Parameters
        root_config = copy.copy(main_mail_config["parameters"])
        for key, parameter in main_mail_config["parameters"].items():
            root_config[key] = parameter

        # Sender
        if sender is None:
            if "sender" in config:
                sender = config["sender"]
            elif "sender" in main_mail_config:
                sender = main_mail_config["sender"]
            elif "sender" in main_mail_config["parameters"]:
                sender = main_mail_config["parameters"]["sender"]
            else:
                self.set_error("sender_error")
                return False

        full_parameters_list = []
        for parameters in parameters_list:
            # root_configuration          = copy.deepcopy(self.get_config())

            parameters_config = {}
            if "parameters" in config:
                parameters_config = copy.deepcopy(config["parameters"])

            full_parameters = {"title": config["title"]}

            _utils.fill_config(parameters_config,
                               source_configuration=parameters)
            _utils.fill_config(root_config, source_configuration=parameters)
            _utils.fill_config(root_config,
                               source_configuration=parameters_config)
            _utils.fill_config(parameters_config,
                               source_configuration=root_config)
            _utils.fill_config(parameters,
                               source_configuration=parameters_config)
            _utils.fill_config(parameters, source_configuration=root_config)

            _utils.merge_configuration(full_parameters,
                                       source_configuration=root_config,
                                       replace=True)
            _utils.merge_configuration(full_parameters,
                                       source_configuration=parameters_config,
                                       replace=True)
            _utils.merge_configuration(full_parameters,
                                       source_configuration=parameters,
                                       replace=True)

            full_parameters_list.append(full_parameters)

        mail_lib.KEY_SIGNATURE = (self.get_config("mails/key_signature"), )
        valid = mail_lib.send_mail(
            mail_path=self.get_config("mails/path"),
            mail_type=config["mail_type"],
            parameters_list=full_parameters_list,
            sender=sender,
            db=db,
            log=self.log,
        )
        if not valid:
            self.set_error("mail_error")
        return valid

    def get_current_route(self) -> Route:
        """Return the current route.

        Returns:
            Route: [description]
        """
        request_uuid = self.get_uuid()

        if request_uuid in self.routes_objects:
            return self.routes_objects[request_uuid]

        default_route = Route(request_uuid, request.full_path, [])
        if request_uuid not in self.routes_objects:
            self.log.critical("Cannot get route for %s" % request_uuid,
                              monitor="DB")
            return default_route

        self.log.critical("Issue with route %s" % request_uuid, monitor="DB")
        return default_route

    def get_path(self):
        return self.get_current_route().route

    def check_is_admin(self) -> bool:
        """Check if user is an admin or not.

        Args:
            log ([type], optional): [description]. Defaults to None.

        Returns:
            bool: [description]
        """
        route = self.get_current_route()

        user_data = _utils.get_logged_user()
        if user_data is not None:
            if user_data["role"] >= 9:
                return True
            else:
                self.warning("Wrong permission: %s is not an admin" %
                             user_data)

        admin_password = self.conf.get("admin_password")
        if self["admin"] and admin_password is not None:
            if secure_lib.check_magic_code(self["admin"], admin_password):
                return True

        ip = request.remote_addr
        admins_ips = self.conf.get("admins")
        if admins_ips and (ip in admins_ips or "::ffff:%s" % ip in admins_ips):
            return True
        else:
            self.warning("Wrong permission: %s is not an admin" % ip)
        return False

    def get_logged_user(self):
        return _utils.get_logged_user()

    def is_get(self):
        return request.method == "GET"

    def is_post(self):
        return request.method == "POST"

    def is_put(self):
        return request.method == "PUT"

    def is_delete(self):
        return request.method == "DELETE"

    def is_patch(self):
        return request.method == "PATCH"

    def get_method(self):
        return request.method
コード例 #22
0
ファイル: __init__.py プロジェクト: Manis99803/SmartKart
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_login import LoginManager

app = Flask(__name__)
app.config['SECRET_KEY'] = 'c3209OIOPP901QOU8c2u'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)
login = LoginManager(app)

from .models import (User, Shipper, Stock, Supplier, Order, OrderList, Product,
                     Shipment, Rating, Cart, Electronics, Clothes, Books)

admin = Admin(app, name='Smart Kart', template_mode='bootstrap3')
admin.add_views(ModelView(User, db.session), ModelView(Supplier, db.session),
                ModelView(Order, db.session), ModelView(OrderList, db.session),
                ModelView(Product, db.session), ModelView(Shipper, db.session),
                ModelView(Shipment, db.session), ModelView(Stock, db.session),
                ModelView(Rating, db.session), ModelView(Cart, db.session),
                ModelView(Electronics, db.session),
                ModelView(Clothes, db.session), ModelView(Books, db.session))

from app import views
コード例 #23
0
from flask_admin import Admin
from {{cookiecutter.project_core_dir}}.admin.views import get_views

admin = Admin(name='{{cookiecutter.project_name}} Admin', template_mode='bootstrap3')
admin.add_views(*get_views())
コード例 #24
0
    _populate_table_files(Software)

    # Create an Admin user
    if app.config['CREATE_ADMIN']:
        user, exists = db_insert_or_get(User,
                                        name='admin',
                                        defaults={'password': '******'},
                                        admin=True)
        db.session.commit()

    # Creates empty folders for use if they don't exist
    if app.config['CREATE_DIRECTORIES']:
        for folder in (os.path.join(app.config['PROJECT_FOLDER'], 'tmp', 'uploads'), \
                       os.path.join(app.config['PROJECT_FOLDER'], 'static', 'db')):
            try:
                os.makedirs(folder)
            except OSError as xcpt:
                pass

    # Add DB views
    admin = Admin(index_view=AdminHomeView(), template_mode='bootstrap3')
    admin.add_views(
        SessionModelView(User, db.session), SessionModelView(File, db.session),
        SessionModelView(Task, db.session),
        SessionModelView(Software, db.session),
        SessionModelView(Status, db.session, column_list=('id', 'name')))
    admin.init_app(app)

    # Start the server
    app.run(host=app.config['DEVICE_HOST'], port=app.config['DEVICE_PORT'])
コード例 #25
0
ファイル: web.py プロジェクト: bng-tv/playwithme
from flask import Flask, render_template
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView
from flask_bootstrap import Bootstrap
from sqlalchemy import func

from playwithme.config import WEB_SECRET, IRC_CHAN, WEB_TITLE, WEB_ADMIN
from playwithme.model import StorageModel, session

web = Flask(__name__)
web.config['SECRET_KEY'] = WEB_SECRET
Bootstrap(web)

if WEB_ADMIN:
    admin = Admin(web)
    admin.add_views(ModelView(StorageModel, session()))


@web.route("/")
def index():
    title = "{}: {}".format(WEB_TITLE, IRC_CHAN)
    print(web.template_folder)
    ses = session()

    ids = [x[0] for x in ses.query(func.max(StorageModel.id)).group_by(StorageModel.twitch, StorageModel.game).all()]
    ids.sort()
    data = ses.query(StorageModel).filter(StorageModel.id.in_(ids)).all()

    return render_template('table.html', data=data, title=title)
コード例 #26
0
from model_schema import ma


app = Flask(__name__)
app.config.from_object(Config)

db.init_app(app)
with app.app_context():
    db.create_all()

ma.init_app(app)

admin = Admin(template_mode='bootstrap3')
admin.add_views(
    ModelView(GiftCode, db.session, name="gift_code", endpoint="gift_code_admin"),
    ModelView(Product, db.session, name="product", endpoint="product_admin"),
    ModelView(Settlement, db.session, name="settlement", endpoint="settlement_admin"),
    ModelView(Transition, db.session, name="transition", endpoint="transition_admin"),
)
admin.init_app(app)

app.register_blueprint(gift_code_bp, url_prefix='/api/v1')
app.register_blueprint(settlement_bp, url_prefix='/api/v1')
app.register_blueprint(transition_bp, url_prefix='/api/v1')
app.register_blueprint(product_bp, url_prefix='/api/v1')


if __name__ == '__main__':
    app.run(
        app.config['HOST'],
        app.config['PORT'],
        app.config['DEBUG']
コード例 #27
0
ファイル: routes.py プロジェクト: ashokcse135/DLMS
from flask import render_template, url_for, flash, redirect
from DLMS import app
from DLMS.models import *
from flask_admin import Admin
from flask_admin.contrib.sqla import ModelView


admin=Admin(app)
admin.add_view(ModelView(Librarian_t1,db.session))
admin.add_views(ModelView(Librarian_t2,db.session))


@app.route('/')
@app.route('/home')
def home():
    return  render_template('home.html')

@app.route('/404.html')
def error():
    return  render_template('404.html')

@app.route('/blank.html')
def blank():
    return  render_template('blank.html')

@app.route('/buttons.html')
def buttons():
    return  render_template('buttons.html')

@app.route('/cards.html')
def cards():
コード例 #28
0
ファイル: __init__.py プロジェクト: lambsteak/faction-master
db = SQLAlchemy(app)

from .models import (
    Player, Question, Option, Weight, Faction, Schedule, Log, Answer,
    Avatar
)

admin = Admin(app, name='Faction Master', template_mode='bootstrap3',
              url='/admin123gh1g2hvh12gvh312us1jsc1j2sj12sf3t2f1stf3y123')
admin.add_view(ModelView(Player, db.session))
admin.add_view(ModelView(Question, db.session))
admin.add_views(
    ModelView(Option, db.session),
    ModelView(Weight, db.session),
    ModelView(Faction, db.session),
    ModelView(Schedule, db.session),
    ModelView(Log, db.session),
    ModelView(Answer, db.session),
    ModelView(Avatar, db.session),

)


from celery import Celery

def make_celery(app):
    celery = Celery(app.import_name,
                    broker=app.config['CELERY_BROKER_URL'])
    celery.conf.update(app.config)
    TaskBase = celery.Task
    class ContextTask(TaskBase):
        abstract = True
コード例 #29
0
ファイル: app.py プロジェクト: AlekseiiKanaiev/olc-project
        return redirect(url_for("security.login", next=request.url))


class AdminView(AdminMixin, ModelView):
    pass


class HomeAdminView(AdminMixin, AdminIndexView):
    pass


class MainView(ModelView):
    def is_accessible(self):
        return  current_user.has_role("admin") or\
                current_user.has_role('main')

    def inaccessible_callback(self, name, **kwargs):
        return redirect(url_for("security.login", next=request.url))


admin = Admin(app, "Home", url="/", index_view=HomeAdminView('Home'))
admin.add_views(AdminView(Video, db.session), AdminView(VideoTags, db.session),
                AdminView(Services, db.session),
                AdminView(ServTypes, db.session))
admin.add_views(MainView(Users, db.session), MainView(Roles, db.session))

### Flask-Security ###

user_datastore = SQLAlchemyUserDatastore(db, Users, Roles)
security = Security(app, user_datastore)
コード例 #30
0

class UserView(MyModelView):
    column_exclude_list = ['password_hash', ]


class TaskView(MyModelView):
    pass


class RoomView(MyModelView):
    pass


load_dotenv()

admin = Admin(
    name='任务导向对话系统· 管理界面',
    template_mode='bootstrap3',
    index_view=MyIndexView()
)

admin.add_views(
    UserView(User),
    TaskView(Task),
    RoomView(Room)
)

results_dir = os.path.join(os.path.dirname(__file__), 'results')
admin.add_view(MyFileAdmin(results_dir, name='Result Files'))