Пример #1
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(Config)

    db_session = init_db(app)

    scheduler = BackgroundScheduler()
    scheduler.start()
    scheduler.add_job(processing_timeout, 'interval', seconds=60)
    scheduler.add_job(old_files_removals, 'interval', hours=24)

    Path(app.config['PROCESSED_REQUESTS_FOLDER']).mkdir(parents=True,
                                                        exist_ok=True)
    Path(app.config['MODELS_FOLDER']).mkdir(parents=True, exist_ok=True)
    Path(app.config['UPLOAD_IMAGES_FOLDER']).mkdir(parents=True, exist_ok=True)

    Bootstrap(app)
    Dropzone(app)

    notification = db_session.query(Notification).first()
    if notification is not None:
        notification.last_notification = datetime.datetime(1970, 1, 1)
    else:
        notification = Notification(datetime.datetime(1970, 1, 1))
        db_session.add(notification)

    db_session.commit()

    jsglue = JSGlue()
    jsglue.init_app(app)

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

    return app
Пример #2
0
def create_app() -> Flask:
    """
    Factory pour la création de l'application Flask
    :return: L'application flask créé
    """
    # Ici on peut rajouter une initialisation de la configuration par un fichier json,
    # Si l'on en veut un autre que celui par defaut
    # config_app.init_from_json_file(json_file)

    configuration_flask = ConfigurationFlask()

    current_app = Flask(__name__,
                        static_folder=web_static_dir + '/',
                        template_folder=web_templates_dir + '/')

    current_app.config.from_object(configuration_flask)

    current_app.app_context().push()  # this does the binding

    blueprint_registrations(current_app)

    # So we can upload files
    # We need to do
    secret = secrets.token_urlsafe(32)
    current_app.secret_key = secret

    # Imperatif de faire l'init_db() après l'initialisation par le fichier de configuration
    # si l'on veut des valeurs autre que celles par défaut
    init_db()

    jsglue = JSGlue()
    jsglue.init_app(current_app)
    return current_app
Пример #3
0
def create_app(test_config=None, SECRET_KEY='dev', instance_path=''):
    # create and configure the app
    if not instance_path:
        app = Flask(__name__, instance_relative_config=True)
    else:
        app = Flask(__name__, instance_path=instance_path)
    app.config.from_mapping(
        SECRET_KEY=SECRET_KEY,
        DATABASE=os.path.join(app.instance_path, 'demosaurus.sqlite'),
    )
    jsglue = JSGlue()
    jsglue.init_app(app)

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    from . import db
    db.init_app(app)

    from . import publication
    app.register_blueprint(publication.bp)

    from . import link_thesaurus
    app.register_blueprint(link_thesaurus.bp)

    from . import subject_headings
    app.register_blueprint(subject_headings.bp)

    from . import contributor
    app.register_blueprint(contributor.bp)

    # a simple page that says hello
    @app.route('/hello')
    def hello():
        return 'Hello, World!'

    @app.route('/favicon.ico')
    def favicon():
        return send_from_directory(os.path.join(app.root_path, 'static'),
                                   'favicon.ico',
                                   mimetype='image/vnd.microsoft.icon')

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

    return app
Пример #4
0
def register_extensions(app):
    """Register Flask extensions."""
    assets.init_app(app)
    bcrypt.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    csrf_protect.init_app(app)
    login_manager.init_app(app)
    debug_toolbar.init_app(app)
    migrate.init_app(app, db)

    jsglue = JSGlue()
    jsglue.init_app(app)

    return None
Пример #5
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    app.config[
        'SQLALCHEMY_DATABASE_URI'] = 'mysql://*****:*****@knowledgebase2018.cd3pupo3w3sq.ap-southeast-1.rds.amazonaws.com/knowledgebase'

    db.init_app(app)

    print("App created")
    csrf.init_app(app)
    from knowledge import knowledge as knowledge_blueprint

    # login_manager.session_protection = "strong"
    login_manager.init_app(app)
    login_manager.login_view = 'knowledge.login'

    app.register_blueprint(knowledge_blueprint)

    moment.init_app(app)
    misaka.init_app(app)

    bootstrap.init_app(app)

    jsglue = JSGlue(app)
    Markdown(app)

    return app
