Beispiel #1
3
def test_gravatar_url():
    """Test that the gravatar url is generated correctly"""
    app = Flask(__name__)

    with app.test_request_context("/"):
        app.debug = True
        url = gravatar_url("*****@*****.**")
        eq_(url, "http://www.gravatar.com/avatar/" "b642b4217b34b1e8d3bd915fc65c4452?d=mm")

        url = gravatar_url("*****@*****.**", 200)
        eq_(url, "http://www.gravatar.com/avatar/" "b642b4217b34b1e8d3bd915fc65c4452?s=200&d=mm")

        app.debug = False

        url = gravatar_url("*****@*****.**")
        eq_(url, "http://www.gravatar.com/avatar/" "b642b4217b34b1e8d3bd915fc65c4452?d=mm")

        app.config["SITE_URL"] = "http://www.site.com"

        url = gravatar_url("*****@*****.**")
        eq_(
            url,
            "http://www.gravatar.com/avatar/"
            "b642b4217b34b1e8d3bd915fc65c4452"
            "?d=http%3A%2F%2Fwww.site.com%2Fstatic%2Fimg%2Fdefault-avatar.png",
        )
def app():
    app = Flask(__name__)
    app.debug = True
    api = Api(app)

    class User(object):
        def __init__(self, name):
            self.name = name

    class Hello(Resource):
        name = "name&required&default='world'"
        date_in = {"validater": "datetime", "input": True, "default": datetime.utcnow}
        date_out = "datetime&required&output"
        schema_inputs = {"get": {"name": name}, "get_user": {"name": name}, "post": {"date": date_in}}
        schema_outputs = {
            "get": {"hello": "unicode&required"},
            "get_user": {"user": {"name": name}},
            "post": {"date": date_out},
        }
        output_types = [User]

        def get(self, name):
            return {"hello": name}

        def get_user(self, name):
            return {"user": User(name)}

        def post(self, date):
            return {"date": date}

    api.add_resource(Hello)
    return app
Beispiel #3
0
    def test_gravatar_url(self):
        """Test that the gravatar url is generated correctly"""
        # Note: We make a fake Flask app for this.
        app = Flask(__name__)

        with app.test_request_context('/'):
            app.debug = True
            url = gravatar_url('*****@*****.**')
            eq_(url,
                'http://www.gravatar.com/avatar/'
                '55502f40dc8b7c769880b10874abc9d0?d=mm')

            url = gravatar_url('*****@*****.**', 200)
            eq_(url,
                'http://www.gravatar.com/avatar/'
                '55502f40dc8b7c769880b10874abc9d0?s=200&d=mm')

            app.debug = False

            url = gravatar_url('*****@*****.**')
            eq_(url,
                'http://www.gravatar.com/avatar/'
                '55502f40dc8b7c769880b10874abc9d0?d=mm')

            app.config['SITE_URL'] = 'http://www.site.com'

            url = gravatar_url('*****@*****.**')
            eq_(url,
                'http://www.gravatar.com/avatar/'
                '55502f40dc8b7c769880b10874abc9d0'
                '?d=http%3A%2F%2Fwww.site.com%2Fstatic%2Fimg%2F'
                'default-avatar.png')
    def setUp(self):
        TB_URI = "http://data.perseus.org/rdfvocab/treebank"

        app = Flask("Nemo")
        app.debug = True
        self.interface = SimpleQuery(
            [
                ("urn:cts:latinLit:phi1294.phi002.perseus-lat2:6.1", "treebanks/treebank1.xml", TB_URI),
                ("urn:cts:latinLit:phi1294.phi002.perseus-lat2:1.5", "treebanks/treebank2.xml", TB_URI),
                ("urn:cts:latinLit:phi1294.phi002.perseus-lat2:6.1", "images/N0060308_TIFF_145_145.tif", "dc:image"),
                ("urn:cts:latinLit:phi1294.phi002.perseus-lat2:6.2", "images/N0060308_TIFF_145_145.tif", "dc:image")
            ],
            resolver=Resolver(LocalRetriever(path="./tests/test_data/"))
        )
        self.arethusa = Arethusa(queryinterface=self.interface)
        app.debug = True
        nemo = Nemo(
            app=app,
            base_url="",
            retriever=NautilusDummy,
            chunker={"default": lambda x, y: level_grouper(x, y, groupby=30)},
            plugins=[self.arethusa]
        )
        self.interface.process(nemo)
        self.client = app.test_client()
Beispiel #5
0
def get_application(generate_css=True, debug=False):
	app = Flask(__name__,
			template_folder='templates',
			static_folder='static',
			static_url_path='',
	)

	from views.index import index_bp
	app.register_blueprint(index_bp)

	if generate_css:
		# force debug because we don't deploy css
		app.debug = True
		app_dir = os.path.dirname(app.static_folder)
		scss.Scss(app,
				static_dir=app.static_folder,
				asset_dir=os.path.join(app_dir, 'assets')
		)

	app.debug = debug

	@app.context_processor
	def context_globals():
		return dict(
			css=css,
		)

	return app
Beispiel #6
0
Datei: main.py Projekt: vddd/rn
def create_app():
    app = Flask(__name__)

    load_config(app)

    app.debug = app.config['DEBUG']
    app.secret_key = app.config['SECRET_KEY']

    # init flask extensions
    db.init_app(app)
    mail.init_app(app)
    login_manager.init_app(app)
    app.context_processor(inject_roles)

    # init my modules
    upload.init_app(app)
    filters.init_app(app)
    views.init_app(app)

    # register routes
    app.register_blueprint(views.bp_basic)
    app.register_blueprint(views.bp_responsable)
    app.register_blueprint(views.bp_activite)
    app.register_blueprint(views.bp_brn)

    return app
