Example #1
0
def create_app():
    app = Flask(__name__)
    # Set crucial variables
    app.secret_key = os.environ['SECRET_KEY']
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']

    # Set non crucial variables
    app.config['MAILGUN_API_URL'] = os.environ.get('MAILGUN_API_URL', '')
    app.config['MAILGUN_API_KEY'] = os.environ.get('MAILGUN_API_KEY', '')
    app.config['MAILGUN_TEST_OPTION'] = True if os.environ.get('MAILGUN_TEST_OPTION', 'True') == 'True' else False
    app.config['NOTIFICATION_EMAIL'] = os.environ.get('MAILGUN_SMTP_LOGIN', '')
    app.config['REDDIT_PASSWORD'] = os.environ.get('WPC_REDDIT_PASSWORD', '')
    app.config['REDDIT_USERNAME'] = os.environ.get('WPC_REDDIT_USERNAME', '')
    app.config['YOUTUBE_KEY'] = os.environ.get('WPC_YOUTUBE_KEY', '')
    app.config['GA_TRACKING_CODE'] = os.environ.get('GA_TRACKING_CODE', '')
    app.config['REDDIT_API_ID'] = os.environ.get('WPC_APP_ID', '')
    app.config['REDDIT_API_SECRET'] = os.environ.get('WPC_APP_SECRET', '')
    app.config['RTMP_LOGIN'] = os.environ.get('RTMP_LOGIN', '')
    app.config['RTMP_PASSWORD'] = os.environ.get('RTMP_PASSWORD', '')
    app.config['RTMP_SERVER'] = os.environ.get('RTMP_SERVER', '127.0.0.1')
    app.config['SERVER_NAME'] = os.environ.get('SERVER_NAME', '')

    app.config['REDDIT_WEB_APP_USER_AGENT'] = "/r/WatchPeopleCode web app(main contact: /u/godlikesme)"
    app.config['REDDIT_BOT_USER_AGENT'] = "/r/WatchPeopleCode flairs&streams bot (main contact: /u/godlikesme)"

    Bootstrap(app)
    loggers_and_levels = [(app.logger, logging.INFO),
                          (logging.getLogger('sqlalchemy'), logging.WARNING),
                          (logging.getLogger('apscheduler.scheduler'), logging.INFO)]
    setup_logging(loggers_and_levels, logentries_id=os.environ.get('LOGENTRIES_ID', None))

    app.logger.info("App created!")

    return app
Example #2
0
    def create_app(self):
        app = Flask(__name__)
        app.config['TESTING'] = True
        app.config['SERVER_NAME'] = 'localhost'
        app.config['SECRET_KEY'] = 'secret secret'

        app.config['IMAGINE_ADAPTER'] = {
            'name': 'fs',
        }

        app.config['IMAGINE_FILTER_SETS'] = {
            'test_scale_cached': {
                'cached': True,
                'filters': {
                    'thumbnail': {'size': [100, 100], 'mode': 'inset'}
                }
            },
            'test_scale_dynamic': {
                'cached': False,
                'filters': {
                    'thumbnail': {'size': [100, 100], 'mode': 'inset'}
                }
            }
        }
        self.imagine = Imagine(app)
        return app
Example #3
0
def create_app():
    """
    Creates the Flask app instance

    @return: Flask app
    @rtype: flask.Flask
    """
    from flask import Flask
    app = Flask(__name__)
    # set debug to true so we see error dumps in the browser
    app.debug = settings.APP_DEBUG
    app.secret_key = settings.APP_SECRET_KEY
    app.config['SQLALCHEMY_DATABASE_URI'] = settings.DATABASE[env]['uri']
    app.config['BASE_URL'] = settings.BASE_URL
    app.config['SQLALCHEMY_ECHO'] = settings.DATABASE[env]['echo']
    app.config['RECAPTCHA_PUBLIC_KEY'] = settings.RECAPTCHA_PUBLIC_KEY
    app.config['RECAPTCHA_PRIVATE_KEY'] = settings.RECAPTCHA_PRIVATE_KEY
    app.config['SERVER_NAME'] = settings.BASE_URL

    app.jinja_options['extensions'].append('jinja2.ext.loopcontrols')
    my_loader = jinja2.ChoiceLoader([
        app.jinja_loader,
        jinja2.FileSystemLoader([os.path.dirname(os.path.abspath(__file__)) + '/static']),
    ])
    app.jinja_loader = my_loader

    return app
