Пример #1
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
Пример #2
0
def generate_app(
         debug=False, config_file=None, secret="",
         session_secret="",
         github_client_id="", github_client_secret="", github_hook_secret="",
         mongodb_db="Hook", mongodb_host='127.0.0.1', mongodb_port=27017, mongodb_user=None, mongodb_password=None,
         hooktest_secret="", hooktest_remote="http://127.0.0.1:5002/hooktest/rest/api/queue"
    ):
    app = Flask(__name__)
    app.config["JSONIFY_PRETTYPRINT_REGULAR"] = False

    if not config_file:
        app.config["SECRET_KEY"] = session_secret,
        app.config["GITHUB_CLIENT_ID"] = github_client_id
        app.config["GITHUB_CLIENT_SECRET"] = github_client_secret

        app.config["MONGODB_DB"]= mongodb_db
        app.config['MONGODB_HOST'] = mongodb_host
        app.config['MONGODB_PORT'] = mongodb_port

        if mongodb_user:
            app.config['MONGODB_USERNAME'] = mongodb_user
        if mongodb_password:
            app.config['MONGODB_PASSWORD'] = mongodb_password

        app.config["HOOKUI_HOOKTEST_SECRET"] = hooktest_secret
        app.config["HOOKUI_GITHUB_SECRET"] = github_hook_secret
        app.config["HOOKUI_REMOTE"] = hooktest_remote
    else:
        app.config.update(read_yaml(config_file)[0])

    app.debug = debug
    app.config["DEBUG"] = debug
    hook = HookUI(prefix="", app=app)
    return app
Пример #3
0
def create():
    """Create application.
    """

    # Create application
    app = Flask("service", static_folder=None)
    app.config["DEBUG"] = True

    # CORS support
    CORS(app)

    # Session
    sess = Session()
    app.config["SESSION_TYPE"] = "filesystem"
    app.config["SECRET_KEY"] = "openspending rocks"
    sess.init_app(app)

    # Register blueprints
    logger.info("Creating Datastore Blueprint")
    app.register_blueprint(datastore.create(), url_prefix="/datastore/")
    logger.info("Creating Package Blueprint")
    app.register_blueprint(package.create(), url_prefix="/package/")
    logger.info("Creating Authentication Blueprint")
    app.register_blueprint(user.oauth_create(), url_prefix="/oauth/")
    logger.info("Creating Users Blueprint")
    app.register_blueprint(user.create(), url_prefix="/user/")
    logger.info("Creating Search Blueprint")
    app.register_blueprint(search.create(), url_prefix="/search/")

    # Return application
    return app
Пример #4
0
def create_app(config=None):
    app = Flask(__name__)

    app.config["SECRET_KEY"] = "129iv3n91283nv9812n3v89q2nnv9iaszv978n98qwe7z897d"
    app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql://postgres@localhost/mooddiaryDb"
    # app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/mooddiary.db'

    app.config["DEBUG"] = True
    app.config["LESS_BIN"] = os.path.realpath(os.path.join(os.path.dirname(__file__), "../node_modules/less/bin/lessc"))

    app.config["JWT_EXPIRATION_DELTA"] = timedelta(days=28)
    app.config["JWT_ALGORITHM"] = "HS512"

    app.config["RECAPTCHA_SECRET_KEY"] = "6LdSswwTAAAAADs20eK6NqYaeppxIWm-gJrpto0l"
    app.config["RECAPTCHA_PUBLIC_KEY"] = "6LdSswwTAAAAABTZq5Za_0blmaSpcg-dFcqaGda9"

    if config:
        app.config.from_object(config)

    app.config["ASSETS_DEBUG"] = app.config["DEBUG"]

    db.init_app(app)
    migrate.init_app(app, db)
    assets.init_app(app)
    jwt.init_app(app)

    assets.register("js", js)
    assets.register("css", css)

    app.register_blueprint(main)
    app.register_blueprint(api, url_prefix="/api")
    app.register_blueprint(auth, url_prefix="/auth")

    return app