Beispiel #7
0
def main():
    app = Flask(__name__)
    app.config.update(
        DB_CONNECTION_STRING=':memory:',
        CACHE_TYPE='simple',
        SQLALCHEMY_DATABASE_URI='sqlite://',
    )
    app.debug = True
    injector = init_app(app=app, modules=[AppModule])

    configure_views(app=app, cached=injector.get(Cache).cached)

    post_init_app(app, injector)

    client = app.test_client()

    response = client.get('/')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.post('/', data={'key': 'foo', 'value': 'bar'})
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.get('/')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.get('/hello')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.delete('/hello')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.get('/')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.get('/hello')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.delete('/hello')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
Beispiel #8
0
def create_app(config_name):
    app = Flask(__name__)
    app.debug = True
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)
    login_manager.init_app(app)
    pagedown.init_app(app)

    db = SQLAlchemy(app)
    bootstrap = Bootstrap(app)
    moment = Moment(app)
    manager = Manager(app)
    mail = Mail(app)
    migrate = Migrate(app, db)
    manager.add_command('db', MigrateCommand)

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

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

    from .api_1_0 import api as api_1_0_blueprint
    app.register_blueprint(api_1_0_blueprint, url_prefix='/api/v1.0')

    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        from flask.ext.sslify import SSLify
        sslify = SSLify(app)

    return app
Beispiel #9
0
def create_app(config, debug=False):
    app = Flask(__name__)
    app.debug = debug
    config_module.init_app(app, config)

    logging.basicConfig(level=logging.DEBUG)

    if app.debug:
        app.config['DEBUG_TB_PROFILER_ENABLED'] = True
        app.config['DEBUG_TB_INTERCEPT_REDIRECTS'] = False
        app.config['DEBUG_TB_PANELS'] = app.config.get('DEBUG_TB_PANELS', [
            'flask_debugtoolbar.panels.versions.VersionDebugPanel',
            'flask_debugtoolbar.panels.timer.TimerDebugPanel',
            'flask_debugtoolbar.panels.headers.HeaderDebugPanel',
            'flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel',
            'flask_debugtoolbar.panels.config_vars.ConfigVarsDebugPanel',
            'flask_debugtoolbar.panels.template.TemplateDebugPanel',
            'flask_debugtoolbar.panels.logger.LoggingPanel',
            'flask_debugtoolbar.panels.profiler.ProfilerDebugPanel',
        ])
        app.toolbar = DebugToolbarExtension(app)

    for blueprint in blueprints:
        blueprint.init_app(app)

    if app.debug:
        run_bower_list()

    return app
Beispiel #10
0
def create_app(config_name = 'default'):
    app = Flask(__name__, static_folder='static', static_url_path='')
    app.config.from_object(config[config_name])
    app.debug = True
    config[config_name].init_app(app)

    db.init_app(app)

    # attach routes and custom error pages here
    from hacer.api import api as api_blueprint
    app.register_blueprint(api_blueprint, url_prefix='/api')

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

    # start discovery server
    with app.app_context():
        from discovery import run_discovery_server
        app.discovery_thread = Thread(target=run_discovery_server, kwargs={ "Session": scoped_session(sessionmaker(bind=db.engine)) })
        app.discovery_thread.daemon = True
        app.discovery_thread.start()

    app.before_request(create_before_request(app))
    return app
Beispiel #11
0
def create_app(debug=False):

    app = Flask(__name__)
    app.debug = debug
    app.config['SECRET_KEY'] = 'secret'

    @app.route('/')
    def index():
        doc = BootstrapDocument()
        # add socket-io client to the doc and our custom js.
        doc.scripts.add(script(
            src='//cdn.socket.io/socket.io-1.4.5.js',
            type='text/javascript'),
            script(src='/static/my.js',
                type='text/javascript'))

        doc.body.children.insert(0, Div(h1('Advanced Example'), 
            Div(h3('Flashes'), Div(id='flashes')))) 
        
        # add buttons below the content of the document
        doc.body.add(Button(
            'Table',
            onclick="user_socket.emit('table');"),
            Button('Form',
                onclick="user_socket.emit('form');"))

        return doc.render()


    io.init_app(app)
    user_io.init_io(io)
    return app
Beispiel #12
0
def serve(py_exec=None):
    parser = argparse.ArgumentParser()
    parser.add_argument("--python", default="python")
    args = parser.parse_args()

    py_exec = args.python

    app = Flask("touchandgo")

    @app.route("/<name>")
    @app.route("/<name>/<season>/<episode>")
    def redirect_to(name, season=None, episode=None):
        interface = get_interface()
        command = "%s touchandgo.py \"%s\" " % (py_exec, name)
        if season is not None:
            command += "%s %s " % (season, episode)
        command += "--daemon"
        print command
        process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT)
        sleep(10)
        port = 8888
        return redirect("http://%s:%s" % (interface, port))

    app.debug = True
    app.run(host="0.0.0.0")
Beispiel #13
0
def create_app(ignore_exceptions=None, debug=False, **config):
    import os

    app = Flask(__name__)
    app.config['SECRET_KEY'] = os.urandom(40)
    for key, value in config.items():
        app.config[key] = value

    app.debug = debug

    if ignore_exceptions:
        app.config['RAVEN_IGNORE_EXCEPTIONS'] = ignore_exceptions

    @app.route('/an-error/', methods=['GET', 'POST'])
    def an_error():
        raise ValueError('hello world')

    @app.route('/capture/', methods=['GET', 'POST'])
    def capture_exception():
        try:
            raise ValueError('Boom')
        except:
            current_app.extensions['sentry'].captureException()
        return 'Hello'

    @app.route('/message/', methods=['GET', 'POST'])
    def capture_message():
        current_app.extensions['sentry'].captureMessage('Interesting')
        return 'World'

    @app.route('/login/', methods=['GET', 'POST'])
    def login():
        login_user(User())
        return "hello world"
    return app