Пример #6
0
def create_app(test_config=None, debug=False):
    # create and configure the app
    app = Flask(__name__)
    app.debug = debug
    app.jinja_options = dict(autoescape=select_autoescape(default=True),
                             trim_blocks=True)
    app.config.from_mapping(
        SECRET_KEY='dev',
        DATABASE=os.path.join(app.root_path, 'database/database.sqlite'),
    )
    app.config['SECRET_KEY'] = 'ARTK'
    jsglue = JSGlue(app)

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    db.init_app(app)
    app.register_blueprint(home.bp)
    app.register_blueprint(packer.bp)
    app.register_blueprint(docs.bp, url_prefix='/docs')
    app.register_blueprint(node.bp, url_prefix='/node')
    app.register_blueprint(projects.bp, url_prefix='/projects')
    app.register_blueprint(editor.bp, url_prefix='/edit')

    socketio.init_app(app)
    messages.init_sockets(socketio)
    editor.init_sockets(socketio)

    return app
Пример #7
0
def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    pages = FlatPages(app)
    freezer = Freezer(app)
    jsglue = JSGlue(app)
    bootstrap.init_app(app)

    from app.core import bp as core_bp
    app.register_blueprint(core_bp)

    if not app.debug:
        if not os.path.exists('logs'):
            os.mkdir('logs')
        file_handler = RotatingFileHandler('logs/endless_farming.log', maxBytes=10240,
            backupCount=10)
        file_handler.setFormatter(logging.Formatter(
            '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)

        app.logger.setLevel(logging.INFO)
        app.logger.info('Endless farming startup')

    return app, freezer, pages
Пример #8
0
def _prepare_app():
    """
    Setup the initial APP values and initialize various flask plugins.

    :returns: flask app instance
    """
    # init JSGLUE. this is needed to query URLs in javascript
    _js_glue = JSGlue(APP)

    cfg_rdr = ConfigReader()

    APP.config['SECRET_KEY'] = cfg_rdr.get_attr('db_secret_key')
    APP.config['SQLALCHEMY_DATABASE_URI'] = cfg_rdr.get_attr('db_address')
    # needed because this functionality is already depricated
    APP.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

    # the salt is a workaround for a bug, as flask-security salts  passwords
    # automatically but somehow it requires and uses this config value which
    # breaks the login if the salt is individually unique (as a salt should be)
    APP.config['SECURITY_PASSWORD_SALT'] = 'fake_salt'
    APP.config['SECURITY_TRACKABLE'] = True
    APP.config['SECURITY_REGISTERABLE'] = True
    APP.config['SECURITY_CONFIRMABLE'] = False

    APP.config['UPLOAD_FOLDER'] = 'config'
    # max upload size is 50 KB
    APP.config['MAX_CONTENT_LENGTH'] = 50 * 1024

    path = os.path.join('.', os.path.dirname(__file__), 'static/js/sijax/')

    APP.config['SIJAX_STATIC_PATH'] = path
    APP.config['SIJAX_JSON_URI'] = '/static/js/sijax/json2.js'
    flask_sijax.Sijax(APP)

    APP.config['JWT_ALGORITHM'] = 'RS256'
    with open(cfg_rdr.get_attr('private_key_file_location'), 'rb') as file:
        APP.config['JWT_PRIVATE_KEY'] = file.read()
    JWT = JWTManager(APP)

    with APP.app_context():
        DB.init_app(APP)
        user_datastore = SQLAlchemyUserDatastore(DB, User, Role)
        _security = Security(APP, user_datastore)
        setup(user_datastore)
        rs256_token = create_access_token(str(current_user),
                                          expires_delta=False)

    APP.config['access_headers'] = {'Authorization': 'Bearer {}'
                                    .format(rs256_token)}
    JSONService.init(APP.config['access_headers'])

    return APP
Пример #9
0
    def setUp(self):
        self.app = Flask(__name__)
        self.jsglue = JSGlue(self.app)

        handler = lambda: "ok"
        self.app.add_url_rule('/', 'case0', handler)
        self.app.add_url_rule('/<a>', 'case1', handler)
        self.app.add_url_rule('/test/<a>', 'case2', handler)
        self.app.add_url_rule('/<int:a>/test', 'case3', handler)
        self.app.add_url_rule('/<int:a>/<int:b>', 'case4', handler)
        self.app.add_url_rule('/<a>/data', 'case5', handler)
        self.app.add_url_rule('/<b>/hello', 'case5', handler)
        self.app.add_url_rule('/<a>/data/<b>', 'case5', handler)

        self.client = self.app.test_client()
Пример #10
0
def create_app(config_name):
    # Create and initialize Flask app
    # config.py is locate with instance_relative_config
    app = Flask(__name__, instance_relative_config=True)
    app.config["SECRET_KEY"] = os.getenv(
        "SECRET_KEY") or "b'_5#y2LF4Q8znxec]/'"
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')
    Bootstrap(app)
    jsglue = JSGlue(app)

    from .home import home as home_blueprint
    app.register_blueprint(home_blueprint)

    return app
Пример #11
0
def create_app():
    app = Flask(__name__, instance_relative_config=True, static_folder=None)
    jsglue = JSGlue(app)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # if running development load dev config, else load from instance file
    if 'ENV' in app.config and app.config['ENV'] == 'development':
        from .dev import config as dev_config

        app.config.from_mapping(dev_config)
    else:
        app.config.from_pyfile('prod.cfg')

    # open db and stuff
    from . import db
    db.init_app(app)

    # expand context
    from .utils.login import context_processor as login_context_processor, is_logged_in
    app.context_processor(login_context_processor)

    # routes
    from .controllers import auth
    from .controllers import membership
    from .controllers import expenses
    from .controllers import debts
    app.register_blueprint(auth.router, url_prefix='/auth')
    app.register_blueprint(membership.router, url_prefix='/member')
    app.register_blueprint(expenses.router, url_prefix='/expenses')
    app.register_blueprint(debts.router, url_prefix='/debts')

    @app.route("/", methods=["GET"])
    def default():
        if not is_logged_in():
            return redirect(url_for('auth.ui_login'), code=302)
        else:
            return redirect(url_for('member.ui_home'), code=302)

    if 'ENV' in app.config and app.config['ENV'] == 'development':
        print('ENDPOINTS:')
        print(app.url_map)

    return app
Пример #12
0
def create_app(with_error=True, configfile=None):
    app = Flask(__name__)

    # Apply frameworks
    Bootstrap(app)
    JSGlue(app)
    HerokuConfig(app, configfile)

    # Register blueprints
    if with_error:
        app.register_blueprint(blueprints.err)
    app.register_blueprint(blueprints.api)
    app.register_blueprint(blueprints.frontend)
    app.register_blueprint(blueprints.frontend_user)
    app.register_blueprint(blueprints.dummy)
    app.register_blueprint(blueprints.static)

    # Configure app for flask-mail
    app.config['MAIL_SERVER'] = 'smtp.gmail.com'
    app.config['MAIL_PORT'] = 465
    app.config['MAIL_USERNAME'] = os.environ["GM_EMAIL"]
    app.config['MAIL_PASSWORD'] = os.environ["GM_PASSWORD"]
    app.config['MAIL_USE_TLS'] = False
    app.config['MAIL_USE_SSL'] = True
    app.config['MAIL_DEFAULT_SENDER'] = os.environ["GM_EMAIL"]

    # Set jinja cache to unlimited
    app.jinja_env.cache = {}

    # Generate secret key for forms
    app.secret_key = bytes(os.environ.get("SECRET_KEY"), encoding='utf-8')

    # Configure app to for bootstrap to not use CDN
    app.config["BOOTSTRAP_SERVE_LOCAL"] = True

    # Configure mail instance
    mail = Mail(app)
    app.config["MAIL_INSTANCE"] = mail

    # Append nav bar to app
    blueprints.nav.init_app(app)

    return app
Пример #13
0
def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__)

    if test_config is None:
        # load the instance config, if it exists, when not testing
        from .config import Config
        app.config.from_object(Config)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # init database
    db.init_app(app)

    # init flask-security
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security = Security(app, user_datastore)

    init_data(app)

    # cleanup any leftover containers, networks or files before starting or exiting
    atexit.register(cleanup, app=app)
    cleanup(app)

    # register blueprints
    register_blueprints(app)

    # init jsglue
    jsglue = JSGlue(app)

    return app
Пример #14
0
import re
from flask import Flask, jsonify, render_template, request, url_for
from flask_jsglue import JSGlue

from cs50 import SQL
from helpers import lookup

# configure application
app = Flask(__name__)
JSGlue(app)

# ensure responses aren't cached
if app.config["DEBUG"]:

    @app.after_request
    def after_request(response):
        response.headers[
            "Cache-Control"] = "no-cache, no-store, must-revalidate"
        response.headers["Expires"] = 0
        response.headers["Pragma"] = "no-cache"
        return response


# configure CS50 Library to use SQLite database
db = SQL("sqlite:///mashup.db")


@app.route("/")
def index():
    return render_template("index.html")
Пример #15
0
from boto.s3.connection import S3Connection
import dna_assembler

BASE_DIR = os.path.dirname(__file__)
UPLOAD_FOLDER = os.path.normpath(os.path.join(
    BASE_DIR, 'data/upload'))  # Local destination for storage of FASTQ files.
DOWNLOAD_FOLDER = os.path.normpath(os.path.join(
    BASE_DIR,
    'data/download'))  # Local destination for storage of FASTA files.
AWS_KEY = ""  # Must include AWS Key ID.
AWS_SECRET = ""  # Must include AWS Secret Key.
KEY_BASE_UPLOAD = "upload/"  # AWS S3 destination for storage of FASTQ files.
KEY_BASE_DOWNLOAD = "download/"  # AWS S3 destination for storage of FASTA files.

application = Flask(__name__)
jsglue = JSGlue(application)
application.config.from_object('config')  # Access data in config.py
application.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
application.config['DOWNLOAD_FOLDER'] = DOWNLOAD_FOLDER

#  ####### VIEWS #########
#  #######################


@application.route('/')
@application.route('/index')
def index():
    """
    Flask microframework root endpoint. Redirects navigation
    to the fileinput endpoint.
    """
Пример #16
0
    monkey.patch_all()


from flask import Flask, g, url_for, render_template, request, redirect, flash, session, abort, Markup
from oauth2client.client import flow_from_clientsecrets
import httplib2
import json
from apiclient.discovery import build
from flask_jsglue import JSGlue
from model.redis_model import RedisModel
import lib.common as common
from lib.mysocket import MySocket
from flask_socketio import join_room


jsglue = JSGlue()
app = Flask(__name__)
jsglue.init_app(app)
app.config.from_object('config.config')
app.config.from_envvar('PPOSTER_SETTINGS', silent=True)

model = RedisModel(app.config)
my_socket = MySocket(app, async_mode)
socketio = my_socket.get_socketio()
#socketio = SocketIO(app, async_mode=async_mode)
thread = None

RESERVED_ALIASES = ['login', 'register', 'google_auth', 'auth_return', 'logout', 'timelinejson', 'public', 'add_tweet', 're_tweet', 'remove_tweet', 'add_comment', 'notifications']


def is_reserved(alias):
Пример #17
0
 def setup_extention(self):
     jsglue = JSGlue(self.app)
Пример #18
0
from ontology.sdk import Ontology
from ontology.utils import utils
from ontology.wallet.wallet_manager import WalletManager
from werkzeug.utils import secure_filename

# ipfs_daemon = subprocess.Popen("ipfs daemon", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
static_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                             'static')
template_folder = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                               'templates')
app = Flask('IPAblum',
            static_folder=static_folder,
            template_folder=template_folder)
