Example #1
0
def create_app(settings=None):
    """
    Create flask application
    """
    app = Flask(__name__)
    app.secret_key = 'plante website'
    app.register_blueprint(simple_page)
    if settings:
        app.config.update(settings)

    DATA_BASE.init_app(app)
    api.init_app(app)
    compress = Compress()
    compress.init_app(app)

    configure_uploads(app, uploaded_image)

    handler = RotatingFileHandler('ueki.log', maxBytes=100000, backupCount=1)
    handler.setLevel(DEBUG)
    app.logger.addHandler(handler)
    logger = getLogger('werkzeug')
    logger.addHandler(handler)

    return app
Example #2
0
app = Flask(__name__)
app.config.from_object(server_config)

app.wsgi_app = StreamConsumingMiddleware(app.wsgi_app)

app.logger.handlers = []

app.logger.addHandler(create_logging_handler(app.config))
app.logger.addHandler(create_console_logger_handler())

app.userstorage = UserStorage()
load_users(app.userstorage)

#Enables GZIP compression
compressor = Compress()
compressor.init_app(app)

#Expose markdown trough application object
app.markdown = Markdown()

app.storage = RecipeStorage(directory=app.config['RECIPE_DIRECTORY'], 
              backup=True, 
              logger=app.logger.info)

#Jinja Context Processor
@app.context_processor
def inject_template_variables():
    return dict(base_path=app.config['BASE_PATH'], upload_directory=app.config['UPLOAD_DIRECTORY'])

@app.context_processor
def file_size_context_processor():
Example #3
0
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_bcrypt import Bcrypt
from itsdangerous import URLSafeTimedSerializer
from datetime import timedelta
from flask_compress import Compress

compress = Compress()

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

db = SQLAlchemy(app)
app.secret_key = 'super secret key'

login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = "signin"
login_serializer = URLSafeTimedSerializer(app.secret_key)
app.config["REMEMBER_COOKIE_DURATION"] = timedelta(days=14)

bcrypt = Bcrypt(app)
compress.init_app(app)

from app import views, models
Example #4
0
def register_extensions(app):
    """ register extensions to the app """
    app.jinja_env.add_extension('jinja2.ext.do')  # Global values in jinja

    # Uncomment to enable profiler
    # See scripts/profile_analyzer.py to analyze output
    # app = setup_profiler(app)

    # Compress app responses with gzip
    compress = Compress()
    compress.init_app(app)

    # Influx db time-series database
    db.init_app(app)
    influx_db.init_app(app)

    # Limit authentication blueprint requests to 200 per minute
    limiter = Limiter(app, key_func=get_ip_address)
    limiter.limit("200/minute")(routes_authentication.blueprint)

    # Language translations
    babel = Babel(app)

    @babel.localeselector
    def get_locale():
        try:
            user = User.query.filter(
                User.id == flask_login.current_user.id).first()
            if user and user.language != '':
                for key in LANGUAGES:
                    if key == user.language:
                        return key
        # Bypass endpoint test error "'AnonymousUserMixin' object has no attribute 'id'"
        except AttributeError:
            pass
        return request.accept_languages.best_match(LANGUAGES.keys())

    # User login management
    login_manager = flask_login.LoginManager()
    login_manager.init_app(app)

    @login_manager.user_loader
    def user_loader(user_id):
        user = User.query.filter(User.id == user_id).first()
        if not user:
            return
        return user

    @login_manager.unauthorized_handler
    def unauthorized():
        flash(gettext('Please log in to access this page'), "error")
        return redirect(url_for('routes_authentication.do_login'))

    # Create and populate database if it doesn't exist
    with app.app_context():
        db.create_all()
        populate_db()

        # This is disabled because there's a bug that messes up user databases
        # The upgrade script will execute alembic to upgrade the database
        # alembic_upgrade_db()

    # Check user option to force all web connections to use SSL
    # Fail if the URI is empty (pytest is running)
    if app.config['SQLALCHEMY_DATABASE_URI'] != 'sqlite://':
        with session_scope(app.config['SQLALCHEMY_DATABASE_URI']) as new_session:
            misc = new_session.query(Misc).first()
            if misc and misc.force_https:
                SSLify(app)