Пример #5
0
def create_app(_run_mode=None):
    # Create Flask app.
    global app
    base_dir = os.path.dirname(os.path.abspath(__file__))
    template_dir = os.path.join(base_dir, 'templates')
    static_dir = os.path.join(base_dir, 'static')
    app = Flask("procjam15", template_folder=template_dir, static_folder=static_dir)

    # Dev run mode.
    if _run_mode == "dev":
        app.config["DEBUG"] = True
        app.config["SECRET_KEY"] = "WeDontCareAboutSecretsInDev"

    # Heroku run mode.
    elif _run_mode == "heroku":
        # Get port number and secret key from Heroku environment variable.
        app.config["PORT_NR"] = int(os.environ["PORT"])
        app.config["SECRET_KEY"] = os.environ["FLASK_SECRET_KEY"]
        app.config["DEBUG"] = False

        init_stdout_handler()
        set_up_logger(app.logger)

    # Dreamhost run mode.
    elif _run_mode == "dreamhost":
        # Get port number and secret key from Heroku environment variable.
        app.config["SECRET_KEY"] = os.environ["FLASK_SECRET_KEY"]
        app.config["DEBUG"] = False

        init_stdout_handler()
        set_up_logger(app.logger)

    # Unrecognized run mode.
    else:
        logging.error("Did not recognize run mode '%s'." % _run_mode)
        return None

    app.debug = app.config["DEBUG"]

    # Import the views, to apply the decorators which use the global app object.
    import main.views

    # Set up Jinja 2 filters.
    set_up_jinja_filters(app)

    return app
Пример #6
0
def create_app():
    app = Flask(__name__)
    app.register_blueprint(bp)
    app.config["DEBUG"] = True
    app.config["DATABASE"] = ":memory:"
    app.config["SECRET_KEY"] = "wow"
    db.init_app(app)
    return app
Пример #7
0
def create_flask_app():
    """Creates a configured flask app."""
    app = Flask(__name__, template_folder="templates")
    app.debug = True
    app.secret_key = "secret"
    app.config["DEBUG"] = True

    return app
Пример #8
0
  def test_cache_control(self):
    app = Flask(__name__)
    app.config["DEBUG"] = True
    appcache = Appcache(app)
    appcache.add_urls("/static/static1.js")

    client = app.test_client()
    response = client.get("/static/static1.js", follow_redirects=True)
    self.assertTrue("no-cache" in response.headers["Cache-Control"])
    self.assertTrue("Expires" not in response.headers)

    app = Flask(__name__)
    app.config["DEBUG"] = False
    appcache = Appcache(app)
    appcache.add_urls("/static/static1.js")

    client = app.test_client()
    response = client.get("/static/static1.js", follow_redirects=True)
    self.assertTrue("must-revalidate" in response.headers["Cache-Control"])
    self.assertTrue("Expires" not in response.headers)
Пример #9
0
 def setup_method(self, test_method):
     #self.db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()
     #flaskr.app.config['TESTING'] = True
     app = Flask(__name__)
     app.config["DEBUG"] = True
     app.config["TESTING"] = True
     app.register_blueprint(module_one)
     self.app = app.test_client()
     #flaskr.init_db()
     self.api_payload = {
         "user_name": "Alice",
         "greeting": "Howdy",
     }
Пример #10
0
    def setUp(self):
        """Creates the Flask application and the APIManager."""
        super(FlaskTestBase, self).setUp()

        # create the Flask application
        app = Flask(__name__)
        app.config["DEBUG"] = True
        app.config["TESTING"] = True
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///%s" % DB["filename"]
        self.flaskapp = app

        # create the test client
        self.app = app.test_client()
Пример #11
0
def create_app(config=None, debug=False):
    # Create the Flask Application
    app = Flask("warehouse")

    # Load Configuration
    logger.debug("Loading configuration from 'warehouse.defaults'")
    app.config.from_object("warehouse.defaults")

    if "WAREHOUSE_CONF" in os.environ:
        logger.debug(
            "Loading configuration from '%s' via $WAREHOUSE_CONF",
            os.environ["WAREHOUSE_CONF"],
        )
        app.config.from_envvar("WAREHOUSE_CONF")

    if config:
        logger.debug("Loading configuration from '%s' via -c/--config", config)
        app.config.from_pyfile(config)

    # Configure Debug if it's enabled
    if debug:
        app.config["DEBUG"] = debug

    # Configure logging
    if "LOGGING" in app.config:
        logging.config.dictConfig(app.config["LOGGING"])

    # Initialize the database
    logger.debug("Initialize the PostgreSQL database object")
    db.init_app(app)

    # Initialize Redis
    logger.debug("Initialize the Redis database object")
    redis.init_app(app)

    for module in MODULES:  # pylint: disable=W0621
        # Load Models
        if module.get("models"):
            logger.debug("Loading models for %s", module["name"])
            importlib.import_module("warehouse.%(name)s.models" % module)

        # Load views
        if module.get("views"):
            logger.debug("Loading blueprints for %s", module["name"])
            mod = importlib.import_module("warehouse.%(name)s.views" % module)

            for blueprint in mod.BLUEPRINTS:
                app.register_blueprint(blueprint)

    return app