Example #4
0
    def create_app(self):
        """Create the app."""
        from flask_iiif import IIIF
        from flask_restful import Api
        from flask_iiif.cache.simple import ImageSimpleCache

        app = Flask(__name__)
        app.config['DEBUG'] = True
        app.config['TESTING'] = True
        app.config['SERVER_NAME'] = "shield.worker.node.1"
        app.config['SITE_URL'] = "http://shield.worker.node.1"
        app.config['IIIF_CACHE_HANDLER'] = ImageSimpleCache()
        app.logger.disabled = True

        api = Api(app=app)

        iiif = IIIF(app=app)

        iiif.uuid_to_image_opener_handler(self.create_image)

        def api_decorator_test(*args, **kwargs):
            if 'decorator' in kwargs.get('uuid'):
                abort(403)

        iiif.api_decorator_handler(api_decorator_test)

        iiif.init_restful(api)
        return app
Example #5
0
def create_app():
    app = Flask("test", template_folder=basedir + "/../app/templates")
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'opinionated-test.db')
    app.config['SERVER_NAME'] = 'localhost:5000'
    app.debug = True
    db.app = app
    db.init_app(app)
    return app
Example #6
0
 def create_app(self):
     app = Flask(__name__)
     app.config['TESTING'] = True
     app.config['SERVER_NAME'] = 'localhost'
     app.config['SECRET_KEY'] = 'secret secret'
     app.config['IMAGES_PATH'] = ['assets']
     self.images = Images(app)
     return app
Example #7
0
 def test_subdomain(self):
     app = Flask(__name__)
     app.config['SERVER_NAME'] = 'example.org'
     blu = Blueprint(__name__, __name__, subdomain='foo')
     silk = Silk(blu)
     app.register_blueprint(blu)
     rv = app.test_client().get('/icons/page_white.png',
                                'http://foo.example.org/')
     assert 294 == len(rv.data), 'could not found an icon file.'
Example #8
0
def app(request):
    flask_app = Flask(__name__)
    flask_app.config['TESTING'] = True
    flask_app.config['DEBUG'] = True
    flask_app.config['SERVER_NAME'] = 'localhost'
    ctx = flask_app.app_context()
    ctx.push()
    request.addfinalizer(ctx.pop)
    return flask_app
 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
Example #10
0
def app():
    app = Flask(__name__)
    app.config['TESTING'] = True
    app.config['SERVER_NAME'] = 'testing.local'

    @app.route('/hello/<arg1>/')
    def hello(arg1):
        return str(app.hello_view.active)

    return app
def create_app(debug=True):
	"""Create an application."""
	app = Flask(__name__, static_url_path='')
	app.debug = debug
	#app.config['SECRET_KEY'] = 'mXcUbE'
	app.config['SERVER_NAME'] = '127.0.0.1'

	from .main import main as main_blueprint
	app.register_blueprint(main_blueprint)
	socketio.init_app(app)#, host='srvv-bli9113-datacollection', port=8081)
	return app
Example #12
0
def create_app(db_uri, datadir=DEFAULT_DATA_DIR, echo=True, pull_password=None,
               host=None, port=5000):
    datadir = os.path.abspath(datadir)

    app = Flask(__name__)
    app.config.setdefault('SQLALCHEMY_DATABASE_URI', db_uri)
    app.config.setdefault('SQLALCHEMY_ECHO', echo)
    app.config.setdefault('PYVO_DATADIR', datadir)
    app.config.setdefault('PYVO_PULL_PASSWORD', pull_password)
    if host:
        server_name = host
        if port != 80:
            server_name += ':{}'.format(port)
        app.config['SERVER_NAME'] = server_name
    app.jinja_env.undefined = StrictUndefined
    db.init_app(app)

    for filter_name in filters.__all__:
        app.jinja_env.filters[filter_name] = getattr(filters, filter_name)

    @app.template_global()
    def url_for_lang(lang_code):
        args = dict(request.view_args)
        args['lang_code'] = lang_code
        return url_for(request.endpoint, **args)

    @app.template_global()
    def tr(cs, en):
        if g.lang_code == 'cs':
            return cs
        elif g.lang_code == 'en':
            return en
        raise ValueError(g.lang_code)

    @app.before_first_request
    def setup():
        db_setup(datadir)

    @app.url_value_preprocessor
    def pull_lang_code(endpoint, values):
        if values:
            g.lang_code = values.pop('lang_code', None)

    @app.url_defaults
    def add_language_code(endpoint, values):
        if 'lang_code' in values or not g.lang_code:
            return
        if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
            values['lang_code'] = g.lang_code

    for url, func, options in routes:
        app.route(url, **options)(func)

    return app
