Example #1
1
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 #2
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 #3
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 #4
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 #5
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
Example #6
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
Example #7
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
    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))
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
0
def app(config):
    auth.Username = config["Webserver"].get("Username")
    auth.Password = config["Webserver"].get("Password")

    app = Flask(config["Webserver"].get("BasicRealm"))
    auth.for_all_routes(app)
    app.config["SERVER_NAME"] = config["Webserver"].get("ServerName")

    api = restful.Api(app=app, prefix="/v{}".format(API_VERSION))

    if config["Modules"].getboolean("PXE"):
        from . import pxe

        api.add_resource(pxe.PXECollection, "/pxe")
        api.add_resource(pxe.PXEObject, "/pxe/<ip_address>")

    if config["Modules"].getboolean("VM"):
        from . import vm

        api.add_resource(vm.VMCollection, "/vm")
        api.add_resource(vm.VMObject, "/vm/<uuid>")
        api.add_resource(vm.VMCommand, "/vm/<uuid>/action")

    if config["Modules"].getboolean("INSTALLIMAGE"):
        from . import installimage

        api.add_resource(installimage.InstallimageCollection, "/installimage")
        api.add_resource(installimage.InstallimageObject, "/installimage/<mac>")
        api.add_resource(installimage.InstallimageConfigCommand, "/installimage/<mac>/config")

    @app.errorhandler(404)
    def not_found(ex):
        resp = jsonify_nl(message="Route not found.", status=404)
        resp.status_code = 404
        return resp

    @app.errorhandler(401)
    def not_found(ex):
        resp = jsonify_nl(message="Unauthorized", status=401)
        resp.status_code = 401
        return resp

    return app
Example #16
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()
Example #17
0
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 #18
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 #19
0
File: server.py Project: metaxy/ipa
    db.session.commit()


if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser()
    parser.add_argument("-d", "--debug", action="store_true")
    parser.add_argument("-n", "--no-reload", action="store_true")
    parser.add_argument("-b", "--database", type=str, default="test.db")
    parser.add_argument("-c", "--create-db", action="store_true")
    parser.add_argument("-p", "--port", type=int, default=8080)
    args = parser.parse_args()

    if args.debug:
        app.debug = True
        app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + args.database

    if args.create_db:
        if args.debug:
            import os

            try:
                os.remove(args.database)
            except:
                pass
        create_test_db()
    else:
        if args.port is not None:
            app.config["SERVER_NAME"] = "localhost:" + str(args.port)
        app.run(host="0.0.0.0", use_reloader=not args.no_reload)
Example #20
0
import datetime
import redis
from logging.handlers import SMTPHandler
from werkzeug.contrib.cache import RedisCache, SimpleCache
from flask import Flask, render_template, g, session, request
from flask.ext.assets import Environment, Bundle
from flask_s3 import FlaskS3
from sqlalchemy.orm.exc import NoResultFound
from radlibs import Client
from radlibs.table.user import User

PROJECT_ROOT = os.path.dirname(os.path.realpath(__file__))
app = Flask(__name__, static_folder=os.path.join(PROJECT_ROOT, "static"), static_url_path="/static")
app.secret_key = os.environ.get("SECRET_KEY")
if "SERVER_NAME" in os.environ:
    app.config["SERVER_NAME"] = os.environ["SERVER_NAME"]

