示例#1
0
class AppFactoryContext(object):

    def __init__(self):
        self.sslify = SSLify()
        self.app = None
        self.appctx = None

    def __enter__(self):
        self.app = self.create_app()
        self.appctx = self.app.app_context()
        self.appctx.push()
        return self.appctx

    def __exit__(self, exc_type, exc_value, exc_tb):
        self.appctx.pop()
        self.app = None
        self.appctx = None

    def create_app(self):
        app = Flask(__name__)
        app.config['DEBUG'] = False
        app.config['TESTING'] = False
        app.config['SERVER_NAME'] = 'example.com'
        app.config['SSLIFY_PERMANENT'] = True
        self.sslify.init_app(app)
        app.add_url_rule('/', 'home', self.view_home)
        return app

    def view_home(self):
        return 'home'
示例#2
0
from flask_sslify import SSLify
from flask_wtf import FlaskForm
from werkzeug.security import check_password_hash, generate_password_hash
from wtforms import BooleanField, StringField, PasswordField, SubmitField
from wtforms.validators import InputRequired, Email, Length, ValidationError

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

db = SQLAlchemy(app)

login = LoginManager(app)

Bootstrap(app)

SSLify(app)

gravatar = Gravatar(app, size=30)

nav = Nav(app)

@nav.navigation('mysite_navbar')
def create_navbar():
    home_view = View('Home', 'homepage')
    login_view = View('Login', 'login')
    logout_view = View('Logout', 'logout')
    posts_view = View('Posts', 'posts')
    register_view = View('Register', 'register')
    about_me_view = View('About Me', 'about_me')
    class_schedule_view = View('Class Schedule', 'class_schedule')
    top_ten_songs_view = View('Top Ten Songs', 'top_ten_songs')
示例#3
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    app.extensions['lfu_cache'] = LFUCache(100e6, getsizeof=lambda i: sys.getsizeof(i)) # ~100 MB

    csrf.init_app(app)
    bootstrap.init_app(app)
    login_manager.init_app(app)

    if app.config.get('SSLIFY_ENABLE'):
        app.logger.info("Using SSLify")
        from flask_sslify import SSLify
        sslify = SSLify(app)

    sentry = None
    if app.config.get('SENTRY_ENABLE'):
        app.logger.info("Using Sentry")
        from raven.contrib.flask import Sentry
        sentry = Sentry(app)

    @app.template_filter('from_millis')
    def _timestamp_to_datetime_filter(ts_millis):
        return datetime.datetime.fromtimestamp(ts_millis / 1000)

    @app.template_filter('nice_datetime')
    def _datetime_format_filter(dt):
        return dt.replace(microsecond=0).isoformat() + "Z"

    @app.errorhandler(500)
    def internal_server_error(error):
        return render_template(
            'errors/500.html',
            event_id=g.sentry_event_id if 'sentry_event_id' in g else None,
            public_dsn=sentry.client.get_public_dsn('https') if sentry else None
        )

    @app.errorhandler(400)
    def error_400(error):
        return render_template(
            'errors/400.html'
        )

    @app.errorhandler(403)
    def error_403(error):
        return render_template(
            'errors/403.html'
        )

    @app.errorhandler(404)
    def error_404(error):
        return render_template(
            'errors/404.html'
        )

    @app.errorhandler(405)
    def error_405(error):
        return render_template(
            'errors/405.html'
        )

    @app.after_request
    def frame_buster(response):
        response.headers['X-Frame-Options'] = 'DENY'
        return response

    @app.after_request
    def server_header(response):
        response.headers['Server'] = 'Server'
        return response

    @app.template_filter('humanize')
    def humanize(dt):
        return dt.strftime(app.config.get('DATE_FORMAT'))

    from .apikey import keys_bp
    app.register_blueprint(keys_bp)

    from .auth import auth_bp
    app.register_blueprint(auth_bp)

    from .admin import admin_bp
    app.register_blueprint(admin_bp)

    return app
示例#4
0
from lib import foodinfo as finfo
from lib import vision as vs
from lib.translator import Translator

HOST = "0.0.0.0"
PORT = 8080
IMG_EXTN = set(["jpg", "jpeg", "png", "tiff", "bmp", "gif"])

FORCE_HTTPS = False
# remove for production
DOWNLOADS = "static/downloads"
if not os.path.isdir(DOWNLOADS):
    os.mkdir(DOWNLOADS)

app = Flask(__name__)
if FORCE_HTTPS: sslify = SSLify(app, subdomains=True)
trans = Translator()


def is_image_file(filename):
    """
    Returns True if filename has an image extension
    Otherwise return False
    """
    return "." in filename and filename.split(".")[-1].lower() in IMG_EXTN