app.config.from_object('default_settings')
ImageFile.LOAD_TRUNCATED_IMAGES = True
jsglue = JSGlue()
jsglue.init_app(app)
default_identity_account = None
default_wallet_account = None

try:
    ipfs = ipfsapi.connect(app.config['IPFS_HOST'], app.config['IPFS_PORT'])
except Exception:
    print('Failed to establish a new connection to IPFS node...')
    exit(1)


def remove_file_if_exists(path):
    if os.path.isfile(path):
        os.remove(path)
        return True
Пример #19
0
# from sqlalchemy.orm import scoped_session, sessionmaker
from werkzeug.security import check_password_hash, generate_password_hash
from helpers import login_required
from flask_socketio import SocketIO, emit, join_room
from sqlalchemy.sql import func
from sqlalchemy import and_, or_
from flask_sqlalchemy import get_debug_queries

# Import table definitions
from models import *

"""Configure app"""
app = Flask(__name__)
# app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
socketio = SocketIO(app) # For chat
JSGlue(app) # For typeahead

# ensure responses aren't cached
if app.config["DEBUG"]:
    @app.after_request
    def after_request(response):
        response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
        response.headers["Expires"] = 0
        response.headers["Pragma"] = "no-cache"
        return response

# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
Пример #20
0
from flask import Flask, render_template, jsonify, url_for, request
from flask_jsglue import JSGlue
import random
from uuid import uuid1