if "SENDGRID_PASSWORD" in os.environ and not app.debug:
    mail_handler = SMTPHandler(
        "smtp.sendgrid.net",
        "errors@radlibs.info",
        ["andrew.lorente@gmail.com"],
        "Radlib error",
        (os.environ["SENDGRID_USERNAME"], os.environ["SENDGRID_PASSWORD"]),
    )
    mail_handler.setLevel(logging.ERROR)
    mail_handler.setFormatter(
        logging.Formatter(
            """
Message type:       %(levelname)s
Location:           %(pathname)s:%(lineno)d
Example #21
0
from flask import Flask, send_file, request, render_template, jsonify, make_response, url_for
import json
from functools import wraps
from hexagram import Hexagram, Trigram

app = Flask(__name__)
with app.app_context():
    app.config["SERVER_NAME"] = "cleromancer.herokuapp.com"


def json_resp():
    return {
        "hexagram": "/hexagram/nnnnnn.png, where n is 1 (solid bar) or 0 (broken bar). Hexagrams are built bottom to top.",
        "trigram": "/trigram/nnn.png, where n is 1 (solid bar) or 0 (broken bar). Trigrams are built bottom to top.",
        "digit_order": "Hexagrams and Trigrams are built using digits read from left to right.",
        "links": "See the Link header for full paths.",
    }


def link_dict(func, ep, *args, **kwargs):
    """ Build "Link" headers from a list of passed values
    kwargs only contains one key: it's passed to the url builder func
    we replace its value with the first, last, and next values, then build
    the url, and append as string
    """
    links = []
    with app.app_context():
        for idx, arg in enumerate(["first", "last", "next"]):
            # kwargs only contains a single key (hexagram or trigram)
            # its value is replaced by the first, next, and last digit sequences
            # args contains values for first, last next
Example #22
0
sys.path.append("/home/sunhwan/.local/lib/python2.7/site-packages/")
sys.path.append("/home/sunhwan/www/anmpathway/pathfinder/")

from flask import g, Flask, render_template
import os
from main import get_db, get_job_folder, download, status
import conf
import errno
from flask_mail import Mail, Message
import time

uuid = sys.argv[1]

if __name__ == "__main__":
    app = Flask(__name__, template_folder=os.path.join(conf.BASEDIR, "templates"))
    app.config["SERVER_NAME"] = conf.SERVER_NAME
    app.add_url_rule("/anmpathway.cgi/download/<uuid>/<filename>", "download", download)
    app.add_url_rule("/anmpathway.cgi/download/<uuid>", "download", download)
    app.add_url_rule("/anmpathway.cgi/status/<uuid>", "status", status)

    mail = None

    with app.app_context():
        db = get_db()
        cur = db.cursor()
        cur.execute("select * from job where uuid == ?", (uuid,))
        uuid, email, date, status = cur.fetchone()

        open(os.path.join(get_job_folder(uuid), "run.pid"), "w").write(str(os.getpid()))
        cur.execute("update job set status = ? where uuid = ?", ("R", uuid))
        db.commit()
Example #23
0
import ConfigParser


cnf = os.path.dirname(os.path.realpath(__file__)) + "/../etc/cli_explorer.cnf"
config = ConfigParser.ConfigParser()
if not config.read(cnf):
    print("Config file '%s' not found" % cnf)
    exit()

section = "api"
domain = config.get(section, "domain")
ip = config.get(section, "ip")

# Define the web container
api = Flask(__name__)
api.config["SERVER_NAME"] = domain

# Ensure the API has endpoint discovery
@api.route("/api")
@crossdomain(origin="*")
def index():
    return jsonify({"apis": ["/api/cli"]})


# Our primary API endpoint
@api.route("/api/cli", methods=["POST"])
@crossdomain(origin="*")
def execute():
    # We only accept POST with a form POST payload
    # This request has two required parameters
    required = ["command", "args"]
Example #24
0
sys.setdefaultencoding("utf8")

from web.models import utils, RedisHandler, RedisSessionInterface, cache, OauthBackend
from web.models.whoosh import SenIndexer, DocIndexer, DefinitionIndexer, Searcher
from web.config import CONFIG, ENV

app = Flask(__name__)
# root dir
app.config["ROOT_DIR"] = os.path.dirname(os.path.abspath(__file__))

# upload config
app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024
app.config["UPLOAD_FOLDER"] = app.config["ROOT_DIR"] + CONFIG["UPLAOD_DIR"]

# server config
app.config["SERVER_NAME"] = CONFIG["SERVER_NAME"]
app.config["CSRF_ENABLED"] = True
app.config["SECRET_KEY"] = os.urandom(24)

# gen basic auth
CONFIG["BASIC_AUTH"] = "Basic %s" % base64.encodestring("%s:%s" % (CONFIG["NAME"], CONFIG["PASSWORD"]))[:-1]

# session config
if "REDIS_SESSION" in CONFIG:
    r = redis.Redis(
        host=CONFIG["REDIS_SESSION"]["host"],
        port=CONFIG["REDIS_SESSION"]["port"],
        password=CONFIG["REDIS_SESSION"]["pass"],
    )
    app.permanent_session_lifetime = datetime.timedelta(days=365)
    app.session_interface = RedisSessionInterface(r)
Example #25
0
from flask import Flask, g
from views.party import party
from views.static import static
from views.upload_form import upload_form
from controllers.api import api
from database import db_session

mycorgi_app = Flask(__name__)

mycorgi_app.config["SERVER_NAME"] = "corgiorgy.com"

mycorgi_app.register_blueprint(party)
mycorgi_app.register_blueprint(static)
mycorgi_app.register_blueprint(upload_form)
mycorgi_app.register_blueprint(api)


@mycorgi_app.teardown_appcontext
def shutdown_session(exception=None):
    db = getattr(g, "_database", None)
    if db:
        db_session.remove()


if __name__ == "__main__":
    mycorgi_app.run(host="0.0.0.0", debug=False)
Example #26
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 #27
0
import logging
import jinja2_highlight  # This isn't used directly, but it's a sanity check

app = Flask(__name__)
app.jinja_options["extensions"].append("jinja2_highlight.HighlightExtension")
limiter = Limiter(app, global_limits=["20 per minute"])

# Load configuration from the environment
secret_key = os.environ.get("SECRET_KEY")
signing_key = os.environ.get("SIGNING_KEY")
if not secret_key:
    raise Exception("SECRET_KEY not set")
if not signing_key:
    raise Exception("SIGNING_KEY not set")

app.config["SERVER_NAME"] = os.environ.get("SERVER_NAME")
app.config["SECRET_KEY"] = secret_key
app.config["BOT_NAME"] = "edsgar"
app.config["SESSION_LIFETIME_DAYS"] = 90  # Used in a template

tokenizer = Tokenizer(signing_key)

app.permanent_session_lifetime = timedelta(days=app.config["SESSION_LIFETIME_DAYS"])


@app.before_request
def before_request():
    session.permanent = True


# This is needed because of a stupid, old bug in Flask
Example #28
0
        if "_method" in environ.get("QUERY_STRING", ""):
            args = url_decode(environ["QUERY_STRING"])
            method = args.get("_method")
            if method:
                method = method.encode("ascii", "replace")
                environ["REQUEST_METHOD"] = method.upper()
        return self.app(environ, start_response)


app = Flask(__name__)
my_ip = requests.get("http://httpbin.org/ip").json()["origin"]
print ("Running on %s" % my_ip)
app.wsgi_app = MethodRewriteMiddleware(app.wsgi_app)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///../db-dev.sqlite"
app.config["SECRET_KEY"] = "supersecret"
app.config["SERVER_NAME"] = "sasha.zza.no"
app.config["PREFERRED_URL_SCHEME"] = "https"
db = SQLAlchemy(app)


def wants_json():
    best = request.accept_mimetypes.best_match(["application/json", "text/html"])
    return best == "application/json" and request.accept_mimetypes[best] > request.accept_mimetypes["text/html"]


class Unit(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    alias = db.Column(db.String(50), default="")
    description = db.Column(db.Text())
    ip = db.Column(db.String(46))
    unit_type = db.Column(db.String(30))
Example #29
0
app.config["SERVER_NAME"] = "test.test"

bp = Blueprint("bptest1", "bptest2")
SubdomainAttributeView.register(bp)
SubdomainRouteView.register(bp)
BasicView.register(bp, subdomain="sub3")

bp2 = Blueprint("bptest2", "bptest2", subdomain="sub4")
BasicView.register(bp2)

app.register_blueprint(bp)
app.register_blueprint(bp2)

client = app.test_client()


def test_bp_attr_subdomain():
    resp = client.get("/subdomainattribute/", base_url="http://sub1.test.test")
    eq_(b"Index", resp.data)


def test_bp_route_subdomain():
    resp = client.get("/subdomainroute/", base_url="http://sub2.test.test")
    eq_(b"Index", resp.data)


def test_bp_register_subdomain():
    resp = client.get("/basic/", base_url="http://sub3.test.test")
    eq_(b"Index", resp.data)


def test_bp_bp_subdomain():
    resp = client.get("/basic/", base_url="http://sub4.test.test")
    eq_(b"Index", resp.data)


########NEW FILE########
__FILENAME__ = test_common
from flask import Flask, url_for
from .view_classes import BasicView, IndexView
from nose.tools import *

app = Flask("common")
BasicView.register(app)
IndexView.register(app)

client = app.test_client()


def test_index():
    resp = client.get("/basic/")
    eq_(b"Index", resp.data)


def test_get():
    resp = client.get("/basic/1234")
    eq_(b"Get 1234", resp.data)


def test_put():
    resp = client.put("/basic/1234")
    eq_(b"Put 1234", resp.data)


def test_patch():
    resp = client.patch("/basic/1234")
    eq_(b"Patch 1234", resp.data)


def test_post():
    resp = client.post("/basic/")
    eq_(b"Post", resp.data)


def test_delete():
    resp = client.delete("/basic/1234")
    eq_(b"Delete 1234", resp.data)


def test_custom_method():
    resp = client.get("/basic/custom_method/")
    eq_(b"Custom Method", resp.data)


def test_custom_method_with_params():
    resp = client.get("/basic/custom_method_with_params/1234/abcd")
    eq_(b"Custom Method 1234 abcd", resp.data)


def test_routed_method():
    resp = client.get("/basic/routed/")
    eq_(b"Routed Method", resp.data)


def test_multi_routed_method():
    resp = client.get("/basic/route1/")
    eq_(b"Multi Routed Method", resp.data)

    resp = client.get("/basic/route2/")
    eq_(b"Multi Routed Method", resp.data)


def test_no_slash():
    resp = client.get("/basic/noslash")
    eq_(b"No Slash Method", resp.data)


def test_index_view_index():
    resp = client.get("/")
    eq_(b"Index", resp.data)


def test_custom_http_method():
    resp = client.post("/basic/route3/")
    eq_(b"Custom HTTP Method", resp.data)


def test_docstrings():
    proxy_func = app.view_functions["BasicView:index"]
    eq_(proxy_func.__doc__, BasicView.index.__doc__)


########NEW FILE########
__FILENAME__ = test_decorators
from flask import Flask, url_for
from .view_classes import DecoratedView
from nose.tools import *

app = Flask("decorated")
DecoratedView.register(app)
client = app.test_client()


def test_func_decorator_index():
    resp = client.get("/decorated/")
    eq_(b"Index", resp.data)


def test_func_decorator_get():
    resp = client.get("/decorated/1234")
    eq_(b"Get 1234", resp.data)


def test_recursive_decorator_post():
    resp = client.post("/decorated/")
    eq_(b"Post", resp.data)


def test_more_recursive_decorator_get():
    resp = client.get("/decorated/get_some/")
    eq_(b"Get Some", resp.data)


def test_multiple_recursive_decorators_get():
    resp = client.get("/decorated/get_this/")
    eq_(b"Get This", resp.data)


def test_routes_with_recursive_decorators():
    resp = client.get("/decorated/mixitup/")
    eq_(b"Mix It Up", resp.data)


def test_recursive_with_parameter():
    resp = client.get("/decorated/someval/1234")
    eq_(b"Someval 1234", resp.data)


def test_recursive_with_route_with_parameter():
    resp = client.get("/decorated/anotherval/1234")
    eq_(b"Anotherval 1234", resp.data)


def test_params_decorator():
    resp = client.get("/decorated/params_decorator_method/")
    eq_(b"Params Decorator", resp.data)


def test_params_decorator_delete():
    resp = client.delete("/decorated/1234")
    eq_(b"Params Decorator Delete 1234", resp.data)


########NEW FILE########
__FILENAME__ = test_endpoints
from flask import Flask, url_for
from .view_classes import BasicView, IndexView, RouteBaseView, VarBaseView
from nose.tools import *

app = Flask("common")
BasicView.register(app)
IndexView.register(app)
RouteBaseView.register(app)
VarBaseView.register(app)

client = app.test_client()


def test_index_url():
    with app.test_request_context():
        url = url_for("IndexView:index")
        eq_("/", url)


def test_basic_index_url():
    with app.test_request_context():
        url = url_for("BasicView:index")
        eq_("/basic/", url)


def test_custom_endpoint_url():
    with app.test_request_context():
        url = url_for("basic_endpoint")
        eq_("/basic/endpoint/", url)


def test_custom_route_base():
    with app.test_request_context():
        url = url_for("RouteBaseView:index")
        eq_("/base-routed/", url)


def test_variable_route_popped_base():
    with app.test_request_context():
        url = url_for("VarBaseView:index", route="bar")
        eq_("/var-base-route/bar/", url)


def test_variable_route_base():
    with app.test_request_context():
        url = url_for("VarBaseView:with_base_arg", route="bar")
        eq_("/var-base-route/bar/with_base_arg/", url)


def test_variable_route_base_with_local_route_var():
    client = app.test_client()
    resp = client.get("/var-base-route/bar/local/baz")
    eq_(resp.data, b"bar baz")


########NEW FILE########
__FILENAME__ = test_inheritance
from flask import Flask
from .view_classes import InheritanceView, DecoratedInheritanceView
from nose.tools import *

app = Flask("inheritance")
InheritanceView.register(app)
DecoratedInheritanceView.register(app)

client = app.test_client()


def test_index():
    resp = client.get("/inheritance/")
    eq_(b"Index", resp.data)


def test_override():
    resp = client.get("/inheritance/1234")
    eq_(b"Inheritance Get 1234", resp.data)


def test_inherited():
    resp = client.post("/inheritance/")
    eq_(b"Post", resp.data)


def test_with_route():
    resp = client.get("/inheritance/with_route")
    eq_(b"Inheritance with route", resp.data)


def test_override_with_route():
    resp = client.delete("/inheritance/1234/delete")
    eq_(b"Inheritance Delete 1234", resp.data)


def test_inherited_base_route():
    resp = client.get("/inheritance/routed/")
    eq_(b"Routed Method", resp.data)


def test_decorated_inherited_mixitup():
    resp = client.get("/decoratedinheritance/mixitup/")
    eq_(b"Mix It Up", resp.data)


def test_decorated_inheritance_get():
    resp = client.get("/decoratedinheritance/1234")
    eq_(b"Decorated Inheritance Get 1234", resp.data)


########NEW FILE########
__FILENAME__ = test_method_detection
from flask_classy import get_interesting_members, FlaskView
from .view_classes import VariedMethodsView, SubVariedMethodsView
from nose.tools import *


def test_special_method_detected():
    members = [m[1] for m in get_interesting_members(FlaskView, VariedMethodsView)]
    assert VariedMethodsView.index in members


def test_routed_method_detected():
    members = [m[1] for m in get_interesting_members(FlaskView, VariedMethodsView)]
    assert VariedMethodsView.routed_method in members


def test_classmethod_ignored():
    members = [m[1] for m in get_interesting_members(FlaskView, VariedMethodsView)]
    assert VariedMethodsView.class_method not in members


def test_subclass_classmethod_ignored():
    members = [m[1] for m in get_interesting_members(FlaskView, SubVariedMethodsView)]
    assert SubVariedMethodsView.class_method not in members
    assert VariedMethodsView.class_method not in members


########NEW FILE########
__FILENAME__ = test_route_base
from flask import Flask
from .view_classes import BasicView, RouteBaseView
from nose.tools import *

app = Flask("route_base")
RouteBaseView.register(app, route_base="/rb_test2/")


def test_route_base_override():
    client = app.test_client()
    resp = client.get("/rb_test2/")
    eq_(b"Index", resp.data)


########NEW FILE########
__FILENAME__ = test_route_prefix
from flask import Flask
from .view_classes import BasicView, RoutePrefixView, RouteBaseView
from nose.tools import *

app = Flask("route_base")

RoutePrefixView.register(app)
RouteBaseView.register(app, route_prefix="/prefix/")
BasicView.register(app, route_prefix="/prefix/")


def test_route_prefix():
    client = app.test_client()
    resp = client.get("/my_prefix/routeprefix/")
    eq_(b"Index", resp.data)


def test_route_prefix_override():
    client = app.test_client()
    resp = client.get("/prefix/basic/")
    eq_(b"Index", resp.data)


def test_route_prefix_with_route_base():
    client = app.test_client()
    resp = client.get("/prefix/base-routed/")
    eq_(b"Index", resp.data)


########NEW FILE########
__FILENAME__ = test_subdomains
from flask import Flask, url_for
from .view_classes import BasicView, IndexView
from nose.tools import *

app = Flask("common")
app.config["SERVER_NAME"] = "test.test"
Example #30
0
        return BASE.find(url[0]) * 62 * 62 + BASE.find(url[1]) * 62 + BASE.find(url[2])


class RegexConverter(BaseConverter):
    def __init__(self, url_map, *items):
        super(RegexConverter, self).__init__(url_map)
        self.regex = items[0]


## app settings
app = Flask(__name__)
app.debug = True
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///shortener.db"
app.secret_key = "DEV"
app.url_map.converters["regex"] = RegexConverter
app.config["SERVER_NAME"] = "dev.app:5000"
db = SQLAlchemy(app)
app.config.from_object(__name__)


## db stuffs
class Url(db.Model):
    __tablename__ = "Urls"
    long_url = db.Column(db.String, nullable=False)
    short_url = db.Column(db.String, nullable=False)
    short_url_id = db.Column(db.Integer, nullable=False, primary_key=True, autoincrement=False)

    def __init__(self, long_url, short_url, short_url_id):
        self.long_url = long_url
        self.short_url = short_url
        self.short_url_id = short_url_id