Beispiel #14
0
def create_app(config, debug=True):
    app = Flask(__name__)
    app.debug = debug
    app.config['SECRET_KEY'] = 'secret'
    app.config['SECURITY_POST_LOGIN_VIEW'] = '/profile'

    from tests.test_app.config import Config
    app.config.from_object(Config)

    if config:
        for key, value in config.items():
            app.config[key] = value

    app.wsgi_app = HTTPMethodOverrideMiddleware(app.wsgi_app)

    @app.route('/')
    def index():
        return render_template('index.html', content='Home Page')

    @app.route('/profile')
    @login_required
    def profile():
        twitter = current_app.social.twitter
        twitter.get_api()

        return render_template(
            'profile.html',
            content='Profile Page',
            twitter_conn=twitter.get_connection(),
            google_conn=current_app.social.google.get_connection(),
            facebook_conn=current_app.social.facebook.get_connection(),
            foursquare_conn=current_app.social.foursquare.get_connection())

    return app
Beispiel #15
0
def main():
    app = Flask(__name__)
    app.config.update(DB_CONNECTION_STRING=':memory:', SQLALCHEMY_DATABASE_URI='sqlite://')
    app.debug = True

    injector = Injector([AppModule(app)])
    configure_views(app=app)

    FlaskInjector(app=app, injector=injector)

    client = app.test_client()

    response = client.get('/')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.post('/', data={'key': 'foo', 'value': 'bar'})
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.get('/')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.get('/hello')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.delete('/hello')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.get('/')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.get('/hello')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
    response = client.delete('/hello')
    print('%s\n%s%s' % (response.status, response.headers, response.data))
Beispiel #16
0
def test_content_type(sign_func):
    responses.add(responses.GET, "https://flask.atlassian.net/")

    app = Flask(__name__)
    app.secret_key = "anything"
    app.debug = True
    backend = MemoryBackend({
        "oauth_token": "faketoken",
        "oauth_token_secret": "fakesecret",
        "oauth_session_handle": "fakehandle",
        "oauth_expires_in": "157680000",
        "oauth_authorization_expires_in": "160272000",
    })
    jira_bp = make_jira_blueprint(
        "https://flask.atlassian.net",
        consumer_key="fakekey",
        backend=backend,
    )
    app.register_blueprint(jira_bp)

    @app.route("/test")
    def api_request():
        jira_bp.session.get("/")
        return "success"

    resp = app.test_client().get("/test")
    headers = responses.calls[0].request.headers
    assert "Content-Type" in headers
    assert headers["Content-Type"] == "application/json"
Beispiel #17
0
def start():
    """start the flask service"""

    # create app
    app = Flask(__name__)
    app.debug = True


    #Data comes into this method:
    #'sessionStartTime' is the number of seconds since 1970 when the experiment started
    #'data' is the latest raw data, served up as a csv (each line contains up to 8 channels)
    @app.route('/data', methods=['POST'])
    def saveRatingsToGene():
        print "starting"
        print request.form

        data = request.form['data']
        sessionStartTime = request.form['sessionStartTime']

        #Do we already have a DB entry for this?
        experiment_obj = db.experiments.find_one({"sessionStartTime": sessionStartTime})

        #The data is coming in as a text CSV.
        rows = data.split('\n')
        for row in rows:
            channels = row.split(',')
            #somehow put this data into a mongo object


        return "OK"

    #This server must expose URLs to allow the user to dload the csv from the server
    #Flask gives us what we need to dload files. This sample code might be overly complicated
    #As it is built for streaming large files, which we don't necessarily need
    #http://flask.pocoo.org/docs/patterns/streaming/
    @app.route('/large.csv')
    def generate_large_csv():
        def generate():
            for row in iter_all_rows():
                yield ','.join(row) + '\n'
        return Response(generate(), mimetype='text/csv')

    # This is where we should be able to display a list of all experiments in the mongodb
    # And use them to fill in a template (.tpl file) to allow either dloaded files
    # or perhaps, even visualized on the screen
    # Very excited about this plotting library (if it's easy to implement):
    # http://code.shutterstock.com/rickshaw/
    @app.route('/', methods=['GET'])
    def hello_world():

        experiments = db.experiments.find() #get all

        for experiment in experiments:
            print "Yep we see an experiment"

        print "yep working"


    # let's go!
    app.run()
def create_app():
    app = Flask(__name__,
        static_folder=os.path.join(PROJECT_ROOT, 'public'),
        static_url_path='/public')

    app.config.update(os.environ)

    #TODO: read in right hand side from HT config vars
    app.config['SECRET_KEY'] = 'secret'
    app.config['SECURITY_PASSWORD_HASH'] = 'bcrypt'
    app.config['MONGODB_DB'] = 'flask_security_test'
    app.config['MONGODB_HOST'] = 'localhost'
    app.config['MONGODB_PORT'] = 27017

    app.debug = app.config['X_HT_DEBUG'] == "True"

    app.wsgi_app = SharedDataMiddleware(app.wsgi_app, 
        {'/': os.path.join(os.path.dirname(__file__), 'public') })

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html'), 404

    SecuritySetup(app)

    # import & register blueprints here:
    #===================================
    from hero_tmpl.views.security import security
    app.register_blueprint(security)

    from hero_tmpl.views.misc import misc
    app.register_blueprint(misc)

    return app