app = Flask(__name__)
jsglue = JSGlue()
jsglue.init_app(app)  # 让js文件中可以使用url_for方法
results = []
chars = 'ABCDEFGHIJKLMNOPQRSTUVWSYZ'
results.append({'name': 'vue.js+flask+element-ui简易Demo', 'flag': 'true'})
results.append({
    'name': '代码请戳github',
    'flag': 'true',
    'url': 'https://github.com/qianbin01/Vue-flask'
})
for i in range(5):
    results.append({'name': random.choice(chars), 'index': str(uuid1())})


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


@app.route('/get_data')
def get_base_data():
    return jsonify({'results': results})


@app.route('/add', methods=['POST'])
Пример #21
0
from flask import Flask, request, render_template, redirect, jsonify, render_template_string
from flask_jsglue import JSGlue # this is use for url_for() working inside javascript which is help us to navigate the url
import util
import os
from werkzeug.utils import secure_filename

application = Flask(__name__)
application.debug = True

# JSGlue is use for url_for() working inside javascript which is help us to navigate the url
jsglue = JSGlue() # create a object of JsGlue
jsglue.init_app(application) # and assign the app as a init app to the instance of JsGlue

util.load_artifacts()
#home page
@application.route("/")
def home():
    return render_template("home.html")

#classify plant
@application.route("/classifyPlant", methods = ["POST"])
def classifyPlant():
    image_data = request.files["file"]
    #save the image to upload
    basepath = os.path.dirname(__file__)
    image_path = os.path.join(basepath, "uploads", secure_filename(image_data.filename))
    image_data.save(image_path)

    predicted_value, details = util.classify_plant(image_path)
    os.remove(image_path)
    return jsonify(predicted_value=predicted_value, details=render_template_string(details))