Пример #12
0
def create_app(package_name):
    app = Flask(package_name)
    app.config.from_object("flaskr.config")

    app.config["DEBUG"] = True
    app.config["DEBUG_TB_INTERCEPT_REDIRECTS"] = False

    db.init_app(app)

    filters.init_app(app)
    logs.init_app(app)
    frontend.init_app(app)

    return app
Пример #13
0
def app_context():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "deterministic"
    app.config["TESTING"] = True
    app.config["PROPAGATE_EXCEPTIONS"] = True
    app.config["DEBUG"] = True

    @app.route("/")
    def index():
        return u"The index"

    @app.route("/login")
    def login():
        id = int(request.args["id"])
        force = "force" in request.args
        remember = "remember" in request.args
        if login_user(USERS[id], force=force, remember=remember):
            if "permanent" in request.args:
                session.permanent = True
            return u"Logged in"
        else:
            return u"Go away, creeper"

    class Protected(LoginRequiredMixin, MethodView):
        def get(self):
            return u"Welcome, %s" % current_user.name

    app.add_url_rule("/protected", view_func=Protected.as_view("protected"))

    @app.route("/sensitive-action")
    @fresh_login_required
    def sensitive_action():
        return u"Be careful, %s" % current_user.name

    @app.route("/logout")
    @login_required
    def logout():
        logout_user()
        return u"Logged out"

    @app.route("/reauth")
    @login_required
    def reauth():
        confirm_login()
        return u"Login confirmed"

    with app.test_request_context():
        yield app
Пример #14
0
def app():
    app_ = Flask("testapp")
    app_.config["DEBUG"] = True
    app_.config["TESTING"] = True

    @app_.route("/posts/<post_id>/comments/")
    def posts_comments(post_id):
        return "Comments for post {}".format(post_id)

    @app_.route("/authors/<int:author_id>")
    def author_detail(author_id):
        return "Detail for author {}".format(author_id)

    ctx = app_.test_request_context()
    ctx.push()
    yield app_
    ctx.pop()
Пример #15
0
def app_context():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "deterministic"
    app.config["TESTING"] = True
    app.config["PROPAGATE_EXCEPTIONS"] = True
    app.config["DEBUG"] = True
    
    @app.route("/")
    def index():
        return u"The index"
    
    @app.route("/login")
    def login():
        id = int(request.args["id"])
        force = "force" in request.args
        remember = "remember" in request.args
        if login_user(USERS[id], force=force, remember=remember):
            if "permanent" in request.args:
                session.permanent = True
            return u"Logged in"
        else:
            return u"Go away, creeper"
    
    @app.route("/protected")
    @login_required
    def protected():
        return u"Welcome, %s" % current_user.name
    
    @app.route("/logout")
    @login_required
    def logout():
        logout_user()
        return u"Logged out"
    
    @app.route("/reauth")
    @login_required
    def reauth():
        confirm_login()
        return u"Login confirmed"
    
    with app.test_request_context():
        yield app
Пример #16
0
def build_flask_app():
    flask_app = Flask(__name__, static_folder="../../dashboardapp/dist", static_url_path="/app")

    # The following settings will likely be overriden.
    flask_app.config["DEBUG"] = False
    flask_app.config["SECRET_KEY"] = "SECRET"

    flask_app.config.from_pyfile("../config.py")

    # Mostly for debugging purposes, this snippet will print the site-map so that we can check
    # which methods we are routing.
    @flask_app.route("/site-map")
    def site_map():
        lines = []
        for rule in flask_app.url_map.iter_rules():
            line = str(escape(repr(rule)))
            lines.append(line)

        ret = "<br>".join(lines)
        return ret

    return flask_app
Пример #17
0
def create_app(config_val="default"):
    app = Flask(__name__)
    # set config values
    app.config.from_object(config[config_val])
    app.config["DEBUG"] = True

    # register blueprints
    app.register_blueprint(main)
    app.register_blueprint(api)

    # initializations
    mongo.init_app(app)
    toolbar.init_app(app)



    # add robots.txt
    @app.route('/robots.txt')
    def static_from_root():
        return send_from_directory(app.static_folder, request.path[1:])


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

import  pywapi
import string

app = Flask(__name__)
app.config["DEBUG"] = True  # Only include this while you are testing your app

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

