Exemplo n.º 1
0
def create_app(config_name):

    app = flask.Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    db.init_app(app)

    from .models import User, Article, Comment
    admin = Admin(app, name='personal', template_mode='bootstrap3')

    class ArticleView(ModelView):
        form_excluded_columns = ['slug']

    admin.add_view(ModelView(User))
    admin.add_view(ArticleView(Article))
    admin.add_view(ModelView(Comment))

    from .api import api_bp as api_blueprint
    app.register_blueprint(api_blueprint)
    apis.init_app(app)

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

    return app
Exemplo n.º 2
0
def initializeAdmin(app):
    admin = Admin(app, name='fuudzie', template_mode='bootstrap3')
    admin.add_view(ModelView(Users))
    admin.add_view(VendorView(Vendors))
    admin.add_view(ModelView(Carts))
    admin.add_view(MealView(Meals))
    admin.add_view(OrderView(Orders))
    admin.add_view(ModelView(Wallets))
Exemplo n.º 3
0
def init(app):
    # Create admin
    admin = flask_admin.Admin(app,
                              'C4E-Portfolio',
                              index_view=AdminIndexView())

    # Add views
    admin.add_view(ModelView(Project))
    admin.add_view(UserView(User))
    admin.add_view(ModelView(Tag))
Exemplo n.º 4
0
def register_debug_extensions(app):
  from flask_debugtoolbar import DebugToolbarExtension
  toolbar = DebugToolbarExtension()
  toolbar.init_app(app)

  from flask_admin.contrib.mongoengine import ModelView
  import flask_admin as admin
  admin = admin.Admin(app, 'TimeTracker:Admin')

  # Add views
  from models import User, Role
  admin.add_view(ModelView(User))
  admin.add_view(ModelView(Role))
Exemplo n.º 5
0
def register_extensions(app):
    db.init_app(app)
    login_manager.init_app(app)
    login_manager.login_view = 'auth.login'

    @login_manager.user_loader
    def load_user(user_id):
        return User.objects(id=user_id).first()

    admin.init_app(app)
    admin.add_view(ModelView(Role))
Exemplo n.º 6
0
def register_extensions(app):
    """Register models."""
    db.init_app(app)
    login_manager.init_app(app)

    # flask-admin configs
    admin.init_app(app)
    admin.add_view(ModelView(User))
    admin.add_view(ModelView(Role))

    login_manager.login_view = 'auth.login'

    @login_manager.user_loader
    def load_user(user_id):
        return User.objects(id=user_id).first()

    # jwt config
    def jwt_authenticate(username, password):
        logging.info("username:{}\npassword:{}\n".format(username, password))
        user = User.objects(name=username, password=password).first()
        return user

    def jwt_identity(payload):
        logging.info("payload:{}".format(payload))
        user_id = payload['identity']
        return User.objects(id=user_id).first()

    def make_payload(identity):
        iat = datetime.utcnow()
        exp = iat + current_app.config.get('JWT_EXPIRATION_DELTA')
        nbf = iat + current_app.config.get('JWT_NOT_BEFORE_DELTA')
        identity = str(identity.id)
        return {'exp': exp, 'iat': iat, 'nbf': nbf, 'identity': identity}

    jwt.authentication_handler(jwt_authenticate)
    jwt.identity_handler(jwt_identity)
    jwt.jwt_payload_handler(make_payload)

    jwt.init_app(app)
Exemplo n.º 7
0
from common.constants import Ports
from core.app import App
from importlib import reload

from models.vcb_card import VCBBank
from vietcombank_app import settings

reload(sys)
mail = Mail()

app = App(__name__, template_folder='./vpbank_app/templates', static_folder='./webapp/static')

app.config.from_object(settings)
db = MongoEngine(app)

app.auto_add_template_filters()

admin = Admin(app, template_mode='bootstrap3')
admin.add_view(ModelView(VCBBank, endpoint='Manage VCBBank'))

mail.init_app(app)

from vpbank_app.views import home, api