Пример #22
0
def create_app(debug=False):

    # -----------------------------
    # Create App
    # -----------------------------
    # instantiate the Flask app, __name__ tells Flask what belongs to the application
    app = Flask(__name__, static_url_path='/static')
    app.debug = debug

    # I make it so you can build URLs in javascript using Flask's url_for
    # rather than having to hardcode anything.
    # http://stewartjpark.com/Flask-JSGlue/
    jsglue = JSGlue(app)

    # -----------------------------------
    # Set up a Logger for your application
    # -----------------------------------
    # log = standard Pythong logging thing you create here -- then add it to the Flask handler
    # app.logger.addHandler(log)
    # use your logger with app.logger.info('this is info'), don't use print statements inside Flask

    # ----------------------------------
    # Load an appropriate Flask configuration file for a debug or production version
    # ----------------------------------
    if app.debug:
        server_config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'configuration', 'localhost.cfg')
    else:
        pass
        # Load a configuration file for a production version of your app!
        # server_config_file = /path/to/production/config/file

    # app.logger.info('Loading config file: {0}'.format(server_config_file))
    app.config.from_pyfile(server_config_file)

    # ----------------------------
    # Manually add any configuration parameters
    # ----------------------------
    app.config["UPLOAD_FOLDER"] = os.environ.get("MYAPP_DATA_DIR", None)

    # ----------------------------
    # Global Error Handlers
    # ----------------------------
    @app.errorhandler(404)
    def this_is_the_wrong_page(e):
        error = {}
        error['title'] = 'MyApp | Page Not Found'
        error['page'] = request.url
        return render_template('errors/page_not_found.html', **error), 404

    # ----------------------------------
    # Web Route Registration - Import and register all your blueprints here
    # ----------------------------------
    from myapp.controllers.index import index_page
    from myapp.controllers.examples import example_page

    url_prefix = '/myapp'  # I can prefix all routes with a name
    app.register_blueprint(index_page, url_prefix=url_prefix)
    app.register_blueprint(example_page, url_prefix=url_prefix)

    # Register all custom Jinja filters in the file.
    app.register_blueprint(jinjablue)

    return app
Пример #23
0
from flask import Flask, render_template, request

import test
from flask_jsglue import JSGlue
app = Flask(__name__)

