Example #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
Example #2
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 #3
0
def create_app():
    app = Flask(__name__, static_folder=None)
    app.config['SECRET_KEY'] = app_setting.secret_key
    app.config["SERVER_NAME"] = "%s:%s" % (app_setting.server_domain, app_setting.server_port)

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

    @app.errorhandler(500)
    def internal_server_error(e):
        return render_template('500.html'), 500

    @app.route('/', defaults={'url': ''})
    @app.route('/<path:url>')
    def general_page(url=None):
        replace_d = replace_domain(request.url, app_setting.proxy_domain, app_setting.proxy_port)
        new_path = remove_anchor(replace_d)

        page = PageManagement.get_page_obj(new_path,
                                           headers=head_convert_to_dict(request.headers),
                                           url=request.url)

        return send_from_directory(cache_dir, str(page))

    @app.route("/", subdomain="<sub>")
    @app.route("/<path:p>", subdomain="<sub>")
    def sub_domain_page(sub, p=None):
        replace_d = replace_sub_domain(request.url, app_setting.proxy_domain, app_setting.proxy_port)
        new_path = remove_anchor(replace_d)

        page = PageManagement.get_page_obj(new_path,
                                           headers=head_convert_to_dict(request.headers),
                                           url=request.url)
        return send_from_directory(cache_dir, str(page))

    return app
Example #4
0
from flask import (Flask, render_template, request, redirect, session, g, jsonify,
                   flash, send_from_directory, abort, make_response)
import sys, redis
import ordereddict
import markdown
import html2text
import feedparser

r = redis.StrictRedis(host='localhost', port=6379, db=4)
#r.flushdb()

md = markdown.Markdown(safe_mode="escape", output_format='html4')
h2t = html2text.HTML2Text()
                   
app = Flask(__name__)
app.config["SERVER_NAME"] = "localhost:5000"

@app.route("/", methods=['GET', 'POST'])
def register():
	if request.method == 'GET':
		return render_template("index.html")
	if request.method == 'POST':
		error = None
		if not request.form['register_url']:
			return render_template("index.html", error="Form data missing")
		try:
			register_url = request.form['register_url']
			data = urlopen(register_url)
		except Exception,e:
			return render_template("index.html", error="Profile not found at " + register_url, register_url = register_url)
		try:
Example #5
0
from flask import (Flask, render_template, request, redirect, session, g, jsonify,
                   flash, send_from_directory, abort, make_response)
import sys, redis
import ordereddict
import markdown
import html2text
import feedparser

r = redis.StrictRedis(host='localhost', port=6379, db=4)
#r.flushdb()

md = markdown.Markdown(safe_mode="escape", output_format='html4')
h2t = html2text.HTML2Text()
                   
app = Flask(__name__)
app.config["SERVER_NAME"] = "eeepc:5000"

@app.route("/", methods=['GET', 'POST'])
def register():
	if request.method == 'GET':
		return render_template("index.html")
	if request.method == 'POST':
		error = None
		if not request.form['register_url']:
			return render_template("index.html", error="Form data missing")
		try:
			register_url = request.form['register_url']
			data = urlopen(register_url)
		except Exception,e:
			return render_template("index.html", error="Profile not found at " + register_url, register_url = register_url)
		try:
Example #6
0
from newparp.model.connections import (
    db_commit,
    db_disconnect,
    redis_connect,
    redis_disconnect,
    set_cookie,
)


app = Flask(__name__)
app.url_map.strict_slashes = False


# Config

app.config["SERVER_NAME"] = os.environ["BASE_DOMAIN"]
app.config["SENTRY_PRIVATE_DSN"] = os.environ.get("SENTRY_PRIVATE_DSN", None)
app.config["SENTRY_PUBLIC_DSN"] = os.environ.get("SENTRY_PUBLIC_DSN", None)
app.config['PROPAGATE_EXCEPTIONS'] = True

if app.config["SENTRY_PRIVATE_DSN"]:  # pragma: no cover
    from raven.contrib.flask import Sentry
    app.config["SENTRY_INCLUDE_PATHS"] = ["newparp"]
    sentry = Sentry(app,
        dsn=app.config["SENTRY_PRIVATE_DSN"],
        logging=True,
        level=logging.ERROR,
    )
    logging.getLogger("sentry.errors.uncaught").setLevel(logging.CRITICAL)