def get_calories_threaded(food, food_info):
    """
    Worker function to use for get calories
    multithreadly
示例#5
0
    "'none'",
    "object-src":
    "'none'",
}
app = Flask(__name__)
app.config["SECRET_KEY"] = os.urandom(16)
app.config["SESSION_COOKIE_NAME"] = "__Secure-session"
app.config["SESSION_COOKIE_SAMESITE"] = "Strict"
app.config["CSRF_COOKIE_NAME"] = "__Secure-csrf-token"
app.config["CSRF_COOKIE_HTTPONLY"] = True
app.config["CSRF_COOKIE_SECURE"] = True
csrf = SeaSurf(app)
talisman = Talisman(app, force_https=False, content_security_policy=csp)

if "DYNO" in os.environ:
    sslify = SSLify(app, skips=[".well-known"])


@app.after_request
def add_feature_policy(response):
    """Add feature policy."""
    response.headers["Feature-Policy"] = "geolocation 'none'"
    return response


@app.route("/<path:path>")
def static_proxy(path):
    """Find static files."""
    return send_from_directory(ROOT, path)

示例#6
0
 def __init__(self):
     self.sslify = SSLify()
     self.app = None
     self.appctx = None
示例#7
0
def create_app(config_mode=None, config_file=None):
    # Create webapp instance
    app = Flask(__name__)
    app.register_blueprint(blueprint)
    CORS(app)
    compress.init_app(app)
    cache_config = {}

    if config_mode:
        app.config.from_object(getattr(config, config_mode))
    elif config_file:
        app.config.from_pyfile(config_file)
    else:
        app.config.from_envvar('APP_SETTINGS', silent=True)

    if app.config.get('SERVER_NAME'):
        SSLify(app)

    if app.config['HEROKU']:
        cache_config['CACHE_TYPE'] = 'saslmemcached'
        cache_config['CACHE_MEMCACHED_SERVERS'] = [getenv('MEMCACHIER_SERVERS')]
        cache_config['CACHE_MEMCACHED_USERNAME'] = getenv('MEMCACHIER_USERNAME')
        cache_config['CACHE_MEMCACHED_PASSWORD'] = getenv('MEMCACHIER_PASSWORD')
    elif app.config['DEBUG_MEMCACHE']:
        cache_config['CACHE_TYPE'] = 'memcached'
        cache_config['CACHE_MEMCACHED_SERVERS'] = [getenv('MEMCACHE_SERVERS')]
    else:
        cache_config['CACHE_TYPE'] = 'simple'

    cache.init_app(app, config=cache_config)

    skwargs = {
        'name': app.config['APP_NAME'], 'version': __version__,
        'description': __description__}

    swag.init_app(app, **skwargs)

    swag_config = {
        'dom_id': '#swagger-ui',
        'url': app.config['SWAGGER_JSON'],
        'layout': 'StandaloneLayout'}

    context = {
        'base_url': app.config['SWAGGER_URL'],
        'app_name': app.config['APP_NAME'],
        'config_json': dumps(swag_config)}

    @app.route('/')
    @app.route('/<path>/')
    @app.route('{API_URL_PREFIX}/'.format(**app.config))
    @app.route('{API_URL_PREFIX}/<path>/'.format(**app.config))
    def home(path=None):
        if not path or path == 'index.html':
            return render_template('index.html', **context)
        else:
            return send_from_directory('static', path)

    exclude = app.config['SWAGGER_EXCLUDE_COLUMNS']
    create_docs = partial(swag.create_docs, exclude_columns=exclude)
    create_defs = partial(create_docs, skip_path=True)

    create_defs({'columns': CACHE_RESULT, 'name': 'reset_result'})
    create_defs({'columns': CACHE_RESULT, 'name': 'delete_result'})
    create_defs({'columns': LOREM_RESULT, 'name': 'lorem_result'})
    create_defs({'columns': SEARCH_RESULT, 'name': 'search_result'})

    with app.app_context():
        for table in gen_tables(app.view_functions, **app.config):
            create_docs(table)

    return app
import logging
import os
import openapi_server

from Flask_AuditLog import AuditLog
from Flask_No_Cache import CacheControl
from flask_sslify import SSLify

app = openapi_server.app
flaskapp = app.app

logging.basicConfig(level=logging.INFO)

AuditLog(app)
CacheControl(app)
if 'GAE_INSTANCE' in os.environ:
    SSLify(app.app, permanent=True)
示例#9
0
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

from urllib.parse import urlparse
from os import urandom, environ
from datetime import datetime as dt
from datetime import timedelta
import requests
import base64
import redis
import json
'''
Flask Server Configuration
'''
flask_server = Flask(__name__)
flask_server.config['SECRET_KEY'] = urandom(16)
SSLify(flask_server)
CORS(flask_server)
'''
    Facebook Webhook Configuration
'''
VERIFY_TOKEN = ""
PAGE_ACCESS_TOKEN = ""
#FB_API_URL = "https://graph.facebook.com/v6.0/me/messages?access_token={}".format(PAGE_ACCESS_TOKEN)
FB_API_URL = "https://graph.facebook.com/v6.0/me/messages"
'''
    Watson Assistant v2 Configuration
'''
iam_authenticator = IAMAuthenticator("")
watson_api = AssistantV2(version='2019-02-28', authenticator=iam_authenticator)
watson_api.set_service_url("https://gateway.watsonplatform.net/assistant/api")
ASSISTANT_ID = ""
示例#10
0

def check_csrf_token(req):
    token = session.pop('_csrf_token', None)
    if not token or token != req.form.get('_csrf_token'):
        abort(403)


def check_ajax_csrf_token(req):
    token = session.pop('_csrf_token', None)
    return token and token == req.form.get('_csrf_token')


app = Flask(__name__)
app.debug = bool(int(os.environ.get('DEBUG', '0')))
SSLify(app, subdomains=True)
app.secret_key = 'xinpeng2o!s'  # os.urandom(24)
app.config['SESSION_COOKIE_SECURE'] = not app.debug
app.config['PERMANENT_SESSION_LIFE_TIME'] = 1800
app.jinja_env.globals['csrf_token'] = generate_csrf_token

tz = pytz.timezone('Asia/Shanghai')

# import projhorus.user

@app.after_request
def finish_headers(response):
    response.headers["X-Frame-Options"] = "SAMEORIGIN"
    return response

@app.route('/')
示例#11
0
 def __init__(self, server: Flask) -> None:
     self._ssl: SSLify = SSLify(server)
示例#12
0
def create_app(_read_config=True, **config):
    app = flask.Flask(
        __name__,
        static_folder=None,
        template_folder=os.path.join(PROJECT_ROOT, 'templates'))

    # Utilized for sessions and other secrets
    # NOTE: This key is insecure and you should override it on the server
    app.config['SECRET_KEY'] = 't\xad\xe7\xff%\xd2.\xfe\x03\x02=\xec\xaf\\2+\xb8=\xf7\x8a\x9aLD\xb1'
    if 'SECRET_KEY' in os.environ:
        app.config['SECRET_KEY'] = os.environ['SECRET_KEY']

    # The api key to authorize end users against this system.
    # NOTE: This key is insecure and you should override it on the server
    app.config['API_KEY'] = '3e84744ab2714151b1db789df82b41c0021958fe4d77406e9c0947c34f5c5a70'
    if 'API_KEY' in os.environ:
        app.config['API_KEY'] = os.environ['API_KEY']

    # The private key to use when cloning repositories
    # TODO(dcramer): this should support an on-disk option, as well as be
    # possible to override per repo
    app.config['SSH_PRIVATE_KEY'] = os.environ.get('SSH_PRIVATE_KEY', '').replace("\\n", "\n")

    app.config['FREIGHT_URL'] = os.environ.get('FREIGHT_URL', '').rstrip('/')

    if 'REDISCLOUD_URL' in os.environ:
        app.config['REDIS_URL'] = os.environ['REDISCLOUD_URL']
    elif 'REDIS_URL' in os.environ:
        app.config['REDIS_URL'] = os.environ['REDIS_URL']

    app.config['WORKSPACE_ROOT'] = os.environ.get('WORKSPACE_ROOT', '/tmp')

    app.config['DEFAULT_TIMEOUT'] = int(os.environ.get('DEFAULT_TIMEOUT', 3600))
    app.config['DEFAULT_READ_TIMEOUT'] = int(os.environ.get('DEFAULT_READ_TIMEOUT', 600))

    app.config['LOG_LEVEL'] = os.environ.get('LOG_LEVEL', 'INFO' if config.get('DEBUG') else 'ERROR')

    app.config['DEV'] = config.get('DEV', False)

    # Currently authentication requires Google
    app.config['GOOGLE_CLIENT_ID'] = os.environ.get('GOOGLE_CLIENT_ID')
    app.config['GOOGLE_CLIENT_SECRET'] = os.environ.get('GOOGLE_CLIENT_SECRET')
    app.config['GOOGLE_DOMAIN'] = os.environ.get('GOOGLE_DOMAIN')

    # Generate a GitHub token via Curl:
    # curlish https://api.github.com/authorizations \
    #     -u your-username \
    #     -X POST \
    #     -J scopes='repo' \
    #     -J note='freight'
    app.config['GITHUB_TOKEN'] = os.environ.get('GITHUB_TOKEN')
    app.config['GITHUB_API_ROOT'] = 'https://api.github.com'

    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
    app.config['SQLALCHEMY_POOL_SIZE'] = 5
    app.config['SQLALCHEMY_MAX_OVERFLOW'] = 0
    if 'SQLALCHEMY_DATABASE_URI' in os.environ:
        app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['SQLALCHEMY_DATABASE_URI']

    app.config['QUEUES'] = [
        'freight.default',
        'freight.tasks',
        'freight.queue',
        'freight.notifications',
    ]
    app.config['QUEUE_DEFAULT'] = 'freight.default'
    app.config['QUEUE_ROUTES'] = {
        'freight.jobs.execute_task': 'freight.tasks',
        'freight.jobs.check_queue': 'freight.queue',
        'freight.jobs.send_pending_notifications': 'freight.notifications',
    }
    app.config['QUEUE_SCHEDULE'] = {
        'freight.jobs.check_queue': {
            'seconds': 1,
        },
        'freight.jobs.send_pending_notifications': {
            'seconds': 1,
        },
    }

    app.config['SENTRY_INCLUDE_PATHS'] = [
        'freight',
    ]

    # We don't support non-proxied installs
    app.wsgi_app = ProxyFix(app.wsgi_app)

    # Pull in Heroku configuration
    heroku.init_app(app)

    # Pull in environment variables from docker
    docker_init_app(app)

    if 'DYNO' in os.environ:
        # XXX: the released version of flask-sslify does not support init_app
        SSLify(app)

    # Set any remaining defaults that might not be present yet
    if not app.config.get('SQLALCHEMY_DATABASE_URI'):
        app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///freight'

    app.config.setdefault('REDIS_URL', 'redis://localhost:6379')
    app.config.setdefault('REDIS_DB', 0)

    app.config.update(config)

    if _read_config:
        if os.environ.get('FREIGHT_CONF'):
            # FREIGHT_CONF=/etc/freight.conf.py
            app.config.from_envvar('FREIGHT_CONF')
        else:
            # Look for ~/.freight/freight.conf.py
            path = os.path.normpath(os.path.expanduser('~/.freight/freight.conf.py'))
            app.config.from_pyfile(path, silent=True)

    configure_logging(app)
    configure_sentry(app)
    configure_api(app)
    configure_redis(app)
    configure_queue(app)
    configure_sqlalchemy(app)
    configure_web_routes(app)

    return app
示例#13
0
# Copyright (C) 2019 Kevin McKenzie.

from flask_sslify import SSLify
import logging
from models_fs import Album, Image, User
from settings import init, ALLOWED_EXTENSIONS
import storage
from flask import (Flask, render_template, flash, request, Blueprint)
from flask_login import (login_required, current_user)

app = Flask(__name__)
sslify = SSLify(app)  #force HTTPS even when user requests HTTP
init(app)

blueprint = Blueprint('admin', __name__)


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def upload_file(file, album):
    folder = "albums/" + album + "/"
    img = None
    if album == "covers":
        folder = "covers/"
    if allowed_file(file.filename):
        saved_file_name = storage.upload_file(file,
                                              folder,
                                              app.config['UPLOAD_BUCKET'],
示例#14
0
文件: app.py 项目: schlich/gram
import dash_html_components as html
import dash_table
import pandas as pd
import pygsheets as pyg
import plotly.graph_objs as go
from dotenv import load_dotenv
from flask_sslify import SSLify
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate

external_stylesheets = [dbc.themes.JOURNAL]
load_dotenv()

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server = app.server
SSLify(server)

# csp = {
#     'default-src': '\'self\'',
#     'script-src': '\'self\'',
#     'style-src': '\'self\''
#     }
# Talisman(server, content_security_policy=csp)

client = pyg.authorize(service_account_env_var="GOOGLE_SHEETS_CREDS_JSON")


def fetch_data(table_name):
    table = client.open("EMR Database").worksheet("title",
                                                  table_name).get_all_values()
    headers = table.pop(0)
示例#15
0
def create_app(config):
    app = Flask(__name__)
    config_name = config

    if not isinstance(config, str):
        config_name = os.getenv("FLASK_CONFIG", "default")

    app.config.from_object(Config[config_name])
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    # not using sqlalchemy event system, hence disabling it

    Config[config_name].init_app(app)

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)
    configure_uploads(app, images)
    configure_uploads(app, docs)
    CKEditor(app)
    share.init_app(app)
    Bootstrap(app)

    # Register Jinja template functions
    from .utils import register_template_utils

    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ["assets/styles", "assets/scripts"]
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register("app_css", app_css)
    assets_env.register("app_js", app_js)
    assets_env.register("vendor_css", vendor_css)
    assets_env.register("vendor_js", vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config["SSL_DISABLE"]:
        from flask_sslify import SSLify

        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint

    app.register_blueprint(main_blueprint)

    from .public import public as public_blueprint

    app.register_blueprint(public_blueprint)

    from .account import account as account_blueprint

    app.register_blueprint(account_blueprint, url_prefix="/account")

    from .question import question as question_blueprint

    app.register_blueprint(question_blueprint, url_prefix="/question")

    from .answer import answer as answer_blueprint

    app.register_blueprint(answer_blueprint, url_prefix="/answer")

    from .project import project as project_blueprint

    app.register_blueprint(project_blueprint, url_prefix="/project")

    from .admin import admin as admin_blueprint

    app.register_blueprint(admin_blueprint, url_prefix="/admin")

    from .organisations import organisations as organisations_blueprint

    app.register_blueprint(organisations_blueprint, url_prefix="/organisations")

    from .blog import blog

    app.register_blueprint(blog, url_prefix="/blog")

    return app
示例#16
0
def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    csrf.init_app(app)
    bootstrap.init_app(app)
    mail.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db)
    login_manager.init_app(app)
    rq.init_app(app)

    if app.config.get('SSLIFY_ENABLE'):
        app.logger.info("Using SSLify")
        from flask_sslify import SSLify
        sslify = SSLify(app)

    sentry = None
    if app.config.get('SENTRY_ENABLE'):
        app.logger.info("Using Sentry")
        sentry = Sentry(app)

    @app.errorhandler(500)
    def internal_server_error(error):
        return render_template('500.html',
                               event_id=g.sentry_event_id,
                               public_dsn=sentry.client.get_public_dsn('https')
                               if sentry else None), 500

    @app.errorhandler(400)
    def error_400(error):
        return render_template('400.html'), 400

    @app.errorhandler(403)
    def error_403(error):
        return render_template('403.html'), 403

    @app.errorhandler(404)
    def error_404(error):
        return render_template('404.html'), 404

    @app.errorhandler(405)
    def error_405(error):
        return render_template('405.html'), 405

    @app.after_request
    def frame_buster(response):
        response.headers['X-Frame-Options'] = 'DENY'
        return response

    @app.after_request
    def server_header(response):
        response.headers['Server'] = 'Server'
        return response

    @app.template_filter('humanize')
    def humanize(dt):
        return dt.strftime(app.config.get('DATE_FORMAT'))

    from .carpool import pool_bp
    app.register_blueprint(pool_bp)

    from .auth import auth_bp
    app.register_blueprint(auth_bp)

    from .admin import admin_bp
    app.register_blueprint(admin_bp)

    @app.before_request
    def block_handling():
        """ Log out a user that's blocked and send them to the index page. """
        if not current_user.is_anonymous and current_user.has_roles('blocked'):
            flash("There was a problem with your login.", 'error')
            current_app.logger.warn("Logged out blocked user %s",
                                    current_user.id)
            logout_user()
            return redirect(url_for('auth.login'))

    return app