Example #13
0
def create_app():
    """Create the flask app."""
    app = Flask(__name__)
    app.config['SERVER_NAME'] = '127.0.0.1:5000'
    app.config['DEBUG'] = True
    app.config['SECRET_KEY'] = 'OWee7sohNgu2chuSh3aequaim6let9Ie'

    app.config.from_envvar('TRELLO_WORKON_SETTINGS')  # overrides server name, debug and secret key

    app.register_blueprint(management)

    return app
Example #14
0
def sslify():
    app = Flask(__name__)
    app.config['DEBUG'] = False
    app.config['TESTING'] = False
    app.config['SERVER_NAME'] = 'example.com'
    sslify = SSLify(app)

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

    return sslify
Example #15
0
def app(request):
    app = Flask(__name__)
    app.config['SERVER_NAME'] = 'localhost'
    app = init_webapp(test=True)
    ctx = app.app_context()
    ctx.push()

    def teardown():
        ctx.pop()

    request.addfinalizer(teardown)
    return app
    def test_init_without_cache_folder(self):
        app = Flask(__name__)
        app.root_path = os.path.abspath(os.path.normpath(os.path.dirname(__file__) + '/../'))
        app.config['TESTING'] = True
        app.config['SERVER_NAME'] = 'localhost'
        app.config['SECRET_KEY'] = 'secret secret'

        app.config['IMAGINE_ADAPTER'] = {
            'name': 'fs',
            'source_folder': 'images'
        }

        imagine = Imagine(app)
        self.assertTrue(isinstance(imagine, Imagine))
Example #17
0
    def setup(self):
        """Creates the Flask application and the APIManager."""
        # create the Flask application
        app = Flask(__name__)
        app.config['DEBUG'] = True
        app.config['TESTING'] = True
        # This is required by `manager.url_for()` in order to construct
        # absolute URLs.
        app.config['SERVER_NAME'] = 'localhost'
        app.logger.disabled = True
        self.flaskapp = app

        # create the test client
        self.app = app.test_client()

        force_content_type_jsonapi(self.app)
Example #18
0
def check_queue(ip, port):
    app = Flask(__name__)
    app.config['SERVER_NAME'] = conf.SERVER_NAME
    app.add_url_rule('/pathfinder/download/<uuid>', 'download', download)

    with app.app_context():
        db = get_db()
        cur = db.cursor()
        cur.execute('select * from job where status == ?', ('R',))
        numjobs = 0
        mail = None
        for row in cur.fetchall():
            uuid, email, date, status = row
            # finished?
            pid = int(open(os.path.join(get_job_folder(uuid), 'run.pid'), 'r').read())
            if pid_exists(pid):
                numjobs += 1
            else:
                mail = Mail(app)
                msg = Message('[PathFinder] Your job is finished.', sender='roux@uchicago.edu', recipients=[email, 'sunhwanj@gmail.com'])

                if os.path.exists(os.path.join(get_job_folder(uuid), 'pathway.pdb')):
                    cur.execute('update job set status = ? where uuid = ?', ('F',uuid))
                    msg.body = render_template('email.tpl', uuid=uuid, has_error=False)
                    msg.attach('pathway.pdb', 'text/pdb', open(os.path.join(get_job_folder(uuid), 'pathway.pdb')).read())
                else:
                    cur.execute('update job set status = ? where uuid = ?', ('E',uuid))
                    msg.body = render_template('email.tpl', uuid=uuid, has_error=True)

        if numjobs < NUMJOBS_CONCUR:
            cur.execute('select * from job where status == ?', ('Q',))
            for row in cur.fetchall():
                uuid, email, date, status = row
                newpid = client(ip, port, "SPAWN:%s" % uuid)
                open(os.path.join(get_job_folder(uuid), 'run.pid'), 'w').write(newpid)
                cur.execute('update job set status = ? where uuid = ?', ('R',uuid))
                numjobs += 1
                if numjobs >= NUMJOBS_CONCUR: break

        db.commit()
        db.close()

        if mail:
            try:
                mail.send(msg)
            except:
                pass
Example #19
0
    def setup(self):
        """Creates the Flask application and the APIManager."""
        # create the Flask application
        app = Flask(__name__)
        app.config['DEBUG'] = True
        app.config['TESTING'] = True
        app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://'
        # This is to avoid a warning in earlier versions of Flask-SQLAlchemy.
        app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
        # This is required by `manager.url_for()` in order to construct
        # absolute URLs.
        app.config['SERVER_NAME'] = 'localhost'
        app.logger.disabled = True
        self.flaskapp = app

        # create the test client
        self.app = app.test_client()

        force_json_contenttype(self.app)