Example #5
0
def server_start():
    list_plans = []
    port = 8000

    lock_plans = threading.Lock()

    compress = Compress()
    app = Flask(__name__,template_folder=workdir+'/'+'webres',static_url_path='/static',static_folder=workdir+'/webres/static')
    app.config['COMPRESS_MIN_SIZE'] = 0
    app.config['COMPRESS_LEVEL'] = 6
    app.config['COMPRESS_MIMETYPES'] = ['text/html', 'text/css', 'text/xml', 'application/json', 'application/javascript', 'application/octet-stream', 'image/svg+xml']
    compress.init_app(app)

    @app.after_request
    def add_header(response):
        if response.headers['Content-Type'] == "image/png":
            response.headers['Cache-Control'] = 'must-revalidate, public, max-age=86400'
        else:
            response.headers['Cache-Control'] = 'must-revalidate, public, max-age=-1'
        return response

    @app.route('/_remove_plan')
    def remove_plan():
        location = (request.args.get('lat', type=float), request.args.get('lng', type=float))
        cid = CellId.from_lat_lng(LatLng.from_degrees(location[0],location[1])).parent(mapl.lvl_big)
        token = cid.to_token()

        lock_plans.acquire()
        if token in list_plans:
            list_plans.pop(list_plans.index(token))
        lock_plans.release()
        return jsonify("")

    @app.route('/_write_plans')
    def writeplans():
        subplans = request.args.get('subplans', type=int)
        plans = []
        lock_plans.acquire()
        for token in list_plans:
            center = LatLng.from_point(Cell(CellId.from_token(token)).get_center())
            center = (center.lat().degrees, center.lng().degrees)
            for ind_sub in range(1,subplans+1):
                plans.append({'type': 'seikur0_s2', 'token': token, 'location': [center[0],center[1]], 'subplans': subplans, 'subplan_index': ind_sub})
        lock_plans.release()

        for plan in plans:
            filename = '{}_{}_{}.plan'.format(plan['token'],plan['subplan_index'],plan['subplans'])
            try:
                f = open(plandir+'/'+filename, 'w', 0)
                json.dump(plan, f, indent=1, separators=(',', ': '))
                print('[+] Plan file {} was written.'.format(filename))
            except Exception as e:
                print('[+] Error while writing plan file, error : {}'.format(e))
            finally:
                if 'f' in vars() and not f.closed:
                    f.close()

        return jsonify("")

    @app.route('/_add_regionplans')
    def regionplans():
        lat_f,lat_t,lng_f,lng_t = request.args.get('lat_f', type=float),request.args.get('lat_t', type=float),request.args.get('lng_f', type=float),request.args.get('lng_t', type=float)
        locations = mapl.cover_region_s2((lat_f,lng_f),(lat_t,lng_t))

        return jsonify(locations)

    @app.route('/_add_plan')
    def add_plan():
        location = (request.args.get('lat', type=float),request.args.get('lng', type=float))
        all_loc,border,cid = mapl.get_area_cell(location,True)
        # grid = mapl.Hexgrid()
        # all_loc = grid.cover_cell(cid)
        center = LatLng.from_point(Cell(cid).get_center())
        center = (center.lat().degrees, center.lng().degrees)
        token = cid.to_token()
        lock_plans.acquire()
        list_plans.append(token)
        lock_plans.release()
        return jsonify((all_loc, border,[center,token],[]))

    @app.route("/_main")
    def mainfunc():

        grid = mapl.Hexgrid()
        locations = grid.cover_region((0.1, -0.1), (-0.1, 0.1)) # even: 53.0894833975485
        return jsonify(locations)

    @app.route("/")
    def mainapp():
        return render_template('spawn-view.html')

    while True:
        try:
            app.run(host='127.0.0.1', port=port, threaded=True)
        except socket.error as e:
            if e.errno == 10048:
                print('[-] Error: The specified port {} is already in use.'.format(port))
                break