app.register_blueprint(home.module)
app.register_blueprint(api.module)

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=Ports.VPB_BANK)
Exemplo n.º 8
0
def create_app(extra_config_settings={}):
    # Create a Flask applicaction.

    # Instantiate Flask
    app = Flask(__name__)

    # Load App Config settings
    # Load common settings from 'app/settings.py' file
    app.config.from_object('app.settings')
    # Load local settings from 'app/local_settings.py'
    app.config.from_object('app.local_settings')
    # Load extra config settings from 'extra_config_settings' param
    app.config.update(extra_config_settings)

    # Setup db Mongo
    db.init_app(app)

    # Setup Flask-Mail
    #mail.init_app(app)

    # Setup WTForms CSRFProtect
    csrf_protect.init_app(app)

    # Register blueprints
    from app.views.public_views import public_blueprint
    app.register_blueprint(public_blueprint)
    from app.views.success import members_blueprint
    app.register_blueprint(members_blueprint)
    from app.views.admin_views import admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')
    from app.views.mod_views import mod_blueprint
    app.register_blueprint(mod_blueprint, url_prefix='/mod')
    from app.views.biz_views import biz_blueprint
    app.register_blueprint(biz_blueprint, url_prefix='/biz')
    # Setup an error-logger to send emails to app.config.ADMINS
    #init_email_error_handler(app)

    # Setup Flask-secure
    from .models.user_models import Role, User
    app.user_datastore = MongoEngineUserDatastore(db, User, Role)
    security.init_app(app, app.user_datastore, register_form=registerForm)
    # datastore.create_user(email='*****@*****.**', password='******')

    babel.init_app(app)  # Initialize flask_babelex

    # Setup Flask-admin
    class AdminUserView(ModelView):
        can_create = False
        column_exclude_list = ('password')
        column_editable_list = ['active']

        def is_accessible(self):
            return current_user.has_role('admin')

    adminDash = Admin(
        app,
        name='admin',
        template_mode='bootstrap4',
        url="/admin",
        endpoint='admin'
    )  #, index_view=adminView(url='/admin', endpoint='admin'))
    adminDash.add_view(AdminUserView(User))
    adminDash.add_view(ModelView(Role))
    path = op.join(op.dirname(__file__), './')
    adminDash.add_view(FileAdmin(path, '/', name='Files'))
    adminDash.add_link(MenuLink(name='Profile',
                                endpoint='members.member_page'))
    adminDash.add_link(MenuLink(name='Logout', endpoint='security.logout'))
    return app
Exemplo n.º 9
0
servrpc = Flask(__name__)
jsonrpc = JSONRPC(servrpc, '/api')

servrpc.config['SECRET_KEY'] = '12345667'
servrpc.config['SECURITY_PASSWORD_HASH'] = 'plaintext'
servrpc.config['SECURITY_PASSWORD_SALT'] = 'salt'

con = connect(
    host="mongodb+srv://filip:R6$h6g#NPZjzT&[email protected]/" +
    "test?retryWrites=true&w=majority")

user_datastore = MongoEngineUserDatastore(con, User, Role)
security = Security(servrpc, user_datastore)

admin = Admin(servrpc, index_view=MyView())
admin.add_view(ModelView(RpcData))
admin.add_view(ModelView(User))


def create_data(request, res):
    req = RpcData(md_method=str(request.json['method']),
                  md_params=str(request.json['params']),
                  md_result=res)
    req.save()


@jsonrpc.method('Servrpc.hello')
def hello(name):
    res = f'Hi {name},welcome to Flask JSON-RPC'
    create_data(request, res)
    return res
Exemplo n.º 10
0
admin = Admin(app, name='wiki admin', template_mode='bootstrap3')

class User(Document):
    user_name = StringField(max_length=50)
    email = StringField(required=True, max_length=50)
    userpw = StringField(max_length=50)
 
class Article(Document):
    author = StringField(max_length=30, required=True)
    title = StringField(max_length=120, required=True)
    content = StringField(required=True)
    tags = ListField(StringField(max_length=30))
    date = DateTimeField(default=datetime.datetime.now)

    