else:
    sentry = None
Example #7
0
import ob2.config as config
import ob2.mailer as mailer
from ob2.util.authentication import user_id
from ob2.util.security import generate_shitty_random_string, get_request_validity
from ob2.util.github_login import is_ta
from ob2.util.templating import JINJA_EXPORTS

app = Flask("ob2.web", static_url_path=("%s/static" % config.web_public_root))
if config.web_behind_proxy:
    app.wsgi_app = ProxyFix(app.wsgi_app)
app.logger.addHandler(StreamHandler(sys.stdout))
app.debug = config.debug_mode
app.config["SESSION_COOKIE_PATH"] = config.web_public_root
app.config["SESSION_COOKIE_SECURE"] = config.web_https
app.config["SERVER_NAME"] = config.web_public_host
app.jinja_env.globals.update(JINJA_EXPORTS)

# We need to tell our mailer daemon about the web application, so that we can use url_for() to
# generate URL's in our email templates. We can't just import "app" from this module, because that
# would create a cyclic import dependency.
mailer.register_app(app)

cache_buster_hash = generate_shitty_random_string(8)


for blueprint in ("onboarding",
                  "dashboard",
                  "ta",
                  "pushhook"):
    module = import_module("ob2.web.blueprints.%s" % blueprint)
Example #8
0
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"
BasicView.register(app, subdomain="basic")

client = app.test_client()

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

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

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

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

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

def test_delete():
Example #9
0
        # return all objects with "last_modified" date in reverse order
        for key in relevant_keys:
            for item in model[key]:
                if "last_modified" in item:
                    data.append(item)
        data = sorted(data, key=lambda k: k['last_modified'], reverse=True)
    return jsonify(gather_ids(data))


if __name__ == "__main__":
    app.run(debug=True)
else:
    # production mode - replace all URLs
    print("WARNING: Running reference server in production mode.")
    print("You don't want that unless you are hosting http://refserv.oparl.org/")
    app.config["SERVER_NAME"] = "refserv.oparl.org"

    def replace_hostname(m, hostname):
        if type(m) == dict:
            for key in m.keys():
                m[key] = replace_hostname(m[key], hostname)
        elif type(m) == list:
            for n in range(len(m)):
                m[n] = replace_hostname(m[n], hostname)
        elif type(m) == unicode:
            m = m.replace("127.0.0.1:5000", hostname)
        return m

    model = replace_hostname(model, app.config["SERVER_NAME"])

    print(app.config)
Example #10
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
            for k in kwargs.keys():
                kwargs[k] = args[idx]
            kwargs['_external'] = True
Example #11
0
from flask import Flask

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://"  # in memory database
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SQLALCHEMY_ECHO"] = True
app.config["DEBUG"] = True
app.config["SERVER_NAME"] = "127.0.0.1:8080"
Example #12
0
# coding=utf-8
from flask import Flask, g

app = Flask(__name__)
app.config["SERVER_NAME"] = "example.com:9000"


@app.url_value_preprocessor
def get_side(endpoint, values):
    g.site = values.pop("subdomain")


app.route("/", subdomain="<subdomain>")


def index():
    return g.site


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=9000, debug=True)
Example #13
0
from flask import Flask, request
from flask_restful import Resource, Api
from json import dumps


class GitFailedStatus(Resource):
    def get(self):
        return {
          "state": "failure",
          "target_url": "https://kk.com:5000/git_response",
          "description": "Manual response"
        }

if __name__ == '__main__':
    app = Flask(__name__)
    app.config["SERVER_NAME"] = "kk.com:5000"
    api = Api(app)
    api.add_resource(GitFailedStatus, '/git')
    app.run(host='0.0.0.0')
from flask import render_template
from flask_bootstrap import Bootstrap
from flask.ext.babel import Babel

try:
    from local import API_KEY, DEBUG, CONCURRENT_API, FLASK_THREADED, SERVER_NAME  # local.py optional
except ImportError:
    API_KEY = ""                        # from https://steamcommunity.com/dev/apikey
    DEBUG = False                       # Enable debugging (default False)
    CONCURRENT_API = 8                  # How many concurrent Steam API requests to make (default 8)
    FLASK_THREADED = True               # Run multithreaded Flask (default True)
    SERVER_NAME = None                  # Hostname of server (default None)