Beispiel #19
0
def app_init(cfg='../config.py'):
    ''' Initialises the flask app. '''

    app        = Flask( __name__, static_folder=os.path.abspath('static'))
    app.register_blueprint(API, url_prefix='/api')
    app.config.from_pyfile(cfg)
    app.debug      =   app.config.get('DEBUG')
    app.secret_key = app.config.get('SECRET_KEY')
    oauth = OAuth()

    '''GOOGLE_CLIENT_ID = conf.GOOGLE_CLIENT_ID
    GOOGLE_CLIENT_SECRET = conf.GOOGLE_CLIENT_SECRET
    '''

    google = oauth.remote_app('google',
      base_url='https://www.google.com/accounts/',
      authorize_url='https://accounts.google.com/o/oauth2/auth',
      request_token_url=None,
      request_token_params={
        'scope': 'https://www.googleapis.com/auth/userinfo.email',
        'response_type': 'code'},
      access_token_url='https://accounts.google.com/o/oauth2/token',
      access_token_method='POST',
      access_token_params={'grant_type': 'authorization_code'},
      consumer_key=app.config.get('GOOGLE_CLIENT_ID'),
      consumer_secret=app.config.get('GOOGLE_CLIENT_SECRET'))

    return app, google
def create_app(config, debug=False, testing=False, config_overrides=None):
  app = Flask(__name__)
  app.config.from_object(config)

  app.debug = debug
  app.testing = testing

  if config_overrides:
    app.config.update(config_overrides)

  #Configure logging
  if not app.testing:
    logging.basicConfig(level=logging.INFO)

  #Setup the data model
  with app.app_context():
    model = get_model()
    model.init_app(app)

  from .app import appview
  app.register_blueprint(appview, url_prefix='')

  @app.errorhandler(500)
  def server_error(e):
    return """
    An internal error occurred:<pre>{}</pre>
    """.format(e), 500

  return app
Beispiel #21
0
def app():
    app = Flask(__name__)
    app.debug = True
    app.testing = True

    @app.context_processor
    def expose_current_timestamp():
        return {
            'now': datetime.now(),
        }

    @app.route('/naturalday')
    def naturalday():
        return render_template_string("{{ now|humanize('naturalday') }}")

    @app.route('/naturaltime')
    def naturaltime():
        return render_template_string("{{ now|humanize('naturaltime') }}")

    @app.route('/naturaldelta')
    def naturaldelta():
        return render_template_string("{{ value|humanize('naturaldelta') }}",
                                      value=timedelta(days=7))

    return app
Beispiel #22
0
def app(jwt, user):
    app = Flask(__name__)
    app.debug = True
    app.config['SECRET_KEY'] = 'super-secret'
    app.config['JWT_EXPIRATION_DELTA'] = timedelta(milliseconds=200)

    jwt.init_app(app)

    @jwt.authentication_handler
    def authenticate(username, password):
        if username == user.username and password == user.password:
            return user
        return None

    @jwt.user_handler
    def load_user(payload):
        if payload['user_id'] == user.id:
            return user

    @app.route('/protected')
    @flask_jwt.jwt_required()
    def protected():
        return 'success'

    return app
Beispiel #23
0
def create_app():
    app = Flask(__name__)
    app.debug = os.getenv('DEBUG') == 'True'
    if os.getenv('SENTRY_DSN'):
        sentry = Sentry()
        sentry.init_app(app)
    return app
    def test(config):
        """Test the given Flask configuration. If configured correctly,
        an error will be tracked by Exceptional for your app. Unlike
        the initialized extension, this test will post data to Exceptional,
        regardless of the configured ``DEBUG`` setting.

        :param config: The Flask application configuration object to test.
                       Accepts either :class:`flask.Config` or the object
                       types allowed by :meth:`flask.Config.from_object`.
        """
        context = getattr(stack.top, "exceptional_context", None)
        app = Flask(__name__)
        exceptional = Exceptional()

        if isinstance(config, Config):
            app.config = config
        else:
            app.config.from_object(config)

        assert "EXCEPTIONAL_API_KEY" in app.config
        app.debug = False
        app.testing = False
        exceptional.init_app(app)
        app.testing = True

        @app.route("/exception")
        def exception():
            setattr(stack.top, "exceptional_context", context)
            message = "Congratulations! Your application is configured for Exceptional error tracking."  # NOQA

            raise Exception(message)

        with app.test_client() as client:
            client.get("/exception")
            json.loads(g.exceptional)
Beispiel #25
0
def test_config():
    app = Flask(__name__)
    app.config.from_object("testdata.config")
    app.debug = True
    configs = ["resource_json", "permission_json", "auth_header",
               "auth_token_name", "auth_secret", "auth_alg", "auth_exp",
               "resjs_name", "resdocs_name", "bootstrap"]
    bp = Blueprint("blueprint", __name__)
    api_bp = Api(bp)
    api_app = Api(app)
    api_no_app = Api()
    for k in configs:
        key = "API_" + k.upper()
        assert key in app.config
        assert app.config[key] == key
        assert hasattr(api_app, k)
        assert getattr(api_app, k) == key

        assert getattr(api_no_app, k) != key
        # inited with blue_print can't load configs
        assert getattr(api_bp, k) != key

    api_bp.config(app.config)
    for k in configs:
        key = "API_" + k.upper()
        assert getattr(api_bp, k) == key