示例#17
0
from jose.jwt import JWTError

from aggregator import (
    COUNT_HISTOGRAM_LABELS, COUNT_HISTOGRAM_PREFIX, NUMERIC_SCALARS_PREFIX, SCALAR_MEASURE_MAP)
from db import get_db_connection_string, histogram_revision_map, _preparedb

pool = None
db_connection_string = get_db_connection_string(read_only=True)
app = Flask(__name__)
dockerflow = Dockerflow(app, version_path='/app')

app.config.from_pyfile('config.py')

CORS(app, resources=r'/*', allow_headers=['Authorization', 'Content-Type'])
cache = Cache(app, config={'CACHE_TYPE': app.config["CACHETYPE"]})
sslify = SSLify(app, permanent=True, skips=['__version__', '__heartbeat__', '__lbheartbeat__', 'status'])

patch_all()
patch_psycopg()
cache.clear()

# For caching - change this if after backfilling submission_date data
SUBMISSION_DATE_ETAG = 'submission_date_v1'
CLIENT_CACHE_SLACK_SECONDS = 3600

# If we get a query string not in this set we throw a 405.
ALLOWED_DIMENSIONS = ('application', 'architecture', 'child', 'dates', 'label',
                      'metric', 'os', 'osVersion', 'version')

# Disallowed metrics for serving - matches regex
METRICS_BLACKLIST_RE = map(
示例#18
0
import rollbar.contrib.flask

DEV = 'development'
LIVE = 'production'

BRICK_PATH = os.path.join(os.path.dirname(legofy.__file__), "assets", "bricks",
                          "1x1.png")
BRICK_IMAGE = Image.open(BRICK_PATH)

ROLLBAR_ACCESS_TOKEN = os.environ.get('ROLLBAR_ACCESS_TOKEN', None)

BRICKY_ENV = os.environ.get('BRICKY_ENV', DEV)

app = Flask(__name__)
if BRICKY_ENV == LIVE:
    sslify = SSLify(app, age=600)


@app.before_first_request
def setup_logging():
    if not app.debug:
        app.logger.addHandler(logging.StreamHandler())
        app.logger.setLevel(logging.INFO)


@app.before_first_request
def setup_rollbar():
    if ROLLBAR_ACCESS_TOKEN:
        rollbar.init(ROLLBAR_ACCESS_TOKEN,
                     BRICKY_ENV,
                     root=os.path.dirname(os.path.realpath(__file__)),
示例#19
0
文件: main.py 项目: paraschadha/final
#!/usr/bin/env python

import flask
import os
import cgi
import requests
import json
import time
import hashlib
import re
from flask import request, redirect
from flask_sslify import SSLify
APP = flask.Flask(__name__)
sslify = SSLify(APP)


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


@APP.route('/pwn', methods=['POST'])
def pwn():
    i = 1000000000
    refer = request.form['refer']
    position = int(request.form['position'])
    email = request.form['email']
    if email == "":
        return redirect('/')
    if position < 400:
        return redirect('/')
示例#20
0
def create_app(package_name,
               package_path,
               settings_override=None,
               register_all_blueprints=True):
    """Returns a :class:`Flask` application instance configured with common
    functionality for the Overholt platform.

    :param package_name: application package name
    :param package_path: application package path
    :param settings_override: a dictionary of settings to override
    :param register_security_blueprint: flag to specify if the Flask-Security
                                        Blueprint should be registered.
                                        Defaults to `True`.
    """
    app = Flask(package_name, instance_relative_config=True)
    app.config.from_object('apollo.settings')
    app.config.from_object(settings_override)

    sentry.init_app(app)
    babel.init_app(app)
    cache.init_app(app)
    db.init_app(app)
    migrate.init_app(app, db)
    mail.init_app(app)
    red.init_app(app)

    configure_uploads(app, uploads)

    if app.config.get('SSL_REQUIRED'):
        SSLify(app)

    if app.config.get('DEBUG') and fdt_available:
        debug_toolbar.init_app(app)

    # don't reregister the locale selector
    # if we already have one
    if babel.locale_selector_func is None:

        @babel.localeselector
        def get_locale():
            # get a list of available language codes,
            # starting from the current user's selected
            # language
            language_codes = set()
            if not current_user.is_anonymous:
                if current_user.locale:
                    return current_user.locale

            language_codes.update(app.config.get('LANGUAGES', {}).keys())

            return request.accept_languages \
                .best_match(language_codes)

    register_blueprints(app, package_name, package_path)

    if register_all_blueprints:
        for configured_app in app.config.get('APPLICATIONS'):
            register_blueprints(app, configured_app,
                                import_module(configured_app).__path__)

    return app
示例#21
0
def create_app(config):
    app = Flask(__name__)
    config_name = config

    if not isinstance(config, str):
        config_name = os.getenv('FLASK_CONFIG', 'default')

    app.config.from_object(Config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    # not using sqlalchemy event system, hence disabling it

    Config[config_name].init_app(app)
    app.config['UPLOADED_IMAGES_DEST'] = '/home/ubuntu/flaskapp/flask-base/appstatic/photo/' if \
        not os.environ.get('UPLOADED_IMAGES_DEST') else os.path.dirname(os.path.realpath(__file__)) + os.environ.get(
        'UPLOADED_IMAGES_DEST')
    app.config['UPLOADED_DOCS_DEST'] = '/home/ubuntu/flaskapp/flask-base/appstatic/docs/' if \
        not os.environ.get('UPLOADED_DOCS_DEST') else os.path.dirname(os.path.realpath(__file__)) + os.environ.get(
        'UPLOADED_DOCS_DEST')
    app.config['docs'] = app.config['UPLOADED_DOCS_DEST']

    # Set up extensions
    mail.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    compress.init_app(app)
    RQ(app)
    configure_uploads(app, images)
    configure_uploads(app, docs)
    share.init_app(app)
    CKEditor(app)
    moment.init_app(app)

    # Register Jinja template functions
    from .utils import register_template_utils
    register_template_utils(app)

    # Set up asset pipeline
    assets_env = Environment(app)
    dirs = ['assets/styles', 'assets/scripts']
    for path in dirs:
        assets_env.append_path(os.path.join(basedir, path))
    assets_env.url_expire = True

    assets_env.register('app_css', app_css)
    assets_env.register('app_js', app_js)
    assets_env.register('vendor_css', vendor_css)
    assets_env.register('vendor_js', vendor_js)

    # Configure SSL if platform supports it
    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask_sslify import SSLify
        SSLify(app)

    # Create app blueprints
    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .api import blueprint as api_blueprint
    app.register_blueprint(api_blueprint)

    from .public import public as public_blueprint
    app.register_blueprint(public_blueprint)

    from .account import account as account_blueprint
    app.register_blueprint(account_blueprint, url_prefix='/account')

    from .admin import admin as admin_blueprint
    app.register_blueprint(admin_blueprint, url_prefix='/admin')

    from .blog import blog as blog_blueprint
    app.register_blueprint(blog_blueprint, url_prefix='/blog')

    return app
示例#22
0
def create_app(config=None):
    from . import models, routes, services
    from .assets import assets
    app = Flask(__name__)

    # Read log level from environment variable
    log_level_name = os.environ.get('PDNS_ADMIN_LOG_LEVEL', 'WARNING')
    log_level = logging.getLevelName(log_level_name.upper())
    # Setting logger
    logging.basicConfig(
       level=log_level,
        format=
        "[%(asctime)s] [%(filename)s:%(lineno)d] %(levelname)s - %(message)s")

    # If we use Docker + Gunicorn, adjust the
    # log handler
    if "GUNICORN_LOGLEVEL" in os.environ:
        gunicorn_logger = logging.getLogger("gunicorn.error")
        app.logger.handlers = gunicorn_logger.handlers
        app.logger.setLevel(gunicorn_logger.level)

    # Proxy
    app.wsgi_app = ProxyFix(app.wsgi_app)

    # CSRF protection
    csrf = SeaSurf(app)
    csrf.exempt(routes.index.dyndns_checkip)
    csrf.exempt(routes.index.dyndns_update)
    csrf.exempt(routes.index.saml_authorized)
    csrf.exempt(routes.api.api_login_create_zone)
    csrf.exempt(routes.api.api_login_delete_zone)
    csrf.exempt(routes.api.api_generate_apikey)
    csrf.exempt(routes.api.api_delete_apikey)
    csrf.exempt(routes.api.api_update_apikey)
    csrf.exempt(routes.api.api_zone_subpath_forward)
    csrf.exempt(routes.api.api_zone_forward)
    csrf.exempt(routes.api.api_create_zone)
    csrf.exempt(routes.api.api_create_account)
    csrf.exempt(routes.api.api_delete_account)
    csrf.exempt(routes.api.api_update_account)
    csrf.exempt(routes.api.api_create_user)
    csrf.exempt(routes.api.api_delete_user)
    csrf.exempt(routes.api.api_update_user)
    csrf.exempt(routes.api.api_list_account_users)
    csrf.exempt(routes.api.api_add_account_user)
    csrf.exempt(routes.api.api_remove_account_user)

    # Load config from env variables if using docker
    if os.path.exists(os.path.join(app.root_path, 'docker_config.py')):
        app.config.from_object('powerdnsadmin.docker_config')
    else:
        # Load default configuration
        app.config.from_object('powerdnsadmin.default_config')

    # Load config file from FLASK_CONF env variable
    if 'FLASK_CONF' in os.environ:
        app.config.from_envvar('FLASK_CONF')

    # Load app sepecified configuration
    if config is not None:
        if isinstance(config, dict):
            app.config.update(config)
        elif config.endswith('.py'):
            app.config.from_pyfile(config)

    # HSTS
    if app.config.get('HSTS_ENABLED'):
        from flask_sslify import SSLify
        _sslify = SSLify(app)  # lgtm [py/unused-local-variable]

    # Load Flask-Session
    if app.config.get('FILESYSTEM_SESSIONS_ENABLED'):
        app.config['SESSION_TYPE'] = 'filesystem'
        sess = Session()
        sess.init_app(app)

    # SMTP
    app.mail = Mail(app)

    # Load app's components
    assets.init_app(app)
    models.init_app(app)
    routes.init_app(app)
    services.init_app(app)

    # Register filters
    app.jinja_env.filters['display_record_name'] = utils.display_record_name
    app.jinja_env.filters['display_master_name'] = utils.display_master_name
    app.jinja_env.filters['display_second_to_time'] = utils.display_time
    app.jinja_env.filters[
        'email_to_gravatar_url'] = utils.email_to_gravatar_url
    app.jinja_env.filters[
        'display_setting_state'] = utils.display_setting_state
    app.jinja_env.filters['pretty_domain_name'] = utils.pretty_domain_name

    # Register context proccessors
    from .models.setting import Setting

    @app.context_processor
    def inject_sitename():
        setting = Setting().get('site_name')
        return dict(SITE_NAME=setting)

    @app.context_processor
    def inject_setting():
        setting = Setting()
        return dict(SETTING=setting)

    @app.context_processor
    def inject_mode():
        setting = app.config.get('OFFLINE_MODE', False)
        return dict(OFFLINE_MODE=setting)

    return app
示例#23
0
from flask import Flask
from flask_sslify import SSLify

from osscla import settings

static_folder = settings.get('STATIC_FOLDER')
app = Flask(__name__, static_folder=static_folder)
app.config.from_object(settings)
app.debug = app.config['DEBUG']

if app.config['SSLIFY']:
    sslify = SSLify(app, skips=['healthcheck'])  # noqa

app.secret_key = app.config['SESSION_SECRET']
示例#24
0
ROOT = os.path.join(DIR, 'docs', '_build', 'html')


def find_key(token):
    if token == os.environ.get("ACME_TOKEN"):
        return os.environ.get("ACME_KEY")
    for k, v in os.environ.items():
        if v == token and k.startswith("ACME_TOKEN_"):
            n = k.replace("ACME_TOKEN_", "")
            return os.environ.get("ACME_KEY_{}".format(n))


app = Flask(__name__)

if 'DYNO' in os.environ:
    sslify = SSLify(app, skips=['.well-known'])


@app.route('/<path:path>')
def static_proxy(path):
    """Static files proxy"""
    return send_from_directory(ROOT, path)


@app.route('/')
def index_redirection():
    """Redirecting index file"""
    return send_from_directory(ROOT, 'index.html')


@app.route("/.well-known/acme-challenge/<token>")
示例#25
0
from werkzeug.contrib.fixers import ProxyFix

from flask import Flask
from flask import jsonify
from flask import make_response
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for
from flask import Response
from flask import abort
from flask_sslify import SSLify

app = Flask(__name__, static_folder='static', static_url_path='')
sslify = SSLify(app, permanent=True, subdomains=True)

db = None
lang = None
config = None

descAllowedTags = bleach.ALLOWED_TAGS + ['br', 'pre']

config_str = open('config.json', 'rb').read()
config = json.loads(config_str)

lang_str = open(config['language_file'], 'rb').read()
lang = json.loads(lang_str)

lang = lang[config['language']]
示例#26
0
def create_app(_read_config=True, **config):
    from kombu import Queue

    app = flask.Flask(__name__,
                      static_folder=None,
                      template_folder=os.path.join(PROJECT_ROOT, 'templates'))

    # Utilized for sessions and other secrets
    # NOTE: This key is insecure and you should override it on the server
    app.config[
        'SECRET_KEY'] = 't\xad\xe7\xff%\xd2.\xfe\x03\x02=\xec\xaf\\2+\xb8=\xf7\x8a\x9aLD\xb1'
    if 'SECRET_KEY' in os.environ:
        app.config['SECRET_KEY'] = os.environ['SECRET_KEY']

    # The api key to authorize end users against this system.
    # NOTE: This key is insecure and you should override it on the server
    app.config[
        'API_KEY'] = '3e84744ab2714151b1db789df82b41c0021958fe4d77406e9c0947c34f5c5a70'
    if 'API_KEY' in os.environ:
        app.config['API_KEY'] = os.environ['API_KEY']

    # The private key to use when cloning repositories
    # TODO(dcramer): this should support an on-disk option, as well as be
    # possible to override per repo
    app.config['SSH_PRIVATE_KEY'] = os.environ.get('SSH_PRIVATE_KEY',
                                                   '').replace("\\n", "\n")

    app.config['FREIGHT_URL'] = os.environ.get('FREIGHT_URL', '').rstrip('/')

    if 'REDISCLOUD_URL' in os.environ:
        app.config['REDIS_URL'] = os.environ['REDISCLOUD_URL']
    elif 'REDIS_URL' in os.environ:
        app.config['REDIS_URL'] = os.environ['REDIS_URL']

    app.config['WORKSPACE_ROOT'] = os.environ.get('WORKSPACE_ROOT', '/tmp')

    app.config['DEFAULT_TIMEOUT'] = int(os.environ.get('DEFAULT_TIMEOUT',
                                                       3600))
    app.config['DEFAULT_READ_TIMEOUT'] = int(
        os.environ.get('DEFAULT_READ_TIMEOUT', 300))

    app.config['LOG_LEVEL'] = os.environ.get(
        'LOG_LEVEL', 'INFO' if config.get('DEBUG') else 'ERROR')

    # Currently authentication requires Google
    app.config['GOOGLE_CLIENT_ID'] = os.environ.get('GOOGLE_CLIENT_ID')
    app.config['GOOGLE_CLIENT_SECRET'] = os.environ.get('GOOGLE_CLIENT_SECRET')
    app.config['GOOGLE_DOMAIN'] = os.environ.get('GOOGLE_DOMAIN')

    # Generate a GitHub token via Curl:
    # curlish https://api.github.com/authorizations \
    #     -u your-username \
    #     -X POST \
    #     -J scopes='repo' \
    #     -J note='freight'
    app.config['GITHUB_TOKEN'] = os.environ.get('GITHUB_TOKEN')
    app.config['GITHUB_API_ROOT'] = 'https://api.github.com'

    app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
    app.config['SQLALCHEMY_POOL_SIZE'] = 5
    app.config['SQLALCHEMY_MAX_OVERFLOW'] = 0
    if 'SQLALCHEMY_DATABASE_URI' in os.environ:
        app.config['SQLALCHEMY_DATABASE_URI'] = os.environ[
            'SQLALCHEMY_DATABASE_URI']

    app.config['BROKER_TRANSPORT'] = None
    if 'BROKER_URL' in os.environ:
        app.config['BROKER_URL'] = os.environ['BROKER_URL']

    app.config['CELERY_ACCEPT_CONTENT'] = ['json']
    app.config['CELERY_ACKS_LATE'] = True
    app.config['CELERY_DEFAULT_QUEUE'] = "default"
    app.config['CELERY_DEFAULT_EXCHANGE'] = "default"
    app.config['CELERY_DEFAULT_EXCHANGE_TYPE'] = "direct"
    app.config['CELERY_DEFAULT_ROUTING_KEY'] = "default"
    app.config['CELERY_DISABLE_RATE_LIMITS'] = True
    app.config['CELERY_IGNORE_RESULT'] = True
    app.config['CELERY_RESULT_BACKEND'] = None
    app.config['CELERY_RESULT_SERIALIZER'] = 'json'
    app.config['CELERY_SEND_EVENTS'] = False
    app.config['CELERY_TASK_RESULT_EXPIRES'] = 1
    app.config['CELERY_TASK_SERIALIZER'] = 'json'
    app.config['CELERY_TIMEZONE'] = 'UTC'
    app.config['CELERYD_PREFETCH_MULTIPLIER'] = 1
    app.config['CELERYD_MAX_TASKS_PER_CHILD'] = 10000
    app.config['CELERYBEAT_SCHEDULE_FILENAME'] = os.path.join(
        tempfile.gettempdir(), 'freight-celerybeat')
    app.config['CELERYBEAT_SCHEDULE'] = {
        'check-queue': {
            'task': 'freight.check_queue',
            'schedule': timedelta(seconds=5),
            'options': {
                'expires': 5,
                'queue': 'freight.queue',
            }
        },
        'send-pending-notifications': {
            'task': 'freight.send_pending_notifications',
            'schedule': timedelta(seconds=5),
            'options': {
                'expires': 5,
                'queue': 'freight.notifications',
            }
        },
    }

    app.config['CELERY_QUEUES'] = (
        Queue('default', routing_key='default'),
        Queue('freight.tasks', routing_key='freight.tasks'),
        Queue('freight.queue', routing_key='freight.queue'),
        Queue('freight.notifications', routing_key='freight.notifications'),
    )

    app.config['CELERY_IMPORTS'] = ('freight.tasks', )

    app.config['CELERY_ROUTES'] = {
        'freight.execute_task': {
            'queue': 'freight.tasks',
            'routing_key': 'freight.tasks',
        },
        'freight.check_queue': {
            'queue': 'freight.queue',
            'routing_key': 'freight.queue',
        },
        'freight.send_pending_notifications': {
            'queue': 'freight.notifications',
            'routing_key': 'freight.notifications',
        },
    }

    app.config['SENTRY_INCLUDE_PATHS'] = [
        'freight',
    ]

    # We don't support non-proxied installs
    app.wsgi_app = ProxyFix(app.wsgi_app)

    # Pull in Heroku configuration
    heroku.init_app(app)

    if 'DYNO' in os.environ:
        # XXX: the released version of flask-sslify does not support init_app
        SSLify(app)

    # Set any remaining defaults that might not be present yet
    if not app.config.get('SQLALCHEMY_DATABASE_URI'):
        app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql:///freight'

    if not app.config.get('BROKER_URL'):
        app.config['BROKER_URL'] = 'redis://localhost/0'

    app.config.update(config)

    if _read_config:
        if os.environ.get('FREIGHT_CONF'):
            # FREIGHT_CONF=/etc/freight.conf.py
            app.config.from_envvar('FREIGHT_CONF')
        else:
            # Look for ~/.freight/freight.conf.py
            path = os.path.normpath(
                os.path.expanduser('~/.freight/freight.conf.py'))
            app.config.from_pyfile(path, silent=True)

    configure_logging(app)
    configure_sentry(app)
    configure_api(app)
    configure_celery(app)
    configure_redis(app)
    configure_sqlalchemy(app)
    configure_web_routes(app)

    return app
示例#27
0
文件: app.py 项目: safrant/Titan
app.config['SQLALCHEMY_DATABASE_URI'] = config['database-uri']
app.config[
    'SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # Suppress the warning/no need this on for now.
app.config['RATELIMIT_HEADERS_ENABLED'] = True
app.config['SQLALCHEMY_POOL_RECYCLE'] = 100
app.config['SQLALCHEMY_POOL_SIZE'] = 15
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['RATELIMIT_STORAGE_URL'] = config["redis-uri"]
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=3)
app.config['REDIS_URL'] = config["redis-uri"]
app.secret_key = config['app-secret']

db.init_app(app)
rate_limiter.init_app(app)
if config.get("enable-ssl", False):
    sslify = SSLify(app, permanent=True)
socketio.init_app(app,
                  message_queue=config["redis-uri"],
                  path='gateway',
                  async_mode=config.get("websockets-mode", None))
babel.init_app(app)
redis_store.init_app(app)

app.register_blueprint(api.api,
                       url_prefix="/api",
                       template_folder="/templates")
app.register_blueprint(admin.admin,
                       url_prefix="/admin",
                       template_folder="/templates")
app.register_blueprint(user.user,
                       url_prefix="/user",
示例#28
0
from flask import Flask
from flask_sslify import SSLify
from flask import request
import requests
import numpy as np
import json
from PIL import Image
from io import BytesIO


app = Flask(__name__)
ssl = SSLify(app)


def get_photo(photo_id, token):
    size = (224, 224)
    url = 'https://api.telegram.org/bot' + token + '/' + 'getFile?file_id=' + str(photo_id)
    r = requests.get(url).json()
    path_to_photo = r['result']['file_path']
    file_url = 'https://api.telegram.org/file/bot' + token + '/' + str(path_to_photo)
    response = requests.get(file_url)
    img = Image.open(BytesIO(response.content))
    img = img.resize(size)
    return img


def send_message(token, chat_id, text='text'):
    url = 'https://api.telegram.org/bot' + token + '/' + 'sendMessage' + '?chat_id=' + str(chat_id) + '&text=' + text
    return requests.get(url)

示例#29
0
from flask import Flask, request, render_template
from flask_sslify import SSLify

from multi import *
from recursive import *
from prepost import *

app = Flask(__name__)
sslify = SSLify(app)  # to redirect everything to https


@app.route('/list', methods=['GET'])
def list():
    return render_template('list.html')


@app.route('/', methods=['GET', 'POST'])
def multi():
    """
    This is the flash view function for /multi, takes GET and POST methods
    """
    form = MultiForm(request.form)

    if request.method == 'GET':

        pps_output, ecog_output, kps_output, ppi_output, psppi_output, pap_output, dpap_output = {},{},{},{},{},{},{}
        clinical_guess = ''
        incomplete_models = []
        cg_is_days = False

        #print form.validate()
示例#30
0
app = Flask(__name__)
app.config.from_object(DefaultConfig)

if 'POLIEDRO_DONATE_CONFIG' in os.environ:
    app.config.from_envvar('POLIEDRO_DONATE_CONFIG')

from .database import db

if app.config.get("APP_ENABLE_CORS", False):
    from flask_cors import CORS

    CORS(app)

if app.config["APP_SSL"]:
    sslify = SSLify(app, age=app.config["APP_SSL_AGE"], permanent=True)

babel = Babel(app)


@babel.localeselector
def get_locale():
    return getattr(g, "lang", "en")


app.jinja_env.globals['json'] = json
app.jinja_env.globals['len'] = len
app.jinja_env.globals['sorted'] = sorted

from .cli import *
from .errors import *
示例#31
0
from mycroft_jarbas_utils.hivemind.database.user import UserDatabase


def root_dir():
    """ Returns root directory for this project """
    return os.path.dirname(os.path.dirname(os.path.realpath(__file__ + '/.')))


def nice_json(arg):
    response = make_response(json.dumps(arg, sort_keys=True, indent=4))
    response.headers['Content-type'] = "application/json"
    return response


app = Flask(__name__)
sslify = SSLify(app)
port = 5678

users = UserDatabase()


def add_response_headers(headers=None):
    """This decorator adds the headers passed in to the response"""
    headers = headers or {}

    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            resp = make_response(f(*args, **kwargs))
            h = resp.headers
            for header, value in headers.items():
示例#32
0
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
import calendar
from bootstrap import conf, application, populate_g
from flask.ext.babel import Babel
from flask.ext.babel import format_datetime

if conf.ON_HEROKU:
    from flask_sslify import SSLify
    SSLify(application)

babel = Babel(application)


# Jinja filters
def month_name(month_number):
    return calendar.month_name[month_number]


application.jinja_env.filters['month_name'] = month_name
application.jinja_env.filters['datetime'] = format_datetime
application.jinja_env.globals['conf'] = conf

# Views
from flask.ext.restful import Api