admin.add_view(ModelView(User))
admin.add_view(ModelView(Article))

@app.route('/')
@app.route('/index/')
def index():
    return render_template('index.html',
                            title='Home',
                            articles=Article.objects)

@app.route('/wiki_page')
def wiki_page():
    return render_template('wiki_page.html',
                           title='Wiki page',
                           articles=Article.objects)
Exemplo n.º 11
0
from models.user import User
from models.user_group import UserGroup
from models.vpb_card import VPBBank

reload(sys)
mail = Mail()

app = App(__name__, template_folder='./webapp/templates', static_folder='./webapp/static')
app.config.from_object(settings)
db = MongoEngine(app)
mail.init_app(app)

toolbar = DebugToolbarExtension(app)

admin = Admin(app, template_mode='bootstrap3')
admin.add_view(ModelView(User, endpoint='Manage User'))
admin.add_view(ModelView(Product, endpoint='Manage Product'))
admin.add_view(ModelView(UserGroup, endpoint='User Group'))
admin.add_view(ModelView(VCBBank, endpoint='VCB Cards'))
admin.add_view(ModelView(VPBBank, endpoint='VPB Cards'))
admin.add_view(ModelView(CertificateKey, endpoint='Certificate Key'))

app.auto_register_blueprint()

app.before_request(create_or_update_session)
app.after_request(set_session_cookie)

app.auto_add_template_filters()

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=Ports.MERCHANT, ssl_context=('cert.pem', 'key.pem'))
Exemplo n.º 12
0
from flask_admin import Admin
from flask_admin.contrib.mongoengine import ModelView

from web_notifier.models import Url, Item

admin = Admin(name='Notifier Admin', template_mode='bootstrap3')
admin.add_view(ModelView(Url))
admin.add_view(ModelView(Item))
Exemplo n.º 13
0
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'


class JobView(ModelView):
    # form_columns = ('job_id', 'name', 'events', 'new_file')
    form_excluded_columns = ['status', 'complete', 'batches', 'started', 'start_time', 'job_id']
    column_ajax_refs = {
        'batches': {
            'fields': ['batch_id']
        }
    }
    # column_searchable_list = ['job_id']
    can_export = True

    @action('start', 'Start', 'Are you sure you want to start?')
    def action_start(self, ids):
        for id in ids:
            job = Job.objects.get(pk=id)
            if not job.started:
                job.start()

    @action('check', 'Check Complete', 'Are you sure you want to run checks?')
    def action_check(self, ids):
        for id in ids:
            job = Job.objects.get(pk=id)
            job.check_complete()

admin.add_view(JobView(Job, name='Jobs'))
admin.add_view(ModelView(Batch, name='Batches'))
Exemplo n.º 14
0
                        'name': {
                            'style': 'color: red'
                        }
                    }
                }
            }
        }
    }


# Flask views
@app.route('/')
def index():
    return '<a href="/admin/">Click me to get to Admin!</a>'


if __name__ == '__main__':
    # Create admin
    admin = admin.Admin(app, 'Example: MongoEngine')

    # Add views
    admin.add_view(UserView(User))
    admin.add_view(TodoView(Todo))
    admin.add_view(ModelView(Tag))
    admin.add_view(PostView(Post))
    admin.add_view(ModelView(File))
    admin.add_view(ModelView(Image))

    # Start app
    app.run(debug=True)
Exemplo n.º 15
0
from flask_admin import Admin, AdminIndexView, expose
from flask_admin.contrib.mongoengine import ModelView
from app import app, redirect, session
from models import User, Category, Order, Meal


class MyAdminIndexView(AdminIndexView):
    @expose('/')
    def index(self):
        if 'role' in session and session['role'] == 'admin':
            return super(MyAdminIndexView, self).index()
        return redirect('/')