Beispiel #26
0
def create_api():
    class Hello(Resource):
        schema_inputs = {
            "get": {"name": ("name&required&default='world'", "name")},
            "post_login": {"date": ("date&required", "date")},
        }
        hello = {"hello": "unicode&required"}
        schema_outputs = {
            "get": hello,
            "get_error": hello,
            "post_login": hello,
        }

        def get(self, name):
            return {"hello": name}

        def get_error(self):
            raise ValueError("get_error")

        def post_login(self, date):
            return {"hello": "world"}

    app = Flask(__name__)
    app.debug = True
    api = Api(app)
    api.add_resource(Hello)

    return api
Beispiel #27
0
def create_app(config_filename=None):
    app = Flask(__name__, instance_relative_config=True)
    if app.config.from_pyfile("settings.conf", silent=True):
        print "Settings loaded from local instance"
    if app.config.from_envvar("RSVP_CONF", silent=True):
        print "Settings loaded from ENVVAR"
    if app.config["DEBUG"]:
        app.debug = True

    log_formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
    root_logger = logging.getLogger("werkzeug")
    if app.config["DEBUG"]:
        root_logger.setLevel(logging.DEBUG)
    file_handler = logging.FileHandler("{}/{}".format(app.config["LOGDIR"], "rsvp.log"))
    file_handler.setFormatter(log_formatter)
    root_logger.addHandler(file_handler)
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(log_formatter)
    root_logger.addHandler(console_handler)

    from extensions import db
    import models
    db.init_app(app)
    models.create_all(app)

    from views import views_bp
    app.register_blueprint(views_bp)
    return app
Beispiel #28
0
def run_flask():
    root_dir = os.path.join(os.getcwd(), 'web')
    app = Flask(__name__, static_folder=root_dir)
    app.use_reloader = False
    app.debug = False
    app.config["SECRET_KEY"] = "OpenPoGoBot"
    socketio = SocketIO(app, logging=False, engineio_logger=False)

    logging_buffer = []

    @app.route("/")
    def index():
        return app.send_static_file("index.html")

    @app.route('/<path:path>')
    def static_proxy(path):
        return app.send_static_file(path)

    @manager.on("logging")
    def logging_event(event_name, output, color):
        line = {"output": output, "color": color}
        logging_buffer.append(line)
        socketio.emit("logging", [line], namespace="/event")

    @socketio.on("connect", namespace="/event")
    def connect():
        emit("logging", logging_buffer, namespace="/event")
        logger.log("Client connected", "yellow", fire_event=False)

    @socketio.on("disconnect", namespace="/event")
    def disconnect():
        logger.log("Client disconnected", "yellow", fire_event=False)

    socketio.run(app, host="0.0.0.0", port=8000, debug=False, use_reloader=False, log_output=False)
def test_parse_schema():
    hello = {"hello": "safestr&required"}
    sche_inputs = {
        "get": {"name": "name&default='world'"},
        "post_login": {
            "name": "name&default='world'",
            "password": "******"
        }
    }
    sche_outputs = {
        "get": hello,
        "post_login": hello
    }

    class Hello(Resource):

        schema_inputs = sche_inputs
        schema_outputs = sche_outputs
        output_types = [Flask]

        def get(self, name):
            pass

        def post_login(self, name, password):
            pass

    app = Flask(__name__)
    app.debug = True
    api = Api(app)
    api.add_resource(Hello)

    assert Hello.schema_inputs == validater.parse(sche_inputs)
    assert Hello.schema_outputs == validater.parse(sche_outputs)
    assert Hello.output_types == [Flask]
Beispiel #30
0
def app(urs, user):
    app = Flask(__name__)
    app.debug = True
    app.config['SECRET_KEY'] = 'super-secret'
    app.config['JWT_EXPIRATION_DELTA'] = timedelta(milliseconds=600)
    app.config['JWT_EXPIRATION_LEEWAY'] = timedelta(milliseconds=5)

    urs.init_app(app)

    @app.route('/protected')
    @flask_urs.jwt_required()
    def protected():
        return 'success'

    @app.route("/authorize")
    def authorize():
        return jsonify({
            "access_token": "asdf",
            "refresh_token": "asdf",
            "endpoint": "/endpoint"
        })

    @app.route("/endpoint")
    def endpoint():
        return jsonify(user)

    # Establish an application context before running the tests.
    ctx = app.app_context()
    ctx.push()

    def teardown():
        ctx.pop()

    return app
Beispiel #31
0
#Testing Git
from flask import Flask, request, render_template
import time
import datetime
import arrow

app = Flask(__name__)
app.debug = True  # Make this False if you are no longer debugging

#@app.route("/")
#def hello():
#    return "Jason, you are soooo awesome!"


@app.route("/")
#@app.route("/lab_temp")
def lab_temp():
    import Adafruit_DHT as DHT
    import RPi.GPIO as GPIO
    import sys

    Sensor = 11
    humiture = 17

    #humidity, temperature = DHT.read_retry(Sensor, humiture)

    # If you don't have a sensor but still wish to run this program, comment out all the
    # sensor related lines, and uncomment the following lines (these will produce random
    # numbers for the temperature and humidity variables):
    import random
    humidity = random.randint(1, 100)
Beispiel #32
0
from flask import Flask, render_template
app3 = Flask(__name__)##creates an instance of a flask and instatiates its name

@app3.route("/")

def hello_world():
    return "No hablo queso-v3"

coll = [1, 3, 3, 7]

@app3.route("/my_first_template")
def tet_template():
    return render_template("foo.html", foo = "SILENCIO", fool=coll)

    
if __name__=="__main__":
        app3.debug = True
        app3.run()
        
Beispiel #33
0
from flask import Flask
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager

import src.config as config
from src.extensions import db

app = Flask(__name__)
app.debug = config.DEBUG
app.config["SQLALCHEMY_DATABASE_URI"] = config.DB_URI
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = config.SQLALCHEMY_TRACK_MODIFICATIONS