jsglue = JSGlue()  ## Jquery 및 ajax 연동하기 위해 설정

app = Flask(__name__)
jsglue.init_app(app)


@app.route("/")
def index():
    print("시작 페이지 접속")
    return render_template('index.html')


#background process happening without any refreshing
@app.route('/background_process_test',
           methods=['GET', 'POST'])  ## html에서 감지하고 감지한 데이터로 UID만 가져오기
def background_process_test():
    print("러닝시작")
    if request.method == "POST":
        data = {}
        data = request.json['uid']
        if data == None:
            return render_template('index.html')
        uid = list(data.keys())[0]

    name = test.getdata(uid)  ## 파일 이름 가져오기
Пример #24
0
def create_app(config_name):
    global app
    global log

    #set up logging
    LOG_FILENAME = os.path.join(sys.path[0],
                                app_config[config_name].STATIC_PATH,
                                'log/rr-log.txt')
    try:
        log_level = getattr(logging, app_config[config_name].LOG_LEVEL)
    except:
        log_level = getattr(logging, 'INFO')
    log.setLevel(log_level)
    log.addFilter(MyLogFilter())
    log_handler = logging.handlers.RotatingFileHandler(LOG_FILENAME,
                                                       maxBytes=10 * 1024,
                                                       backupCount=5)
    log_formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(username)s - %(message)s')
    log_handler.setFormatter(log_formatter)
    log.addHandler(log_handler)

    log.info('start RR')

    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')

    app.jinja_env.filters['milliseconds_to_minutes_seconds'] = ms2m_s_ms

    Bootstrap(app)

    jsglue = JSGlue(app)
    db.app = app  # hack :-(
    db.init_app(app)
    excel.init_excel(app)

    app.url_map.converters['int'] = IntegerConverter

    random.seed()

    if not config.DB_TOOLS:
        login_manager.init_app(app)
        login_manager.login_message = 'Je moet aangemeld zijn om deze pagina te zien!'
        login_manager.login_view = 'auth.login'

        migrate = Migrate(app, db)

        from app import models

        #create_admin(db) # Only once

        #flask db migrate
        #flask db upgrade
        #uncheck when migrating database
        #return app

        from .auth import auth as auth_blueprint
        app.register_blueprint(auth_blueprint)

        from .settings import settings as settings_blueprint
        app.register_blueprint(settings_blueprint)

        from .user import user as user_blueprint
        app.register_blueprint(user_blueprint)

        from .registration import registration as registration_blueprint
        app.register_blueprint(registration_blueprint)

        @app.errorhandler(403)
        def forbidden(error):
            return render_template('errors/403.html', title='Forbidden'), 403

        @app.errorhandler(404)
        def page_not_found(error):
            return render_template('errors/404.html',
                                   title='Page Not Found'), 404

        @app.errorhandler(500)
        def internal_server_error(error):
            return render_template('errors/500.html',
                                   title='Server Error'), 500

        @app.route('/500')
        def error_500():
            abort(500)

    return app
Пример #25
0
scraper_dependencies = dict(get=requests.get,
                            BeautifulSoup=BeautifulSoup,
                            re=re)
scraper = ScheduleScraper(**scraper_dependencies)

settings['SECRET_KEY'] = os.environ.get('SECRET_KEY', helpers.get_salt(25))

app = Flask(__name__)

# required for datad url_for
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
app.static_path = STATIC_ROOT

jsglue = JSGlue(app)

app.jinja_env.add_extension('jinja2.ext.loopcontrols')
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
app.config['TEMPLATES_AUTO_RELOAD'] = True

app.config.update(
    {'SECRET_KEY': os.environ.get('SECRET_KEY', settings.get('SECRET_KEY'))})