app = Flask(__name__.split('.')[0])
app.config["SERVER_NAME"] = SERVER_NAME
Bootstrap(app)
babel = Babel(app)



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


@app.route('/game/<steam_id>/<app_id>')
def steamid_appid(steam_id=None, app_id=None):
    print("Connecting to Steam API server and populating friends...")
    me = MySteamFriends(
        api_key=API_KEY,
Example #15
0
from flask.ext.pagedown import PageDown


app = Flask(__name__)
app.config.from_object("config")
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
mail = Mail(app)
mailer = Mailer(app, mail)
pagedown = PageDown(app)

lm = LoginManager()
lm.init_app(app)
lm.login_view = "login"

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

Markdown(app)

if app.config.get("DEBUG"):
    app.config["SERVER_NAME"] = "localhost:8000"
else:
    app.config["SERVER_NAME"] = "kinkstruction.com"

# for key in sorted(app.config.keys()):
#     print key + ": " + str(app.config.get(key))

from app import views, models, mailer
Example #16
0
File: server.py Project: MWold/hal
@app.before_request
def check_auth():
    if request.args.get("key") != settings.KEY:
        if settings.ENV == "prod":
            if (
                    request.endpoint != "login" and
                    request.endpoint != "authorized" and
                    request.endpoint != "static"
                ):
                # Pebble request
                if request.method == "POST" and request.form.get("pebble_token"):
                    authorized_pebble_tokens = json.load(open("auth.json")).get("pebbles")
                    if request.form.get("pebble_token") not in authorized_pebble_tokens:
                        return "Unauthorized user"
                # Web request
                else:
                    access_token = session.get("access_token")
                    if access_token is None:
                        return redirect(url_for("login"))
                    authorized_emails = json.load(open("auth.json")).get("emails")
                    if session.get("email") not in authorized_emails:
                        return "Unauthorized user"

if __name__ == "__main__":
    if app.debug:
        app.config["SERVER_NAME"] = "localhost:8083"
    else:
        app.config["SERVER_NAME"] = "localhost:80"
    app.run()
Example #17
0
#!/usr/bin/env python
from flask import Flask, redirect, url_for, render_template, jsonify
from porc import Client
from humanize import intword
from secrets import ORCHESTRATE_KEY
import random
app = Flask(__name__)
app.config["SERVER_NAME"] = "chopmotto.ml"
orche = Client(ORCHESTRATE_KEY, "https://api.aws-eu-west-1.orchestrate.io/")
orche.ping().raise_for_status()

tops = [""]
bots = [""]

with open("top.txt") as f:
    for line in f:
        if len(line.strip()) > 0:
            tops.append(line.strip())
print("%i tops loaded" % (len(tops)-1))

with open("bottom.txt") as f:
    for line in f:
        if len(line.strip()) > 0:
            if not line.strip().endswith("."):
                line = line.strip() + "."
            bots.append(line)
print("%i bottoms loaded" % (len(bots)-1))

@app.route("/api/<int:t>/<int:b>")
@app.route("/api/r/<int:b>")
@app.route("/api/<int:t>/r")
Example #18
0
import flask
from flask import Flask, render_template, request, redirect, url_for, current_app, abort, jsonify
from flask.ext.login import LoginManager, login_required, login_user, logout_user, current_user
from flask.ext.principal import Principal, Permission, RoleNeed, UserNeed, PermissionDenied
from flask.ext.principal import Identity, AnonymousIdentity, identity_changed, identity_loaded

from functools import wraps


app = Flask(__name__)
app.config["SECRET_KEY"] = "123123123"
app.config["SERVER_NAME"] = "127.0.0.1:5007"

login_manager = LoginManager()
login_manager.init_app(app)

# load the extension
principals = Principal(app)

# Create a permission with a single Need, in this case a RoleNeed.
admin_permission = Permission(RoleNeed('admin'))
user_permission = Permission(RoleNeed('user'))

@app.errorhandler(PermissionDenied)
def handle_invalid_usage(error):
    response = jsonify(error.to_dict())
    response.status_code = error.status_code
    return response

def requires_roles(*roles):
    def wrapper(f):