db.init_app(app)

migrate = Migrate(app, db)
manager = Manager(app)
manager.add_command("db", MigrateCommand)

if __name__ == "__main__":
    manager.run()
Beispiel #34
0
from flask import Flask, render_template, redirect, url_for, flash, jsonify
from flask_debugtoolbar import DebugToolbarExtension
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField, FloatField, BooleanField, TextAreaField, RadioField
from wtforms.validators import InputRequired, Optional, URL, NumberRange
import requests
import os
import websiteconfig

PLACEHOLDER_IMG = "https://image.freepik.com/free-vector/unicorn-background-design_1324-79.jpg"

app = Flask(__name__)

app.debug = websiteconfig.DEBUG
app.config['SECRET_KEY'] = "abc123"
app.pf_api_key = websiteconfig.pf_api_key
toolbar = DebugToolbarExtension(app)

DB = "postgresql://localhost/adopt"

app.config['SQLALCHEMY_DATABASE_URI'] = DB
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SQLALCHEMY_ECHO'] = True

db = SQLAlchemy(app)


class Pet(db.Model):
    __tablename__ = 'pets'
Beispiel #35
0
import os
from flask import Flask
from app.routes import blueprint
from app.spiders import tjal, tjms

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

app = Flask(__name__, instance_relative_config=True)

app.register_blueprint(blueprint)
app.debug = os.environ.get('DEBUG', True)

app.port = os.environ.get('PORT', 5000)
app.host = os.environ.get('HOST', '0.0.0.0')

AGENTS = os.path.join(BASE_DIR, 'app', 'agents.txt')

app.config["JSONIFY_MIMETYPE"] = "application/json; charset=utf-8"

app.config['SPIDERS'] = {'tjal': tjal.TjAl(), 'tjms': tjms.TjMs()}
app.config['celery'] = {
    'imports': ('app.tasks', ),
    'task_serializer': 'json',
    'result_serializer': 'json',
    'accept_content': ['json'],
}


def create_app(app, config_extra={}):
    app.config.update(config_extra)
    return app
Beispiel #36
0
import numpy as np
import plotly.graph_objs as go

import plotly
import json
from flask_sqlalchemy import SQLAlchemy
import plotly.graph_objs as go
from sqlalchemy.sql import func

app = Flask(__name__)
app.secret_key = 'key'

ENV = 'dev'

if ENV == 'dev':
    app.debug = True
    app.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://*****:*****@localhost/postgres'
else:
    app.debug = False
    app.config[
        'SQLALCHEMY_DATABASE_URI'] = 'postgres://*****:*****@ec2-23-21-249-0.compute-1.amazonaws.com:5432/dfc1evd9hjiukk'

app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)


class ormStudent(db.Model):
    __tablename__ = 'Students'

    student_email = db.Column(db.String(30), primary_key=True)
Beispiel #37
0
app.route('/restaurant/<int:restaurant_id>/edit')
def editRestaurant():
    '"This page is used to edit a restaurant"'

app.route('/restaurant/<int:restaurant_id>/delete')
def deleteRestaurant():
     '"This page is used to delete a restaurant "'

app.route('/restaurant/<int:restaurant_id>')
app.route('/restaurant/<int:restaurant_id/menu>')
def showMenu():
     '"This page is used to show menu items in a restaurant"'

app.route('/restaurant/<int:restaurant_id/menu/new>')
def newMenuItem():
     '"This page is used to add new menu items in a restaurant"'

app.route('/restaurant/<int:restaurant_id/menu/menu_id/edit>')
def editMenuItem():
     '"This page is used to edit menu items in a restaurant"'

app.route('/restaurant/<int:restaurant_id/menu/menu_id/delete>')
def deleteMenuItem():
     '"This page is used to show menu items in a restaurant'''



if __name__ =='__main__':
    app.debug =True
    app.run(host = '0.0.0.0', port = 8080)
Beispiel #38
0
    }, {
        'name': '猪八戒',
        'age': 23
    }, {
        'name': '不知火舞',
        'age': 25
    }, {
        'name': '程咬金',
        'age': 29
    }, {
        'name': '达摩',
        'age': 24
    }, {
        'name': '不知好歹',
        'age': 25
    }, {
        'name': '玄策',
        'age': 27
    }, {
        'name': '百里守约',
        'age': 26
    }]
    return render_template('test.html', dict=dic, stu=stu)


if __name__ == '__main__':
    print('静态文件硬盘地址:', app.static_folder)  # 静态文件在硬盘上的绝对路径
    print('静态文件url:', app.static_url_path)  # 静态文件在网首页上的url地址
    app.debug = True  # 也可以写在run()中
    app.run(host='127.0.0.1', port='8000')
Beispiel #39
0
@application.route('/api/v1/train', methods=['POST'])
@cross_origin(origin='localhost', headers=['Content- Type', 'Authorization'])
def train_model():
    try:
        authentic_uris = request.get_json()["signatures"]
        name = request.get_json()["name"]
        forged_uris = forger.forge_name(name)
        return train.train(authentic_uris, forged_uris)
    except Exception as e:
        return data_not_found(e)


@application.route('/api/v1/verify', methods=['POST'])
@cross_origin(origin='localhost', headers=['Content- Type', 'Authorization'])
def verify_sig():
    try:
        signature = request.get_json()["signature"]
        uuid = request.get_json()["uuid"]
        return verify.verify(uuid, signature)
    except Exception as e:
        return data_not_found(e)


if __name__ == "__main__":
    # Setting debug to True enables debug output. This line should be
    # removed before deploying a production app.
    application.debug = True
    CORS(application)
    application.run(host="0.0.0.0", port=80, threaded=True)