@app.route("/monica")
def name():
	return "Monica"

@app.route("/search/<search_query>")
def search(search_query):
	return search_query

@app.route("/add/<x>/<y>")
def add(x,y):
	return str(int(x) + int(y))

@app.errorhandler(404)
def page_not_found(error):
	return "Sorry, this page was not found.", 404

@app.route("/weather", methods=["GET", "POST"])
def weather():
	if request.method == "POST":
Пример #19
0
from flask import Flask
from redis import StrictRedis
import config

app = Flask(__name__)

UPLOAD_FOLDER = "uploads"
ALLOWED_EXTENSIONS = set(["txt", "pdf", "png", "jpg", "jpeg", "gif"])
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
app.secret_key = config.SECRET_KEY
app.config["DEBUG"] = "true"

red = StrictRedis()

from gethem import views
Пример #20
0
from flask import Flask

app = Flask(__name__)
app.config["DEBUG"] = True  # Disable this for deployment

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run()
Пример #21
0
import os
from flask import Flask, render_template, send_from_directory, jsonify, redirect, url_for, request, abort
from flask.ext.sqlalchemy import SQLAlchemy
import uuid

import random, string

from dungeon import dungeon
from cards import cards

# Initilization
APPLICATION_CONFIG = os.environ.get("BLUE_MONGOOSE_SETTINGS")
BASE_URL = "https://blue-mongoose.herokuapp.com/"

app = Flask(__name__)
app.config["DEBUG"] = False
app.config["TESTING"] = False

if APPLICATION_CONFIG == "production":
    print("Starting in production mode")
    app.config["DATABASE_URI"] = os.environ["DATABASE_URL"]
    GITHUB_CLIENT_ID = os.environ["GITHUB_CLIENT_ID"]
    GITHUB_CLIENT_SECRET = os.environ["GITHUB_CLIENT_SECRET"]
else:
    BASE_URL = "http://localhost:5000/"
    app.config["DATABASE_URI"] = os.environ["BLUE_MONGOOSE_DATABASE_URL"]

    GITHUB_CLIENT_ID = os.environ["BLUE_MONGOOSE_GITHUB_CLIENT_ID"]
    GITHUB_CLIENT_SECRET = os.environ["BLUE_MONGOOSE_GITHUB_CLIENT_SECRET"]

    if APPLICATION_CONFIG == "testing":
Пример #22
0
def build_flask_app():
    flask_app = Flask(__name__)
    flask_app.config["DEBUG"] = True
    flask_app.config["SECRET_KEY"] = "SECRET"
    return flask_app
Пример #23
0
# SNS HTTP request endpoint: subscribe, unsubscribe, notification
@application.route('/kitkat', methods = ['POST', 'GET'])
def sns():
	headers = request.headers
	# print "headers", headers
	print "request", request
	obj = json.loads(request.data)
	print "!!!!!!!!!!!!!!!!!!!!!POST SUCCESS!!!!!!!!!!!!!!!!!!!!! = ", obj

	global  finalList
	finalList.append(obj[u'data1'])
	finalList.append(obj[u'data2'])
	finalList.append(obj[u'data3'])

	print finalList

	return '', 200



if __name__ == '__main__':
	try: 
		application.config["DEBUG"] = True
		application.run(host='0.0.0.0', port=9090)
		#application.run(host='199.58.86.213', port=5000)


	except:
		print "application.run failed"

Пример #24
0
"""
Flask Documentation:     http://flask.pocoo.org/docs/
Jinja2 Documentation:    http://jinja.pocoo.org/2/documentation/
Werkzeug Documentation:  http://werkzeug.pocoo.org/documentation/
"""

import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy


app = Flask(__name__)

app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY", "this_should_be_configured")
app.config["PORT"] = int(os.environ.get("PORT", 8000))
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL")
app.config["DEBUG"] = bool(os.environ.get("DEBUG", False))

if app.config["SQLALCHEMY_DATABASE_URI"]:
    db = SQLAlchemy(app)

config = app.config

app.jobs = {}
Пример #25
0
from flask import Flask, g
from flask.ext.sqlalchemy import SQLAlchemy
from flask_oauthlib.provider import OAuth2Provider

import settings


app = Flask(__name__)

app.config["SECRET_KEY"] = settings.SECRET_KEY
app.config["DEBUG"] = settings.DEBUG

app.config["DATABASE_FILE"] = settings.DATABASE_FILE
app.config["SQLALCHEMY_DATABASE_URI"] = settings.SQLALCHEMY_DATABASE_URI
app.config["SQLALCHEMY_ECHO"] = settings.SQLALCHEMY_ECHO