Example #6
0
def server_start():
    global exclude_ids
    try:
        f = open(settings_file, 'r')
        try:
            allsettings = json.load(f)
        except ValueError as e:
            print('[-] Error: The settings file is not in a valid format, {}'.format(e))
            f.close()
            sys.exit()
        f.close()
    finally:
        if 'f' in vars() and not f.closed:
            f.close()

    exclude_ids = allsettings['exclude_ids']
    port = allsettings['port']
    if allsettings['icon_set'] == 'standard':
        icon_set = 'icons_gen1_standard.png'
    elif allsettings['icon_set'] == 'shuffle':
        icon_set = 'icons_gen1_shuffle.png'
    elif allsettings['icon_set'] == 'alt':
        icon_set = 'icons_gen1_alt.png'
    elif allsettings['icon_set'] == 'toon':
        icon_set = 'icons_gen1_toon.png'
    else:
        print('[-] Error: Icon set in settings file is invalid, possible sets are: "standard", "shuffle", "toon", "alt".')
    list_profiles = []
    list_lats = []
    list_lngs = []
    for i in range(0, len(allsettings['profiles'])):
        if allsettings['profiles'][i]['id'] not in list_profiles:
            list_profiles.append(allsettings['profiles'][i]['id'])
            list_lats.append(allsettings['profiles'][i]['coordinates']['lat'])
            list_lngs.append(allsettings['profiles'][i]['coordinates']['lng'])

    if len(list_profiles) == 0:
        print('[-] Error: No profiles in settings file.')
        sys.exit()
    else:
        main_ind = 0

    db_data = sqlite3.connect(data_file, check_same_thread=False)
    db_data.create_function("isnotExcluded", 1, isnotExcluded)

    # def patched_finish(self):
    #     print('still')
    #     try:
    #         if not self.wfile.closed:
    #             self.wfile.close()
    #     except socket.error as e:
    #         sys.stdout.write('socket error: {}\n'.format(e))
    #     self.rfile.close()
    # SocketServer.StreamRequestHandler.finish = patched_finish
    # BaseHTTPServer.HTTPServer.allow_reuse_address = False

    compress = Compress()
    app = Flask(__name__,template_folder=workdir+'/'+'webres',static_url_path='/static',static_folder=workdir+'/webres/static')
    app.config['COMPRESS_MIN_SIZE'] = 0
    app.config['COMPRESS_LEVEL'] = 6
    app.config['COMPRESS_MIMETYPES'] = ['text/html', 'text/css', 'text/xml', 'application/json', 'application/javascript', 'application/octet-stream', 'image/svg+xml']
    compress.init_app(app)

    @app.teardown_appcontext
    def close_connection(exception):
        db = getattr(g, '_database', None)
        if db is not None:
            db.close()

    @app.after_request
    def add_header(response):
        if response.headers['Content-Type'] == "image/png":
            response.headers['Cache-Control'] = 'must-revalidate, public, max-age=86400'
        else:
            response.headers['Cache-Control'] = 'must-revalidate, public, max-age=-1'
        return response

    @app.route('/_getdata')
    def add_numbers():
        datatill = request.args.get('data_till', 0, type=int)
        profile = request.args.get('profile', -1, type=int)

        timenow = int(round(time.time(),0))

        cursor_data = db_data.cursor()

        while True:
            try:
                if profile == -1:
                    results = cursor_data.execute('SELECT spawnid, latitude, longitude, spawntype, pokeid, expiretime FROM spawns WHERE isnotExcluded(pokeid) AND (expiretime > ?) AND (fromtime >= ?)',(timenow,datatill))
                else:
                    results = cursor_data.execute('SELECT spawnid, latitude, longitude, spawntype, pokeid, expiretime FROM spawns WHERE isnotExcluded(pokeid) AND (profile == ?) AND (expiretime > ?) AND (fromtime >= ?)', (profile,timenow, datatill))
                return jsonify([timenow, results.fetchall()])
            except sqlite3.OperationalError as e:
                print('[-] Sqlite operational error: {} Retrying...'.format(e))


    @app.route("/")
    def mainapp():
        return render_template('index.html',api_key=allsettings['api_key'],icon_scalefactor=allsettings['icon_scalefactor'],mobile_scale=allsettings['mobile_scalefactor'],lat=list_lats[main_ind],lng=list_lngs[main_ind],language=allsettings['language'],icon_set = icon_set, profile=-1)

    @app.route("/id<int:profile>")
    def subapp(profile):
        if profile in list_profiles:
            sub_ind = list_profiles.index(profile)
            return render_template('index.html', api_key=allsettings['api_key'], icon_scalefactor=allsettings['icon_scalefactor'], mobile_scale=allsettings['mobile_scalefactor'],lat=list_lats[sub_ind],lng=list_lngs[sub_ind], language=allsettings['language'], icon_set = icon_set, profile=profile)

    http_server = HTTPServer(WSGIContainer(app))

    try:
        http_server.listen(port=port,address='0.0.0.0')
        IOLoop.instance().start()
    except socket.error as e:
             if e.errno == 10048:
                 print('[-] Error: The specified port {} is already in use.'.format(port))