Beispiel #40
0
from flask import Flask, request, session, g, url_for, abort, render_template, make_response, redirect, app
import math, re, sys
#from werkzeug.contrib.cache import MemcachedCache
#from __init__ import buf
import redis
from flask_caching import Cache

#cache = Cache(config={'CACHE_TYPE': 'simple'})
#from werkzeug.contrib.cache import SimpleCache
#cache = SimpleCache()

app = Flask(__name__)
#cache.init_app(app)
app.debug = 1
application = app


def get_resource_as_string(name, charset='utf-8'):
    with app.open_resource(name) as f:
        return f.read().decode(charset)


app.jinja_env.globals['get_resource_as_string'] = get_resource_as_string
r = redis.StrictRedis(host='localhost', port=6379, db=0)


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

from flask import Flask, request, render_template
import plivohelper
import os

response_server = Flask("ResponseServer")
response_server.debug = True



@response_server.errorhandler(404)
def page_not_found(error):
    """error page"""
    print "404 page not found"
    return 'This URL does not exist', 404

@response_server.route('/ringing/', methods=['GET', 'POST'])
def ringing():
    """ringing URL"""
    # Post params- 'to': ringing number, 'request_uuid': request id given at the time of api call
    print "We got a ringing notification"
    return "OK"

@response_server.route('/hangup/', methods=['GET', 'POST'])
def hangup():
    """hangup URL"""
    # Post params- 'request_uuid': request id given at the time of api call,
    #               'CallUUID': unique id of call, 'reason': reason of hangup
    print "We got a hangup notification"
    return "OK"

@response_server.route('/redirected/', methods=['GET', 'POST'])
Beispiel #42
0
from models import Garage, GarageEntry
from bs4 import BeautifulSoup
from requests import get
from email_helper import send_email
from mongoengine import connect
from flask_cors import CORS
from datetime import datetime
from urllib.parse import urlparse
from flask_talisman import Talisman
from dotenv import load_dotenv

load_dotenv(verbose=True)

app = Flask(__name__, template_folder='./dist', static_folder='./dist/static')
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = True
app.debug = os.getenv('DEBUG') == 'TRUE'

SCRAPE_URL = 'http://secure.parking.ucf.edu/GarageCount/'
SERVER_KEY = os.getenv('SERVER_KEY')

CORS(app)

if not app.debug:
    # Transforms all http requests to https
    Talisman(app, content_security_policy=None)

connect(host=os.getenv('DATABASE_HOST'), alias='default')


def jsonify_error(msg, error_code):
    return jsonify({'error': msg}), error_code
Beispiel #43
0
                                     Length(min=2, max=55)])
    password_confirm = PasswordField(
        "Confirm Password",
        validators=[DataRequired(),
                    Length(min=4, max=15),
                    EqualTo('pword')])
    submit = SubmitField("Register Now")

    #Check that uname doesn't already exist
    def validate_uname(self, uname):
        for user, user_info in userList.items():
            for user_key in user_info:
                if user_key == "uname":
                    if user_info[user_key] == uname:
                        self.errors.append(
                            "Username is already in use. Pick another one.")
                        #raise ValidationError("Username is already in use. Pick another one.")


class SpellCheckForm(FlaskForm):
    inputtext = StringField(
        "Enter Text to Spell Check",
        validators=[DataRequired(), Length(min=2, max=5000)])
    check_spelling = SubmitField("Check Spelling")


# Run with Debug? -----------------------------------------------------------------------------------------------------------------
if __name__ == "__main__":
    app.debug = False
    app.run()
Beispiel #44
0
# coding: utf-8
from flask import Flask

from config import CONFIG
from src.commons.utils import init_logger
from src.blueprint import (LOAD_API_BLUEPRINT)
from src.blueprint.blueprint_utils import flask_constructor_error

import src.requests as req

logging_config = CONFIG[u"logging"]
init_logger(logging_config[u'pattern'], logging_config[u'pattern_debug'],
            logging_config[u"level"])

# create flask server
APP = Flask(__name__)
APP.debug = CONFIG[u"app"][u"debug"]
APP.register_blueprint(LOAD_API_BLUEPRINT, url_prefix=u'/api')


@APP.errorhandler(404)
def page_not_found(e):
    return flask_constructor_error(u"Not Found", 404, 404)


if __name__ == u"__main__":
    APP.run(threaded=True, port=5000, debug=True)
Beispiel #45
0
import app_config
import app_utils
import datetime
import logging
import static

from app_utils import comma_filter, percent_filter, open_db, close_db, never_cache_preview
from flask import Flask, make_response, render_template
from flask_admin import Admin
from flask_admin.contrib.peewee import ModelView
from models import models
from render_utils import make_context, smarty_filter, urlencode_filter
from werkzeug.debug import DebuggedApplication

app = Flask(__name__)
app.debug = app_config.DEBUG
secrets = app_config.get_secrets()
app.secret_key = secrets.get('FLASK_SECRET_KEY')

app.add_template_filter(comma_filter, name='comma')
app.add_template_filter(percent_filter, name='percent')

try:
    file_handler = logging.FileHandler('%s/admin_app.log' % app_config.SERVER_LOG_PATH)
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
except IOError:
    print('Could not open %s/admin_app.log, skipping file-based logging' % app_config.SERVER_LOG_PATH)

app.logger.setLevel(logging.INFO)
Beispiel #46
0
    except Exception as e:
        return json.dumps({"error": {"message": "Server was unable to connect to Epitech's intra API", "code": 500}}), 500