Example #20
0
def app(view_and_schema):
    view_class, schema, _ = view_and_schema
    blueprint = FlumpBlueprint('flump', __name__)
    blueprint.register_flump_view(view_class, '/user/')

    app = Flask(__name__)
    app.response_class = FlumpTestResponse
    app.config['SERVER_NAME'] = 'localhost'
    app.config['SERVER_PROTOCOL'] = 'http'
    app.config['DEBUG'] = True
    app.config['TESTING'] = True

    app.register_blueprint(blueprint, url_prefix='/tester')

    ctx = app.app_context()
    ctx.push()
    try:
        yield app
    finally:
        ctx.pop()
def create_app(db_interface, app_name='testapp', db_name='__test-db__'):
    app = Flask(app_name)
    app.config['SERVER_NAME'] = 'localhost:5000'

    if db_interface == 'pymongo':
        app.config['MONGO_DBNAME'] = db_name
        mongo = PyMongo(app)
        with app.app_context():
            app.session_interface = MongoDBSessionInterface(
                app, mongo.db, 'sessions')
    elif db_interface == 'mongoengine':
        app.config['MONGODB_DB'] = db_name
        mongo = MongoEngine(app)
        app.session_interface = MongoDBSessionInterface(
            app, mongo.connection[app.config['MONGODB_DB']], 'sessions')

    @app.route("/set")
    def set_session():
        session['data'] = request.args['d']
        return 'data'

    @app.route("/setpermanent")
    def set_permanent_session():
        session.permanent = True
        session['data'] = request.args['d']
        return 'data'

    @app.route("/get")
    def get_session():
        return session.get('data', '')

    @app.route("/unicode/set")
    def unicode_set():
        session['foo'] = u'Alpenerstra\xdfe'
        return 'done'

    @app.route("/unicode/get")
    def unicode_get():
        return session['foo']

    return app
Example #22
0
def create_app():
    app = Flask(__name__, static_folder='build/public/', static_url_path='/assets')
    app.config['SECRET_KEY'] = 'sekrit!'
    app.config['WEBPACK_MANIFEST_PATH'] = detect_webpack_manifest_path('./brigade/build/manifest.json')

    webpack = Webpack()
    webpack.init_app(app)

    if 'SERVER_NAME' in os.environ:
        app.config['SERVER_NAME'] = os.environ['SERVER_NAME']
    if 'SITEMAP_URL_SCHEME' in os.environ:
        app.config['SITEMAP_URL_SCHEME'] = os.environ['SITEMAP_URL_SCHEME']

    app.register_blueprint(brigade)
    app.register_blueprint(filters)
    app.register_blueprint(sitemap_blueprint)

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

    return app
Example #23
0
File: app.py Project: zparmley/YH12
import json
import re
import StringIO

from flask import Flask, make_response, render_template
import qrcode

from config.votes import votes as votes_config
from wallet.connection import get_bitcoin_connection, get_source_connection

app = Flask(__name__)
app.config['SERVER_NAME'] = 'dev2-devc.dev.yelpcorp.com:35535'


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

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

@app.route('/qr/vote/<vote>')
def vote_qr_code(vote):
    if vote not in votes_config:
        return None
    out = StringIO.StringIO()
    qrcode.make('bitcoin:%s?amount=%s&label=%s' % (votes_config[vote]['address'], votes_config[vote]['ammount'], votes_config[vote]['label'])).save(out)
    resp = make_response(out.getvalue())
    resp.content_type = 'image/png'
    return resp
Example #24
0
from flask import Flask, jsonify, render_template, request, send_file, send_from_directory

app = Flask(__name__)

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

if __name__ == '__main__':
    app.config['SERVER_NAME']="localhost:5000"
    import logging
    app.config.update(DEBUG=True,PROPAGATE_EXCEPTIONS=True,TESTING=True)
    logging.basicConfig(level=logging.DEBUG)

    app.run()
Example #25
0
#!flask/bin/python

import os, json, logging
from datetime import datetime
from flask import Flask, abort, request, jsonify, g
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.httpauth import HTTPBasicAuth
from passlib.apps import custom_app_context as pwd_context
from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired)

# initialization
app = Flask(__name__)
app.config['SECRET_KEY'] = 'ini ceritaku, mana ceritamu'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SERVER_NAME'] = '127.0.0.1:5000'

# logger initialization
file_handler = logging.FileHandler('app.log')
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)

# extensions
db = SQLAlchemy(app)
auth = HTTPBasicAuth()

# create users table
class User(db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(32), index=True)
Example #26
0
def getCurrentUserFirstName():
  return getCurrentUserName().split()[0]

@app.route('/logout')
def logout():
  session.pop('token')
  return redirect(url_for('index'))

