Beispiel #1
0
def create_app():
    app = Flask(__name__)
    app.config.from_object(__name__)
    app.config["PROPAGATE_EXCEPTIONS"] = True
    app.logger.setLevel(app.config["LOG_LEVEL"])
    app.register_blueprint(mainbp)
    return app
Beispiel #2
0
def build_app():
    """
    Build the Flask app
    """
    app = Flask(__name__)

    def make_json_error(ex):
        """
        Return errors as JSON objects
        """
        status = getattr(ex, "code", 500)

        response = jsonify(message="Error {0}: {1}".format(status, ex if app.debug else "Internal server error"))
        response.status_code = status

        return response

    # Allow using custom error handler when debug=True
    app.config["PROPAGATE_EXCEPTIONS"] = False
    app.error_handler_spec[None][500] = make_json_error

    jobs = JobsView.as_view("jobs")
    app.add_url_rule("/jobs", view_func=jobs, methods=["GET", "POST"])
    app.add_url_rule("/jobs/<jid>", view_func=jobs, methods=["GET"])

    runners = RunnersView.as_view("runners")
    app.add_url_rule("/runners", view_func=runners, methods=["GET", "POST"])

    return app
Beispiel #3
0
def webapp(request):
    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://"
    app.config["PROPAGATE_EXCEPTIONS"] = True

    db = SQLAlchemy(app)

    class Object(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        field1 = db.Column(db.Integer)
        field2 = db.Column(db.Integer)

    db.create_all()

    @app.route("/objects")
    @paginated_view
    @sorted_view(allowed_fields=["id", "field1"])
    def view_objects():
        return Object.query

    @app.route("/objects_different_renderer")
    @paginated_view(renderer=lambda obj: {"id_value": obj.id})
    def view_objects_different_renderer():
        return Object.query

    @app.route("/objects_limited_page_size")
    @paginated_view(max_page_size=10, default_page_size=5)
    def view_objects_limited_page_size():
        return Object.query

    @app.route("/objects_no_count")
    @paginated_view(max_page_size=10, default_page_size=5, include_count=False)
    def view_objects_no_count():
        return Object.query

    @app.route("/objects_by_field2")
    @paginated_view
    @sorted_view(default="-field2")
    def view_objects_by_field2():
        return Object.query

    num_objects = 100
    field1_values = list(range(num_objects))
    random.shuffle(field1_values)
    field2_values = list(range(num_objects))
    random.shuffle(field2_values)

    for field1_value, field2_value in zip(field1_values, field2_values):
        db.session.add(Object(field1=field1_value, field2=field2_value))

    db.session.commit()

    returned = App(app)
    returned.num_objects = num_objects
    returned.activate()
    request.addfinalizer(returned.deactivate)

    return returned
Beispiel #4
0
def setup_app(env, debug=False, output_path=None, lang="en"):
    app = Flask("lektor.admin")
    app.lektor_info = LektorInfo(env, output_path, lang)
    app.debug = debug
    app.config["PROPAGATE_EXCEPTIONS"] = True

    register_modules(app)

    return app
Beispiel #5
0
    def setUp(self):

        self.cookbook = API("cookbook", "http://localhost:8881/api")

        @self.cookbook.action
        def cabbage(spicy, capitalize=False):
            if spicy:
                c = "kimchi"
            else:
                c = "sauerkraut"
            if capitalize:
                return c.capitalize()
            else:
                return c

        @self.cookbook.action
        def pounds_to_kilos(pounds):
            if pounds > 100:
                raise APIError("Too many pounds", http_code=501)
            return 0.453592 * pounds * pounds / pounds

        @self.cookbook.action
        def noop():
            return None

        api.apio_index = RemoteAPI(index_spec)

        with patch.object(requests, "post") as mock_post:
            # Load API
            mock_post.return_value.status_code = 200
            mock_post.return_value.json = cookbook_spec
            from apio.index import cookbook as remote_cookbook

            self.remote_cookbook = remote_cookbook
            mock_post.assert_called_with(
                "http://api.apio.io/actions/get_spec",
                headers={"Content-Type": "application/json"},
                data=json.dumps("cookbook"),
            )

        # Create test client for some HTTP tests
        from flask import Flask

        app = Flask(__name__, static_folder=None)
        app.register_blueprint(self.cookbook.get_blueprint(), url_prefix="/api")
        self.werkzeug_client = app.test_client()

        # Test debug mode
        app = Flask(__name__, static_folder=None)
        app.config["PROPAGATE_EXCEPTIONS"] = True
        app.register_blueprint(self.cookbook.get_blueprint(debug=True), url_prefix="/api")
        self.werkzeug_client_debug = app.test_client()
Beispiel #6
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
Beispiel #7
0
    def run(self, *args, **kwargs):
        """Runs the API as a Flask app. All arguments channelled into Flask#run
        except for `register_api`, which is a boolean that defaults to True
        and determines whether you want your API pushed to APIO index.
        """

        debug = kwargs.get("debug", False)
        if kwargs.pop("register_api", True):
            ensure_bootstrapped()
            apio_index.actions.register_api(self.spec)
        if "dry_run" in kwargs.keys():
            return
        app = Flask(__name__, static_folder=None)
        # Flask will catch exceptions to return a nice HTTP response
        # in debug mode, we want things to FAIL!
        app.config["PROPAGATE_EXCEPTIONS"] = debug
        blueprint = self.get_blueprint(debug=debug)
        app.register_blueprint(blueprint)
        app.run(*args, **kwargs)
Beispiel #8
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
Beispiel #9
0
    def _generate_app(self):
        app = Flask(__name__)
        app.config["PROPAGATE_EXCEPTIONS"] = True
        app.config["SQLALCHEMY_DATABASE_URI"] = "postgres:///ealgis"
        app.config["BROWSERID_LOGIN_URL"] = "/api/0.1/login"
        app.config["BROWSERID_LOGOUT_URL"] = "/api/0.1/logout"
        with open("/etc/ealgis/secret_key") as secret_fd:
            secret_key = secret_fd.read().rstrip()
        app.config["SECRET_KEY"] = secret_key
        app.config["TESTING"] = True

        login_manager = LoginManager()
        login_manager.user_loader(self.get_user_by_id)
        login_manager.init_app(app)

        browserid = BrowserID()
        browserid.user_loader(self.browserid_get_user)
        browserid.init_app(app)

        return app
Beispiel #10
0
    def create_application():
        """Create a test Flask application.
        """
        ret_val = Flask(__name__)
        ret_val.testing = True
        ret_val.config["EXCEPTIONAL_API_KEY"] = "key"
        ret_val.config["EXCEPTIONAL_DEBUG_URL"] = environ.get(
            "EXCEPTIONAL_DEBUG_URL", "http://posttestserver.com/post.php"
        )
        ret_val.config["PROPAGATE_EXCEPTIONS"] = False

        @ret_val.route("/error")
        def error():
            """Do something that raises an exception.
            """
            1 / 0

        @ret_val.route("/http/<int:code>")
        def http(code):
            """Raises an HTTP exception.
            """
            abort(code)

        return ret_val
Beispiel #11
0
import copy
import requests
import json
import hmac
import math
import urllib
import urlparse
from hashlib import sha1

import collections

rcpart = Flask(__name__)
rcpart.config["GITHUB_CLIENT_ID"] = os.environ["GITHUB_CLIENT_ID"]
rcpart.config["GITHUB_CLIENT_SECRET"] = os.environ["GITHUB_CLIENT_SECRET"]
rcpart.config["GITHUB_BASE_URL"] = os.environ["GITHUB_BASE_URL"]
rcpart.config["PROPAGATE_EXCEPTIONS"] = True
application = rcpart

es = elasticsearch.Elasticsearch([os.environ["ES_HOST"]])

partCategories_string = ""
partCategories = {}

github_cache = pylru.lrucache(64)

from git import Repo

github = GitHub(rcpart)

SOCIAL_BOTS = [
    "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)",
Beispiel #12
0
from flask import Flask, render_template, request
from uwsgidecorators import *
import pytronics
import os, time

public = Flask(__name__)
public.config["PROPAGATE_EXCEPTIONS"] = True

# Include "no-cache" header in all POST responses
@public.after_request
def add_no_cache(response):
    if request.method == "POST":
        response.cache_control.no_cache = True
    return response


# config for upload
ALLOWED_EXTENSIONS = set(["png", "jpg", "jpeg", "gif"])
ALLOWED_DIRECTORIES = set(["static/uploads/", "static/pictures/"])
LIVE_PINS = ["LED", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"]
# public.config['MAX_CONTENT_LENGTH'] = 4 * 1024 * 1024

### Home page ###
@public.route("/")
@public.route("/index.html")
def default_page():
    try:
        with open("/etc/hostname", "r") as f:
            name = f.read().strip().capitalize()
    except:
        name = "Rascal"
from flask import Flask, Response
import json
from datetime import datetime
import gensim
from gensim.models import Word2Vec, Phrases
import sys
import os

w2v_api = Flask(__name__)
w2v_api.config["PROPAGATE_EXCEPTIONS"] = True

cached_synonyms = {}
start = datetime.now()
print("start loading w2v " + str(start))
# w2v_model = Word2Vec.load_word2vec_format('GoogleNews-vectors-negative300.bin', binary=True)  # C binary format
# w2v_model = Word2Vec.load("en_1000_no_stem/en.model") # MemoryError :-(
try:
    model_filepath = sys.argv[1]
    if model_filepath in ["-d", "--daemonize"]:
        raise IndexError
    w2v_model = Word2Vec.load(model_filepath)  # C binary format
except IndexError:
    print("using default model")
    current_dir = os.path.dirname(__file__)
    model_filepath = os.path.join(
        current_dir, "model_sentences_raw_words_trigrams_min_count_50_size_200_downsampling_0.001.bin"
    )
    w2v_model = Word2Vec.load(model_filepath)  # C binary format
print("using model from " + model_filepath)

bigrams_model_name = "bigrams_model_nyt_sentences_5.5M_5.bin"
from flask import Flask
from flask import request
from flask import jsonify
from sentimenter import CNNSentimenter

application = Flask(__name__)
application.config["PROPAGATE_EXCEPTIONS"] = True
sent = CNNSentimenter()


@application.route("/getsentiment", methods=["GET"])
def getsentiment():
    inputtext = request.args.get("text", "")
    return jsonify(sent.computeSentiment(inputtext))


if __name__ == "__main__":
    application.run(host="0.0.0.0", port=8000)
Beispiel #15
0
import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.orm import mapper, relationship, backref

STATIC_PATH = "/static"
STATIC_FOLDER = os.path.join("..", "static")
TEMPLATE_FOLDER = os.path.join("..", "templates")

# create database
SQLALCHEMY_DATABASE_FILE = "bigbang.db"

app = Flask(__name__, static_url_path=STATIC_PATH, static_folder=STATIC_FOLDER, template_folder=TEMPLATE_FOLDER)

app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + SQLALCHEMY_DATABASE_FILE
app.config["PROPAGATE_EXCEPTIONS"] = True  # for debugging; turn off when deployed

# create database object
db = SQLAlchemy(app)

from model.planet import Planet
from model.feed import Feed
from model.feed_content import FeedContent

Planet.feed = relationship(Feed, backref=backref("planet"))
Feed.feed_content = relationship(FeedContent, cascade="delete", backref=backref("feed"))


from bigbang.view import admin
Beispiel #16
0
from sqlalchemy.dialects import postgresql
from collections import defaultdict
from setup import *

import traceback
import zlib
import json
import sys
import os

from stats import statsmgr

is_debug_mode = ("DEBUG" in os.environ) or ("DEBUG" in sys.argv)

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

##############################################################################
## Database Stuff
##############################################################################
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

if is_debug_mode:
    # Sqlite for debug mode
    app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://"
else:
    app.config["SQLALCHEMY_DATABASE_URI"] = os.environ["DATABASE_URL"]

db = SQLAlchemy(app)

Beispiel #17
0
def create_app():
    app = Flask(__name__)
    app.config["PROPAGATE_EXCEPTIONS"] = True
    app.register_blueprint(root)
    return app
Beispiel #18
0
        if isinstance(v, collections.Mapping):
            r = update(d.get(k, {}), v)
            d[k] = r
        else:
            d[k] = u[k]
    return d


# Init the rcbuild.info app.
rcbuild = Flask(__name__)
sslify = SSLify(rcbuild, skips=["healthz"])
rcbuild.config["GITHUB_CLIENT_ID"] = os.environ["GITHUB_CLIENT_ID"]
rcbuild.config["GITHUB_CLIENT_SECRET"] = os.environ["GITHUB_CLIENT_SECRET"]
rcbuild.config["GITHUB_BASE_URL"] = os.environ["GITHUB_BASE_URL"]
rcbuild.config["GITHUB_AUTH_URL"] = os.environ["GITHUB_AUTH_URL"]
rcbuild.config["PROPAGATE_EXCEPTIONS"] = True
rcbuild.config["PERMANENT_SESSION_LIFETIME"] = 365 * 24 * 60 * 60
rcbuild.secret_key = os.environ["SESSION_SECRET_KEY"]
application = rcbuild

FERNET_KEY = os.environ["FERNET_KEY"]
f = Fernet(FERNET_KEY)

es = elasticsearch.Elasticsearch([os.environ["ES_HOST"]])

SILENT_COMMIT_MESSAGE = "Silently upgrade - "

partCategories_string = ""
partCategories = {}

buildSkeleton = {}
Beispiel #19
0
    def test_dispatcher(self):
        app = Flask(__name__)
        app.config["PROPAGATE_EXCEPTIONS"] = True

        @app.route("/")
        @app.route("/", subdomain="<sub>")
        @app.route("/<path:path>")
        @app.route("/<path:path>", subdomain="<sub>")
        def catchall(sub="", path=None):
            return jsonify(app=[sub, request.script_root, request.path, request.query_string.decode("utf8")])

        def dummy_fetcher(url):
            return {"string": "dummy " + url}

        def assert_app(url, host, script_root, path, query_string=""):
            """The URL was dispatched to the app with these parameters."""
            assert json.loads(dispatcher(url)["string"]) == {"app": [host, script_root, path, query_string]}

        def assert_dummy(url):
            """The URL was not dispatched, the default fetcher was used."""
            assert dispatcher(url)["string"] == "dummy " + url

        # No SERVER_NAME config, default port
        with app.test_request_context(base_url="http://a.net/b/"):
            dispatcher = make_url_fetcher(next_fetcher=dummy_fetcher)
        assert_app("http://a.net/b", "", "/b", "/")
        assert_app("http://a.net/b/", "", "/b", "/")
        assert_app("http://a.net/b/c/d?e", "", "/b", "/c/d", "e")
        assert_app("http://a.net:80/b/c/d?e", "", "/b", "/c/d", "e")
        assert_dummy("http://a.net/other/prefix")
        assert_dummy("http://subdomain.a.net/b/")
        assert_dummy("http://other.net/b/")
        assert_dummy("http://a.net:8888/b/")
        assert_dummy("https://a.net/b/")

        # Change the context’s port number
        with app.test_request_context(base_url="http://a.net:8888/b/"):
            dispatcher = make_url_fetcher(next_fetcher=dummy_fetcher)
        assert_app("http://a.net:8888/b", "", "/b", "/")
        assert_app("http://a.net:8888/b/", "", "/b", "/")
        assert_app("http://a.net:8888/b/cd?e", "", "/b", "/cd", "e")
        assert_dummy("http://subdomain.a.net:8888/b/")
        assert_dummy("http://a.net:8888/other/prefix")
        assert_dummy("http://a.net/b/")
        assert_dummy("http://a.net:80/b/")
        assert_dummy("https://a.net/b/")
        assert_dummy("https://a.net:443/b/")
        assert_dummy("https://a.net:8888/b/")

        # Add a SERVER_NAME config
        app.config["SERVER_NAME"] = "a.net"
        with app.test_request_context():
            dispatcher = make_url_fetcher(next_fetcher=dummy_fetcher)
        assert_app("http://a.net", "", "", "/")
        assert_app("http://a.net/", "", "", "/")
        assert_app("http://a.net/b/c/d?e", "", "", "/b/c/d", "e")
        assert_app("http://a.net:80/b/c/d?e", "", "", "/b/c/d", "e")
        assert_app("https://a.net/b/c/d?e", "", "", "/b/c/d", "e")
        assert_app("https://a.net:443/b/c/d?e", "", "", "/b/c/d", "e")
        assert_app("http://subdomain.a.net/b/", "subdomain", "", "/b/")
        assert_dummy("http://other.net/b/")
        assert_dummy("http://a.net:8888/b/")

        # SERVER_NAME with a port number
        app.config["SERVER_NAME"] = "a.net:8888"
        with app.test_request_context():
            dispatcher = make_url_fetcher(next_fetcher=dummy_fetcher)
        assert_app("http://a.net:8888", "", "", "/")
        assert_app("http://a.net:8888/", "", "", "/")
        assert_app("http://a.net:8888/b/c/d?e", "", "", "/b/c/d", "e")
        assert_app("https://a.net:8888/b/c/d?e", "", "", "/b/c/d", "e")
        assert_app("http://subdomain.a.net:8888/b/", "subdomain", "", "/b/")
        assert_dummy("http://other.net:8888/b/")
        assert_dummy("http://a.net:5555/b/")
        assert_dummy("http://a.net/b/")
Beispiel #20
0
#!/usr/bin/env python

import os
import re

from flask import Flask, redirect
from tumblpy import Tumblpy

import app_config

app = Flask(app_config.PROJECT_NAME)
app.config["PROPAGATE_EXCEPTIONS"] = True


@app.route("/dear-mr-president/", methods=["POST"])
def _post_to_tumblr():
    """
    Handles the POST to Tumblr.
    """

    def clean(string):
        """
        Formats a string all pretty.
        """
        return string.replace("-", " ").replace("id ", "I'd ").replace("didnt", "didn't").replace("i ", "I ")

    # Request is a global. Import it down here where we need it.
    from flask import request

    def strip_html(value):
        """
Beispiel #21
0
import sys

from flask import Flask

from httpobs.conf import DEVELOPMENT_MODE, API_PORT, API_PROPAGATE_EXCEPTIONS
from httpobs.website import add_response_headers
from httpobs.website.api import api
from httpobs.website.monitoring import monitoring_api


def __exit_with(msg: str) -> None:
    print(msg)
    sys.exit(1)


# Register the application with flask
app = Flask("http-observatory")
app.config["PROPAGATE_EXCEPTIONS"] = API_PROPAGATE_EXCEPTIONS
app.register_blueprint(api)
app.register_blueprint(monitoring_api)


@app.route("/")
@add_response_headers()
def main() -> str:
    return "Welcome to the HTTP Observatory!"


if __name__ == "__main__":
    app.run(debug=DEVELOPMENT_MODE, port=API_PORT)