@app.route('/favicon.ico', methods=['POST', 'GET'])
def favicon():
    track_event(category='Favicon', action=request.method)
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'favicon.ico', mimetype='image/vnd.microsoft.icon')

@app.route('/wakeup', methods=['POST', 'GET'])
def wake_up():
    track_event(category='WakeUp', action=request.method)
    return ("OK")

@app.after_request
def after_request(response):
    response.headers.add("Access-Control-Allow-Credentials", "true")
    response.headers.add('Access-Control-Allow-Origin', '*')
    response.headers.add("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, PATCH, DELETE")
    response.headers.add('Access-Control-Allow-Headers',"Origin, X-Requested-With, Content-Type, Accept")
    response.headers.add('Content-Type','application/json')
    return response

if __name__ == '__main__':
    try:
        app.debug = debug
        app.run(port=listen_port, host=listen_host, threaded=True)
    except Exception as e:
        if debug:
            log_file(e)
Beispiel #47
0
from flask import Flask

fill_up = Flask(__name__)


@fill_up.route("/")
def homepage():
    return ("Hello! This is '/', route 1 of 3")


@fill_up.route("/two")
def two():
    return ("Hello! This is '/two', route 2 of 3")


@fill_up.route("/three")
def three():
    return ("Hello! This is '/three', route 3 of 3")


if __name__ == "__main__":
    fill_up.debug = True
    fill_up.run()
if ENV_FILE:
    load_dotenv(ENV_FILE)

AUTH0_CALLBACK_URL = env.get(constants.AUTH0_CALLBACK_URL)
AUTH0_CLIENT_ID = env.get(constants.AUTH0_CLIENT_ID)
AUTH0_CLIENT_SECRET = env.get(constants.AUTH0_CLIENT_SECRET)
AUTH0_DOMAIN = env.get(constants.AUTH0_DOMAIN)
AUTH0_AUDIENCE = env.get(constants.AUTH0_AUDIENCE)
AUTH0_MANAGEMENT_JWT = env.get(constants.MANAGEMENT_JWT)

if AUTH0_AUDIENCE is '':
    AUTH0_AUDIENCE = 'https://' + AUTH0_DOMAIN + '/userinfo'

APP = Flask(__name__, static_url_path='/public', static_folder='./public')
APP.secret_key = constants.SECRET_KEY
APP.debug = True


# Format error response and append status code.
class AuthError(Exception):
    def __init__(self, error, status_code):
        self.error = error
        self.status_code = status_code


@APP.errorhandler(AuthError)
def handle_auth_error(ex):
    response = jsonify(ex.error)
    response.status_code = ex.status_code
    return response
from flask import Flask, redirect, url_for, session, request, jsonify, Markup
from flask import render_template

app = Flask(__name__)

app.debug = True  #Change this to False for production


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


@app.route('/update_div1')
def update():
    return Markup('<p>This text came from le server!</p>')


if __name__ == '__main__':
    app.run()
Beispiel #50
0
def create_app(node_id: str,
               debug=False,
               n_replica=None,
               test_config=None) -> Flask:
    """Create flask application.

    Args:
         node_id: ID used to identify this node.
         debug: debug mode flag.
         n_replica: Number of model replicas used for fault tolerance purposes.
         test_config: database test settings.
    Returns:
         app : Flask App instance.
    """
    app = Flask(__name__)
    app.debug = debug

    app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY", None)

    if app.config["SECRET_KEY"] is None:
        app.config["SECRET_KEY"] = DEFAULT_SECRET_KEY
        logging.warning(
            "Using default secrect key, this is not safe and should be used only for testing and development. To define a secrete key please define the environment variable SECRET_KEY."
        )

    app.config["N_REPLICA"] = n_replica
    sockets = Sockets(app)

    # Register app blueprints
    from .main import (
        auth,
        data_centric_routes,
        hook,
        local_worker,
        main_routes,
        model_centric_routes,
        ws,
    )

    # set_node_id(id)
    local_worker.id = node_id
    hook.local_worker._known_workers[node_id] = local_worker
    local_worker.add_worker(hook.local_worker)

    # Register app blueprints
    app.register_blueprint(main_routes, url_prefix=r"/")
    app.register_blueprint(model_centric_routes, url_prefix=r"/model-centric")
    app.register_blueprint(data_centric_routes, url_prefix=r"/data-centric")

    sockets.register_blueprint(ws, url_prefix=r"/")

    # Set SQLAlchemy configs
    set_database_config(app, test_config=test_config)
    s = app.app_context().push()
    db.create_all()
    db.session.commit()

    # Set Authentication configs
    app = auth.set_auth_configs(app)

    CORS(app)

    # Threads
    executor.init_app(app)
    app.config["EXECUTOR_PROPAGATE_EXCEPTIONS"] = True
    app.config["EXECUTOR_TYPE"] = "thread"

    return app
Beispiel #51
0
import json
import random

from google.appengine.api import users
from flask import Flask, request, render_template, redirect

# Import code from our own files:
from user import UserProfile
from puzzleSequenceLogic import userCompletedPuzzle

# make the flask app:
app = Flask(__name__)

# Set up debug/error logging, when not running "for real" on Google App Engine:
if not os.getenv('SERVER_SOFTWARE').startswith('Google App Engine/'):
    app.debug = True  # with this setting on, the cause of Python errors is displayed in App Engine logs.


# when the user goes to home page, redirect to static welcome page
@app.route('/')
def home():
    return redirect('/resources/welcome.html')


# when the user goes to /next, automatically redirect them to their current puzzle.
@app.route('/next')
def nextStep():
    profile = UserProfile.get_by_user(users.get_current_user())
    return redirect(profile.current_puzzle)