@app.route('/add_sample_set')
@req_auth
def add_sample_set():
  colors = ["Coral", "Black", "White", "Pink", "Blue", "Canary"]
  styles = ["Shirt", "Pants", "OCBD", "Jacket", "Tie", "Hat"]
  samples = []
  for i in colors:
    for j in styles:
      samples.append(i + " " + j)

  for i in samples:
    j = i.upper()
    guid = getDB().addCloth(j)
    getDB().tagCloth(guid, j.split()[0])
    getDB().tagCloth(guid, j.split()[1])
  return redirect(url_for("edit_wardrobe"))

if __name__ == '__main__':
  port = int(os.environ.get('PORT', 8080))
  app.config['SERVER_NAME'] = os.environ.get("server_name", "wardrobe-plus-jeffhou.c9users.io")
  app.secret_key = APP_SECRET
  app.run('0.0.0.0', debug=True, port=port)
Example #27
0
positive certification over it.

See README.md for details.
"""
from __future__ import division, print_function

from flask import Flask, request, make_response
from pgpdump import dumpbuffer
from requests_futures.sessions import FuturesSession

from deadbeef import deadbeef
from remunge import remunge
from asciiarmor import armor

app = Flask(__name__)
app.config['SERVER_NAME'] = '127.0.0.1:11371'
app.debug = True

session = FuturesSession()

GET_HEADERS = {}


@app.route("/pks/<star>")
def main(star):
  """Proxy keyserver requests.

  All requests other than get ops are transparently forwarded.
  """
  future = session.get(request.url.replace('127.0.0.1',
                                           'keyserver.ubuntu.com'))
Example #28
0


if __name__ == '__main__':
  logging.basicConfig(level=logging.INFO)
  import argparse
  parser = argparse.ArgumentParser(description='Run Development version of GPUVerifyRise4Fun web service')
  parser.add_argument('-p', '--port', type=int, default=55000, help='Port to use. Default %(default)s')
  parser.add_argument('-d', '--debug', action='store_true',default=False, help='Use Flask Debug mode and show debugging output. Default %(default)s')
  parser.add_argument('--public', action='store_true', default=False, help='Make publically accessible. Default %(default)s')
  parser.add_argument('-s','--server-name', type=str, default='localhost' , help='Set server hostname. This is ignored is --public is used. Default "%(default)s"')

  args = parser.parse_args()


  if args.debug:
    print("Using Debug mode")
    logging.getLogger().setLevel(logging.DEBUG)
  
  # extra options
  options = { }
  if args.public:
    options['host'] = '0.0.0.0'
    app.config['SERVER_NAME'] = gethostname() + ':' + str(args.port)
  else:
    app.config['SERVER_NAME'] = args.server_name + ':' + str(args.port)

  print("Setting SERVER_NAME to " + app.config['SERVER_NAME'])

  app.run(debug=args.debug, port=args.port, **options)
Example #29
0
from flask import Flask, render_template, request, url_for
from .config import config

app = Flask(__name__)
app.debug = True
app.secret_key = config['secret_key']
app.config['SERVER_NAME'] = config['server_name']


@app.errorhandler(404)
def not_found(error):
    #for rule in app.url_map.iter_rules():
        #print('%s => %s' % (url_for(rule.endpoint), rule.endpoint))
    print('%s' % request.headers)
    return 'Not Found: %s %s' % (request.path, error), 404


@app.route('/')
def index():
    return render_template('index.html', title='Plan your journey! - Vasco')
Example #30
0
from flask.ext.sqlalchemy import SQLAlchemy

# Create Flask application
application = Flask('web')
if os.environ.get('JARR_TESTING', False) == 'true':
    application.debug = logging.DEBUG
    application.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
    application.config['TESTING'] = True
else:
    application.debug = conf.LOG_LEVEL <= logging.DEBUG
    application.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    application.config['SQLALCHEMY_DATABASE_URI'] \
            = conf.SQLALCHEMY_DATABASE_URI

scheme, domain, _, _, _ = urlsplit(conf.PLATFORM_URL)
application.config['SERVER_NAME'] = domain
application.config['PREFERRED_URL_SCHEME'] = scheme

set_logging(conf.LOG_PATH, log_level=conf.LOG_LEVEL)

# Create secrey key so we can use sessions
application.config['SECRET_KEY'] = os.urandom(12)

application.config['RECAPTCHA_USE_SSL'] = True
application.config['RECAPTCHA_PUBLIC_KEY'] = conf.RECAPTCHA_PUBLIC_KEY
application.config['RECAPTCHA_PRIVATE_KEY'] = conf.RECAPTCHA_PRIVATE_KEY

db = SQLAlchemy(application)

def populate_g():
    from flask import g