if app.config["DEBUG"]:

    @app.after_request
    def after_request(response):
        response.headers["Cache-Control"] = ("no-cache, no-store," +
Пример #26
0
log.setLevel(log_level)
log.addFilter(MyLogFilter())
log_handler = logging.handlers.RotatingFileHandler(LOG_FILENAME,
                                                   maxBytes=10 * 1024,
                                                   backupCount=5)
log_formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(username)s - %(message)s')
log_handler.setFormatter(log_formatter)
log.addHandler(log_handler)

log.info('start SULCM')

flask_app.config.from_object(app_config[config_name])
flask_app.config.from_pyfile('config.py')

jsglue = JSGlue(flask_app)
db.app = flask_app  # hack:-(
db.init_app(flask_app)

socketio = SocketIO(
    flask_app,
    async_mode=flask_app.config['SOCKETIO_ASYNC_MODE'],
    ping_timeout=10,
    ping_interval=5,
    cors_allowed_origins=flask_app.config['SOCKETIO_CORS_ALLOWED_ORIGIN'])

flask_app.url_map.converters['int'] = IntegerConverter

login_manager.init_app(flask_app)
login_manager.login_message = 'Je moet aangemeld zijn om deze pagina te zien!'
login_manager.login_view = 'auth.login'
Пример #27
0
def create_app(config_name):
    global app
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')
    #    app.create_jinja_environment()
    #    app.jinja_options={'extensions':['jinja2.ext.i18n']}
    #    app.

    Bootstrap(app)

    jsglue = JSGlue(app)
    db.app = app  # hack :-(
    db.init_app(app)

    if not config.DB_TOOLS:
        login_manager.init_app(app)
        login_manager.login_message = 'You must be logged in to access this page'
        login_manager.login_view = 'auth.login'

        migrate = Migrate(app, db)

        from app import models

        #create_admin(db) # Only once

        #flask db migrate
        #flask db upgrade
        #uncheck when migrating database
        #return app

        from .admin import admin as admin_blueprint
        app.register_blueprint(admin_blueprint)

        from .auth import auth as auth_blueprint
        app.register_blueprint(auth_blueprint)

        from .user import user as user_blueprint
        app.register_blueprint(user_blueprint)

        from .asset import asset as asset_blueprint
        app.register_blueprint(asset_blueprint)

        from .supplier import supplier as supplier_blueprint
        app.register_blueprint(supplier_blueprint)

        from .device import device as device_blueprint
        app.register_blueprint(device_blueprint)

        from .purchase import purchase as purchase_blueprint
        app.register_blueprint(purchase_blueprint)

        from .documents import init_documents
        init_documents(app, 'commissioning')
        init_documents(app, 'risk_analysis')
        init_documents(app, 'photo')
        init_documents(app, 'manual')
        init_documents(app, 'safety_information')

        @app.errorhandler(403)
        def forbidden(error):
            return render_template('errors/403.html', title='Forbidden'), 403

        @app.errorhandler(404)
        def page_not_found(error):
            return render_template('errors/404.html',
                                   title='Page Not Found'), 404

        @app.errorhandler(500)
        def internal_server_error(error):
            return render_template('errors/500.html',
                                   title='Server Error'), 500

        @app.route('/500')
        def error_500():
            abort(500)

    return app
Пример #28
0
from flask import Flask, render_template, request, redirect, url_for, jsonify
from flask_login import login_required, LoginManager, UserMixin, login_user, logout_user, current_user
from flask_jsglue import JSGlue
from functools import wraps, update_wrapper
import hashlib
from .utils import make_hash, check_db, convert_datetime
from .db import DB
import json
import flask
from .types import UserClass

DB_FILE = r"/home/akanksha/flask/app/pythonsqlite.db"
db = DB(DB_FILE)
login_manager = LoginManager()
app = Flask(__name__)
fujs = JSGlue(app)
login_manager.init_app(app)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'


@login_manager.user_loader
def load_user(user_id):
    return check_db(user_id)


def my_decorator():
    def decorator(function):
        def wrapper(*args, **kwargs):
            print("hello", function, kwargs)
            if kwargs['name'] != current_user.get_name():
                flask.abort(400)
Пример #29
0
def create_app():
    app = Flask(__name__,
                static_folder='public/static',
                static_url_path='/static')
    Bootstrap(app)
    mongo = PyMongo(app)
    jsglue = JSGlue(app)
    filter_keys = ['all', 'type', 'setname', 'buildname', 'jailname', 'server']

    @app.template_filter('duration')
    def duration_filter(s):
        s = int(s)
        hours, remainder = divmod(s, 3600)
        minutes, seconds = divmod(remainder, 60)
        return '%d:%02d:%02d' % (hours, minutes, seconds)

    @app.template_filter('datetime')
    def format_datetime(timestamp, format='%Y-%m-%d %H:%M'):
        date = datetime.datetime.fromtimestamp(int(timestamp))
        return time.strftime(format, time.gmtime(int(timestamp)))

    def _get_builds(selector, projection=None):
        return {
            'filter':
            selector,
            'builds':
            list(
                mongo.db.builds.find(selector, projection).sort([
                    ('started', pymongo.DESCENDING),
                    ('setname', pymongo.ASCENDING),
                    ('ptname', pymongo.ASCENDING),
                    ('jailname', pymongo.ASCENDING),
                    ('buildname', pymongo.ASCENDING),
                ]))
        }

    # Mongo does not allow '.' in keys due to dot-notation.
    def fix_port_origins(ports):
        if 'pkgnames' not in ports:
            return
        for origin in ports['pkgnames']:
            if '%' in origin:
                fixed_origin = origin.replace('%', '.')
                ports['pkgnames'][fixed_origin] = ports['pkgnames'].pop(origin)
                for field in ['built', 'failed', 'skipped', 'ignored']:
                    if field in ports and origin in ports[field]:
                        ports[field][fixed_origin] = ports[field].pop(origin)

    def get_server_map():
        return {
            x["_id"]: x
            for x in list(mongo.db.servers.find({}, {'masternames': 0}))
        }

    @app.route('/')
    def index():
        return builds()

    @app.route('/servers.js')
    def servers_js():
        return make_response(
            "var servers = %s;" % (json.dumps(get_server_map())), 200,
            {'Content-Type': 'text/javascript'})

    def _get_filter():
        query = {'latest': True}
        projection = {
            'jobs': False,
            'snap.now': False,
        }
        latest = True
        if request.args is not None:
            for key, value in request.args.iteritems():
                if key in filter_keys:
                    query[key] = value
            filter = query.copy()
            if "setname" in query:
                if query['setname'] == "default":
                    query['setname'] = ''
            if "all" in query or "buildname" in query:
                if "all" in query:
                    del (query['all'])
                del (query['latest'])
                latest = False
            if "type" in query:
                build_types = query['type'].split(',')
                query['type'] = {'$in': build_types}
        return (query, projection, filter)

    def _builds():
        query, projection, filter = _get_filter()
        build_results = _get_builds(query, projection)

        filter_qs_filter = filter.copy()
        if 'type' in filter_qs_filter:
            del filter_qs_filter['type']
        filter_qs = urlencode(filter_qs_filter)

        return {
            'builds': build_results['builds'],
            'filter': build_results['filter'],
            'filter_qs': filter_qs
        }

    @app.route('/api/1/builds')
    def api_builds():
        results = _builds()
        del results['filter_qs']
        return jsonify(results)

    @app.route('/builds')
    def builds():
        results = _builds()
        results['servers'] = get_server_map()
        return render_template('builds.html', **results)

    def _build(buildid):
        build = mongo.db.builds.find_one_or_404({'_id': buildid})
        ports = mongo.db.ports.find_one({'_id': buildid})
        if ports is not None:
            fix_port_origins(ports)
        return {'build': build, 'ports': ports}

    @app.route('/api/1/builds/<buildid>')
    def api_build(buildid):
        results = _build(buildid)
        return jsonify(results)

    @app.route('/builds/<buildid>')
    def build(buildid):
        results = _build(buildid)
        results['servers'] = get_server_map()
        return render_template('build.html', **results)

    return app
Пример #30
0
        would automatically have a __tablename__ value of 'my_model'
        :return:
        """
        return to_snake_case(cls.__name__)

    def __init__(self, **kwargs):
        for attr_name, attr_value in kwargs.items():
            setattr(self, attr_name, attr_value)

    def __repr__(self: DeclarativeMeta):
        column_names = (c.name for c in self.__mapper__.columns)
        kwargs = ', '.join(f'{n}={getattr(self, n)!r}' for n in column_names)
        return f'{self.__class__.__name__}({kwargs})'

    def as_dict(self: DeclarativeMeta):
        column_names = (c.name for c in self.__mapper__.columns)
        return {n: getattr(self, n) for n in column_names}

    @property
    def session(self):
        instance_state = inspect(self)
        return instance_state.session or db.session


db = SQLAlchemy(model_class=ModelBase)
debug_toolbar = DebugToolbarExtension()
jsglue = JSGlue()
mail = Mail()
csrf = CSRFProtect()
login_manager = LoginManager()
Пример #31
0
def _setup_jsglue(app):
    return JSGlue(app)