admin = Admin(app, url='/', index_view=MyAdminIndexView())
admin.add_view(ModelView(User))
admin.add_view(ModelView(Category))
admin.add_view(ModelView(Order))
admin.add_view(ModelView(Meal))
Exemplo n.º 16
0
import xlrd
from flask_admin import Admin
from mongoengine import *
from flask_mongoengine import MongoEngine
from flask_admin.contrib.mongoengine import ModelView
from models import AromaCompound, Ingredient, IngredientForm, CookingStyle, TasteCompound, IngredientCompoundRelation

app = Flask(__name__)
app.secret_key = "super secret key"
app.config['MONGODB_SETTINGS'] = {
    'db': 'dishq',
    'host': 'mongodb://127.0.0.1:27017/dishq'
}
admin = Admin(app, name='inground', template_mode='bootstrap3')
db = connect('dishq')
admin.add_view(ModelView(AromaCompound))
admin.add_view(ModelView(Ingredient))
admin.add_view(ModelView(IngredientForm))
admin.add_view(ModelView(CookingStyle))
admin.add_view(ModelView(TasteCompound))
admin.add_view(ModelView(IngredientCompoundRelation))


@app.route('/')
def initialize():
    dishq_data_book = xlrd.open_workbook('ingredientforms.xlsx')
    ingredient_sheet = dishq_data_book.sheet_by_index(0)
    for i in range(1, 57):
        ingredient = IngredientForm(
            ingredient_form_id=str(ingredient_sheet.cell(i, 0).value),
            ingredient_form_name=str(ingredient_sheet.cell(i, 1).value))
Exemplo n.º 17
0
def init_admin(app=None):
    app = app or create_app()
    admin = Admin(app, name='user_center', template_mode='bootstrap3')
    admin.add_view(ModelView(User))
    admin.add_view(ModelView(TokenBlacklist))
Exemplo n.º 18
0
from flask_babelex import Babel
from admin import admin, MyModelView, AdminUser, login, limiter
from flask_admin.contrib.mongoengine import ModelView
from homework.view import ActModelView, StudentModelView
from wechat.view import OauthModelView
from production import *
from rsync_tasks import celery, redis
try:
    from local_settings import *
except Exception:
    pass

blueprints = ['routes:uploadApi']

admin.add_view(StudentModelView(name="APP合作"))
admin.add_view(ModelView(Consultation, name="官网首页"))
admin.add_view(ModelView(ClassInfo, name="学生预约课"))
admin.add_view(ActModelView(name="作业帮活动"))
admin.add_view(OauthModelView(name="微信多平台"))
admin.add_view(ModelView(Operation, name="访客记录"))


# 初始化app
def create_app(config_name):
    app = Flask(config_name)
    app.config.from_object(config[config_name])

    # 全局响应头
    @app.after_request
    def after_request(response):
        if "Access-Control-Allow-Origin" not in response.headers.keys():
Exemplo n.º 19
0
from flask_admin.contrib.mongoengine import ModelView
from resources import Recommend
from models import db, SearchMovie
import config

app = Flask(__name__)
api = Api(app)

app.config['SECRET_KEY'] = 'seeecccreet'
app.config['UPLOAD_FOLDER'] = config.UPLOAD_FOLDER

#db
app.config['MONGODB_HOST'] = 'mongodbhost'
app.config['MONGODB_PORT'] = 27017
app.config['MONGODB_DB'] = 'admin'
app.config['MONGODB_USERNAME'] = '******'
app.config['MONGODB_PASSWORD'] = '******'

db.init_app(app)
app.session_interface = MongoEngineSessionInterface(db)

# admin
admin = Admin(app)
admin.add_view(ModelView(SearchMovie))

#endpoints
api.add_resource(Recommend, '/recommend')

if __name__ == "__main__":
    app.run(host=config.HOST, port=config.HOST, debug=config.DEBUG)