Example #7
0
    return send_from_directory('static/swaggerui/', path)


@app.route('/spec')
def swagger_json():
    """
    Endpoint that returns the swagger api using JSON
    :return:
    """
    with open('static/api.json', 'r') as f:
        return jsonify(flask.json.loads(f.read()))
        # return url_for('static', filename='api.json')


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--dev', action='store_true')
    parser.add_argument('--debug', action='store_true')
    options = parser.parse_args()

    if options.dev:
        _json_pretty = True
        _gzip = False

    if _gzip:
        c = Compress()
        c.init_app(app)
    if options.debug:
        logger.setLevel(logging.DEBUG)
    app.run(debug=options.dev)
Example #8
0
COMPRESS_LEVEL = 6
COMPRESS_MIN_SIZE = 500

load_dotenv(find_dotenv())
COMPANY_EMAIL = "@futurice.com"

# app = Flask(__name__)
app = Flask(__name__, static_url_path='', static_folder='static')
# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.getcwd() + '/database.db'
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get("DATABASE_URL")
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
app.config['SECRET_KEY'] = os.environ.get("SECRET_KEY")
sslify = SSLify(app)
db = SQLAlchemy(app)
compress = Compress()
compress.init_app(app)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
login_manager = LoginManager(app)
login_manager.login_view = "login"
login_manager.session_protection = "strong"
User, Location, Detection, TrainingDetection, Measurement, Device = get_models(
    db)


def get_name_from_email(email):
    return email.split("@")[0].replace('.', ' ').title()


@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))
Example #9
0
flask_admin.add_view(admin.CSRModelView)
flask_admin.add_view(admin.OfficeModelView)
flask_admin.add_view(admin.RoleModelView)
flask_admin.add_view(admin.ServiceModelView)
flask_admin.add_view(admin.SmartBoardModelView)
flask_admin.add_link(
    admin.LoginMenuLink(name='Login', category='', url="/api/v1/login/"))
flask_admin.add_link(
    admin.LogoutMenuLink(name='Logout', category='', url="/api/v1/logout/"))

login_manager = LoginManager()
login_manager.init_app(application)
from app import auth

compress = Compress()
compress.init_app(application)

logging.basicConfig(format=application.config['LOGGING_FORMAT'],
                    level=logging.INFO)
logger = logging.getLogger("myapp.sqltime")
logger.setLevel(logging.DEBUG)


def api_call_with_retry(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        attempts = 3

        while attempts > 0:
            attempts -= 1
            try:
Example #10
0
def extension_compress(app):
    compress = Compress()
    compress.init_app(app)
    return app