###########################


db = SQLAlchemy(app)

"""
In models.py we import 'db' from 'app'. So, we have
circular dependency here. Import 'Account' after 'db'
to temporarily resolve this.
"""
from models import User


###########################
Пример #26
0
    _app_ctx_stack,
    abort,
    Markup,
    make_response,
)

from flaskext.markdown import Markdown
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.admin import Admin
from flask.ext.admin.contrib.sqla import ModelView

from postmark import PMMail

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DATABASE_URL")
app.config["DEBUG"] = os.environ.get("DEBUG")
app.config["USERNAME"] = os.environ.get("USERNAME")
app.config["PASSWORD"] = os.environ.get("PASSWORD")
app.config["SECRET_KEY"] = os.environ.get("SECRET_KEY")
app.config["POSTMARK_API_KEY"] = os.environ.get("POSTMARK_API_KEY")
app.config["POSTMARK_SENDER"] = os.environ.get("POSTMARK_SENDER")

markdown = Markdown(app, extensions=["tables"])

db = SQLAlchemy(app)

candidate_problems = db.Table(
    "candidate_problems",
    db.Model.metadata,
    db.Column("candidate_id", db.Integer, db.ForeignKey("candidates.id")),
    db.Column("problem_id", db.Integer, db.ForeignKey("problems.id")),
Пример #27
0
from flask import Flask, render_template,request
from clarifai_api.client import ClarifaiApi
import requests,json

token = "a010c8418f86e4bee30358ac4812b7beee9772e8"
clarifai_api = ClarifaiApi()

app = Flask(__name__)
app.config["DEBUG"] = True #Only for testing!!

@app.errorhandler(404)
def page_not_found(error):
    return "Sorry bruh, this page ain't here", 404

@app.route("/")
def hello():
    return render_template("hello.html")

@app.route("/name")
def name():
    return "Your Name"

@app.route("/website")
def website():
    return "https://github.com/kendurkin"

@app.route("/search",methods=["GET","POST"])
def search():
    if request.method == "POST":
        url = "https://api.github.com/search/repositories?q=" + request.form["user_search"] + "&access_token=" + token
        response_dict = requests.get(url).json()
Пример #28
0
    global user_count
    user_count += 1

@socket.on("disconnect")
def disconnect(sid):
    global user_count
    user_count -= 1

@socket.on("send message")
def send_message(sid, data):
    global user_count

    data["users"] = user_count

    socket.emit("receive chat", data)

@socket.on("get user count")
def get_user_count(sid):
    global user_count

    data = {}
    data["users"] = user_count

    socket.emit("get user count", data, room=sid)


if __name__ == "__main__":
    app.config["DEBUG"] = anonconf["anontalk"]["debug"]
    app = socketio.Middleware(socket, app)
    eventlet.wsgi.server(eventlet.listen((anonconf["anontalk"]["ip"], int(anonconf["anontalk"]["port"]))), app)
Пример #29
0
from flask import Flask
from .blueprints.user_bp import *
from .blueprints.paragraph_bp import *
from .blueprints.plane_bp import *

app = Flask(__name__)
app.config["DEBUG"] = True
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'

app.register_blueprint(user_bp, url_prefix='/user')
app.register_blueprint(paragraph_bp, url_prefix='/paragraph')
app.register_blueprint(plane_bp, url_prefix='/plane')
Пример #30
0
#import the F;ask and render_template class from flask module
from flask import Flask, render_template, redirect, url_for, request, session, flash, g #g saves the object based on queries which resets after every request
from functools import wraps #for login decorators
import sqlite3

#Create flask object and assign to app
app = Flask(__name__)
app.secret_key = "My Layday" #adding secret key to make a session encryption key. Session relys on cookie. This key helps to access actual data on server side
app.config["DEBUG"] = True #This will do same as: app.run(debug = 'True')
app.database = "sample.db"
#login decorators
def login_required(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        if 'logged_in' in session:
            return f(*args, **kwargs)
        else:
            flash("You need to login first!")
            return redirect(url_for('login'))
    return wrap


#Use decorators to link functions to url
@app.route('/')
@app.route('/home')
@login_required
def home():
    #return "Hello, World!"
    g.db = connect_db() #saving the temporary conection object
    qur = g.db.execute('select * from posts') #qur will query/fethc the data from posts table
    #print(qur) #this will show a <sqlite3.Cursor object at 0x00000186EEB9E030>