Exemplo n.º 20
0
def create_app(extra_config_settings={}):
    # Create a Flask applicaction.

    # Instantiate Flask
    app = Flask(__name__)

    # Load App Config settings
    # Load common settings from 'app/settings.py' file
    app.config.from_object('app.settings')
    # Load local settings from 'app/local_settings.py'
    app.config.from_object('app.local_settings')
    # Load extra config settings from 'extra_config_settings' param
    app.config.update(extra_config_settings)

    # Setup db Mongo
    db.init_app(app)

    # Setup Flask-Mail
    mail.init_app(app)

    # Setup WTForms CSRFProtect
    csrf_protect.init_app(app)

    # Register blueprints
    from app.views.public_views import public_blueprint
    app.register_blueprint(public_blueprint)
    from app.views.members_views import members_blueprint
    app.register_blueprint(members_blueprint)

    # Setup an error-logger to send emails to app.config.ADMINS
    init_email_error_handler(app)

    # Setup Flask-secure
    from .models.user_models import User, Role
    app.user_datastore = MongoEngineUserDatastore(db, User, Role)
    security.init_app(app, app.user_datastore)
    # datastore.create_user(email='*****@*****.**', password='******')

    Bootstrap(app)  # Initialize flask_bootstrap

    babel.init_app(app)  # Initialize flask_babelex

    # Define bootstrap_is_hidden_field for flask-bootstrap's bootstrap_wtf.html
    from wtforms.fields import HiddenField

    def is_hidden_field_filter(field):
        return isinstance(field, HiddenField)

    app.jinja_env.globals['bootstrap_is_hidden_field'] = is_hidden_field_filter

    # Setup Flask-admin
    class AdminUserView(ModelView):
        can_create = False
        column_exclude_list = ('password')
        form_overrides = dict(password=HiddenField)

    admin = Admin(app, template_mode='bootstrap3')
    admin.add_view(AdminUserView(User))
    admin.add_view(ModelView(Role))
    path = op.join(op.dirname(__file__), 'static')
    admin.add_view(FileAdmin(path, '/static/', name='Files'))
    admin.add_link(MenuLink(name='Profile', endpoint='members.member_page'))
    admin.add_link(MenuLink(name='Logout', endpoint='security.logout'))

    return app
Exemplo n.º 21
0

#/..........................................................................


@flask_app.route("/home")
def home2():
    username = request.args.get('username')
    session_id = request.args.get('session_id')
    return render_template('home.html',
                           username=username,
                           session_id=session_id)


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


@flask_app.route('/index')
def index():
    return render_template("z.html")


admin = Admin(flask_app)
admin.add_view(ModelView(Users))
admin.add_view(ModelView(Chats))

if __name__ == '__main__':
    socketio.run(flask_app, debug=True, host='0.0.0.0', port=5006)
Exemplo n.º 22
0
from filters import my_strftime
from werkzeug.exceptions import HTTPException


class AuthException(HTTPException):
    def __init__(self, message):
        super().__init__(
            message,
            Response(
                "You could not be authenticated. Please refresh the page.",
                401, {'WWW-Authenticate': 'Basic realm="Login Required"'}))


class ModelView(ModelView):
    def is_accessible(self):
        if not basic_auth.authenticate():
            raise AuthException('Not authenticated.')
        else:
            return True

    def inaccessible_callback(self, name, **kwargs):
        return redirect(basic_auth.challenge())


admin.add_view(ModelView(User, 'Пользователи'))

app.register_blueprint(gallery, url_prefix='')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)
Exemplo n.º 23
0
    return 'Helloo'


@app.route('/admin')
def admin_index():
    return '<a href="/admin/">Click me to get to Admin!</a>'


if __name__ == '__main__':
    # Create admin
    admin = Admin(app, 'Ephoenix Admin')

    # Add views
    admin.add_view(UserView(User))

    admin.add_view(ModelView(File))
    # admin.add_view(ModelView(Image))
    admin.add_view(ReportsView(name='Reports', endpoint='reports'))
    admin.add_view(NotificationsView(
        name='Notifications', endpoint='notifications'))

    # @app.route('/login')
    # def login():
    #     # if current_user.is_authenticated:
    #     #     user = User.objects(name='Aronique')
    #     #     print(user)
    #     #     # login_user(user)
    #     return redirect(url_for('admin.index'))
    #     # return None

    # @app.route('/logout')