Example #1
0
def create_server(config=None, **_options):
    """Returns a Flask server application. `config` is a path to a
    ``slicer.ini`` file with Cubes workspace and server configuration."""

    config = read_server_config(config)

    # Load extensions

    if config.has_option("server", "modules"):
        modules = shlex.split(config.get("server", "modules"))
        for module in modules:
            e = __import__(module)

    app = Flask(__name__.rsplit(".", 1)[0])
    # FIXME: read note about _options in Workspace. Only for internal use as a
    # temporary quick fix.
    app.register_blueprint(slicer, config=config, **_options)

    app.config["MAX_CONTENT_LENGTH"] = 1024 * 1024 * 512
    app.config["DEBUG"] = True
    return app
Example #2
0
def zoe_web_main() -> int:
    """
    This is the entry point for the Zoe Web script.
    :return: int
    """
    config.load_configuration()
    args = config.get_conf()
    if args.debug:
        logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT)
    else:
        logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
    logging.getLogger("requests").setLevel(logging.WARNING)
    logging.getLogger("tornado").setLevel(logging.DEBUG)

    log.info("Starting HTTP server...")
    app = Flask(__name__, static_url_path="/does-not-exist")
    app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024

    zoe_api.db_init.init()

    api_endpoint = zoe_api.api_endpoint.APIEndpoint()
    config.api_endpoint = api_endpoint

    app.register_blueprint(zoe_api.rest_api.api_init(api_endpoint))
    app.register_blueprint(zoe_api.web.web_init())

    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(args.listen_port, args.listen_address)
    ioloop = IOLoop.instance()

    retry_cb = PeriodicCallback(api_endpoint.retry_submit_error_executions, 30000)
    retry_cb.start()

    try:
        ioloop.start()
    except KeyboardInterrupt:
        print("CTRL-C detected, terminating")
Example #3
0
import os
import config
from predict import predict
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename

try:
    from flask_debugtoolbar import DebugToolbarExtension
except:
    pass


app = Flask(__name__)
app.debug = True
app.config["MAX_CONTENT_LENGTH"] = config.max_content_length * 1024 * 1024
app.config["UPLOAD_FOLDER"] = config.upload_folder
app.config["SECRET_KEY"] = "test."
app.config["DEBUG_TB_PANELS"] = (
    "flask_debugtoolbar.panels.headers.HeaderDebugPanel",
    "flask_debugtoolbar.panels.request_vars.RequestVarsDebugPanel",
)
try:
    toolbar = DebugToolbarExtension(app)
except:
    pass


ALLOWED_EXTENSIONS = set(config.allowed_extensions)

Example #4
0
File: main.py Project: rekyuu/kyoli
import os
from helpers import uploads
from flask import Flask, request, render_template, make_response, send_file


if not os.path.exists(config.UPLOAD_TO):
    os.makedirs(config.UPLOAD_TO)
    os.makedirs(config.UPLOAD_TO + "/audio")
    os.makedirs(config.UPLOAD_TO + "/file")
    os.makedirs(config.UPLOAD_TO + "/image")
    os.makedirs(config.UPLOAD_TO + "/text")
    os.makedirs(config.UPLOAD_TO + "/video")


app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = config.MAX_SIZE_MB * 1024 * 1024


@app.route("/")
def index():

    return render_template("index.html")


@app.route("/a/<audio>")
def render_audio(audio):

    location = config.UPLOAD_TO + "/audio/" + audio
    return send_file(location)

Example #5
0
from flask import Flask, request, send_from_directory, redirect, url_for, render_template

import interestingizer
from PIL import Image

import md5
import random
import os

app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024  # 16Mb upload file limit

TMP_DIR = "./tmp"
ITEMS_BASE = "./images/"
items = [Image.open(os.path.join(ITEMS_BASE, filename)).convert("RGBA") for filename in os.listdir(ITEMS_BASE)]


@app.route("/ping")
def ping():
    return "OK"


def cache_image(pil_img):
    global TMP_DIR
    key = md5.md5(pil_img.tostring()).hexdigest()
    with open(os.path.join(TMP_DIR, key), "w+") as fd:
        pil_img.save(fd, "JPEG", quality=70)
    return key


@app.route("/cache/<key>")
Example #6
0
from flask import Flask

__author__ = "an"

app = Flask(__name__, static_url_path="")
app.config["MAX_CONTENT_LENGTH"] = 50000000  # use base 10
app.debug = True

if __name__ == "__main__":
    from view import *

    host = "0.0.0.0"
    port = 10002
    app.run(host, port)
Example #7
0
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object("config")

db = SQLAlchemy(app)

ALLOWED_EXTENSIONS = set(["png", "jpg", "jpeg", "gif", "bmp"])
UPLOAD_FOLDER = "/static/uploads/"
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
app.config["ALLOWED_EXTENSIONS"] = ALLOWED_EXTENSIONS
app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024

# important, for some reason, that this stay down here
from app import views, models


import logging
from logging.handlers import RotatingFileHandler

file_handler = RotatingFileHandler("tmp/website.log", "a", 1 * 1024 * 1024, 10)
file_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]"))
app.logger.setLevel(logging.INFO)
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
app.logger.info("website startup")
Example #8
0
import StringIO

# from PIL import Image

import requests

# create Flask app
app = Flask(__name__)  # create our flask app


app = Flask(__name__)  # create our flask app
app.secret_key = os.environ.get(
    "SECRET_KEY"
)  # put SECRET_KEY variable inside .env file with a random string of alphanumeric characters
app.config["CSRF_ENABLED"] = False
app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024  # 16 megabyte file upload

# --------- Database Connection ---------
# MongoDB connection to MongoLab's database
mongoengine.connect("mydata", host=os.environ.get("MONGOLAB_URI"))
app.logger.debug("Connecting to MongoLabs")

ALLOWED_EXTENSIONS = set(["png", "jpg", "jpeg", "gif"])

# hardcoded categories for the checkboxes on the form
# categories = ['GEAR','TECH','FASHION','BODY','ART','RIDE','PLACE']


# --------- Routes ----------

Example #9
0
from routes.content import content

# Imports API modules
from api.account import api_account
from api.hash_table import api_hash_table
from api.languages import api_languages
from api.pages import api_pages
from api.rank import api_rank
from api.users import api_users


# Create application and configuration
app = Flask(__name__)
app.config.from_pyfile("config.py")
app.config.from_envvar("FLASKR_SETTINGS", silent=True)
app.config["MAX_CONTENT_LENGTH"] = 10 * 1024 * 1024  # 10 Mb Max Upload
app.test_request_context().push()

# regular expressions inside url routing
class RegexConverter(BaseConverter):
    def __init__(self, url_map, *items):
        super(RegexConverter, self).__init__(url_map)
        self.regex = items[0]


app.url_map.converters["regex"] = RegexConverter

LIST_MODULES = [
    login,
    api_account,
    api_hash_table,
Example #10
0
    CLIENT_SECRET_FILE = APACHE_ROOT + CLIENT_SECRET_FILE

CLIENT_ID = json.loads(open(CLIENT_SECRET_FILE, "r").read())["web"]["client_id"]

logger = logging.getLogger("app")
log_handler = logging.FileHandler(UPLOAD_FOLDER + "application.log")
formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
log_handler.setFormatter(formatter)
logger.addHandler(log_handler)
logger.setLevel(logging.DEBUG)

# Start Flask
app = Flask(__name__)
# Set upload folder and max content size for image uploads
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
app.config["MAX_CONTENT_LENGTH"] = 32 * 1024 * 1024  # Limit each upload to 32 MB

# Connect to the appropriate database and create database session
engine = None
if __name__ == "__main__":
    engine = create_engine("sqlite:///catalog.db")
else:
    engine = create_engine("postgresql://catalog:catalog@localhost/catalog")

Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
db_session = DBSession()


@app.route("/login")
def showLogin():
Example #11
0
from flask import Flask, send_file, request
from werkzeug.exceptions import BadRequest
import conf
from images import convert_image_with_vote
from utils import has_valid_extension


app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = conf.MAXIMUM_FILE_SIZE

FILE_NAME = "{vote}_{filename}"


@app.route("/pride", methods=["POST"])
def be_proud():
    vote = request.form.get("vote")
    if not vote:
        return BadRequest("A vote must be provided")

    image = request.files["image"]
    if not has_valid_extension(image.filename):
        return BadRequest("File type is not supported")

    converted_image = convert_image_with_vote(image, vote)

    response = send_file(
        converted_image, as_attachment=True, attachment_filename=FILE_NAME.format(vote="no", filename=image.filename)
    )

    return response
Example #12
0
from flask import Flask, request, render_template, redirect, session, url_for
from werkzeug import secure_filename
import db
import json
import os

app = Flask(__name__)
Flask.secret_key = "folio is short for portfolio"  # obvs temporary
app.config["MAX_CONTENT_LENGTH"] = 24 * 1024 * 1024  # max filesize 10mb
app.config["UPLOAD_FOLDER"] = "./static/uploads"
global ALLOWED_EXTENSIONS
ALLOWED_EXTENSIONS = set(["png", "jpg", "jpeg", "gif"])


@app.route("/", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        if "user" in session:
            username = session["user"]
            return redirect(url_for("home", username=username))
        return render_template("login.html")
    else:
        if "user" in session:
            return "we have issues right now."  # aka this is not a thing

        button = request.form["button"]
        if button == "Login":
            password = request.form["password"]
            username = request.form["login"]

            # check pass
Example #13
0
    api.SetOutputName("outputName");
    api.Init(".","eng",tesseract.OEM_DEFAULT)
    api.SetPageSegMode(tesseract.PSM_AUTO)
    mImgFile = "./output/trialone.png"
    api.SetRectangle(100,100,700,100)
    result = tesseract.ProcessPagesFileStream(mImgFile,api)
    print "result(ProcessPagesFileStream)=",result 
    """


UPLOAD_FOLDER = "./uploads"
ALLOWED_EXTENSIONS = set(["png", "jpg", "jpeg"])

app = Flask(__name__)
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
app.config["MAX_CONTENT_LENGTH"] = 6 * 1224 * 1632


def allowed_file(filename):
    return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS


@app.route("/processsubmitted", methods=["GET", "POST"])
def upload_file():
    print "upload method called"
    if request.method == "POST":
        print "upload method POST"
        file = request.files["file"]
        if file and allowed_file(file.filename):
            print "upload method", file.filename
            filename = file.filename  # secure_filename(file.filename)
Example #14
0
def generate_app(db_uri=AENEAS_DB_URI, max_content_length=AENEAS_MAX_CONTENT_LENGTH):

    app = Flask(__name__)
    app.config["SQLALCHEMY_DATABASE_URI"] = db_uri
    app.config["MAX_CONTENT_LENGTH"] = max_content_length
    db = app.db = SQLAlchemy(app)

    class Report(db.Model):
        id = db.Column(db.Integer, primary_key=True)
        raw = db.Column(db.Text(256000), nullable=False)
        product = db.Column(db.String(100), nullable=False)
        version = db.Column(db.String(100), nullable=False)
        timestamp = db.Column(db.DateTime, nullable=False)

        def __init__(self, raw, product, version, timestamp=None):
            self.raw = raw
            self.product = product
            self.version = version
            if timestamp is None:
                timestamp = datetime.datetime.utcnow()
            if isinstance(timestamp, basestring):
                timestamp = dparse(timestamp)
            self.timestamp = timestamp

        def to_dict(self):
            return {
                "id": self.id,
                "raw": self.raw,
                "product": self.product,
                "version": self.version,
                "timestamp": self.timestamp,
            }

    @app.route("/v1.0/reports", methods=["POST"])
    def submit_report():
        if request.content_type != "application/json":
            return (
                'Content-Type was "{}", but only "application/json" is ' "supported.".format(request.content_type),
                415,
            )
        if len(request.data) > app.config["MAX_CONTENT_LENGTH"]:
            return "", 413

        report_json = request.json

        if "product" not in report_json:
            return "No product specified", 400
        product = report_json["product"]
        if not isinstance(product, basestring):
            return "Product is wrong type", 400

        if "version" not in report_json:
            return "No version specified", 400
        version = report_json["version"]
        if not isinstance(version, basestring):
            return "Version is wrong type", 400

        if "X-Real-IP" in request.headers:
            report_json["server_remote_ip"] = request.headers["X-Real-IP"]
        else:
            report_json["server_remote_ip"] = request.remote_addr

        raw = json.dumps(report_json)

        report = Report(raw, product, version)
        db.session.add(report)
        db.session.commit()

        clean_up_report(report)
        db.session.add(report)
        db.session.commit()

        return "", 201

    def get_accept_type():
        best = request.accept_mimetypes.best_match(["application/json", "text/html"])
        if best == "text/html" and request.accept_mimetypes[best] >= request.accept_mimetypes["application/json"]:
            return "html"
        elif best == "application/json" and request.accept_mimetypes[best] >= request.accept_mimetypes["text/html"]:
            return "json"
        else:
            return None

    @app.route("/v1.0/reports", methods=["GET"])
    def list_reports():
        accept = get_accept_type()
        if accept is None:
            return "", 406

        reports = Report.query.all()

        if accept == "html":
            return render_template("list_reports.html", reports=reports, cycle=itertools.cycle)
        else:
            jreports = [json.loads(r.raw) for r in reports]
            return json.dumps(jreports), 200

    def clean_up_report(report):
        jraw = json.loads(report.raw)
        jraw["id"] = report.id
        report.raw = json.dumps(jraw)
        return report

    @app.route("/v1.0/reports/clean-up-all", methods=["GET"])
    def clean_up_all_reports():
        reports = Report.query.all()
        for report in reports:
            clean_up_report(report)
            db.session.add(report)
        db.session.commit()
        return redirect(url_for("list_reports"))

    @app.route("/v1.0/reports/<int:id>", methods=["GET"])
    def show_report(id):
        accept = get_accept_type()
        if accept is None:
            return "", 406

        report = Report.query.get(id)
        if report is None:
            return "", 404
        if accept == "html":
            raw = json.dumps(json.loads(report.raw), indent=2)
            return render_template("show_report.html", report=report, raw=raw)
        return report.raw, 200

    @app.route("/v1.0/reports/<int:id>/download", methods=["GET"])
    def download_report(id):
        report = Report.query.get(id)
        if report is None:
            return "", 404
        return report.raw, 200

    @app.route("/v1.0/diagnostics/show-full-request")
    def show_full_request():
        req = request
        # raise ZeroDivisionError
        return render_template("show_full_request.html", request=request, keys=dir(request), getattr=getattr)

    return app
Example #15
0
DEBUG = True

LOGO_FOLDER = r"./static/images/"
UPLOAD_FOLDER = r"/home/icsfsu/FlaskApp/uploads/"
DESC_FOLDER = r"./database/descs/"
RESUME_FOLDER = r"./database/resumes/"
ALLOWED_IMG_EXT = set(["png", "jpg", "jpeg", "gif"])
ALLOWED_TXT_EXT = set(["txt", "doc", "docx"])

app = Flask(__name__)
app.config["LOGO_FOLDER"] = LOGO_FOLDER
app.config["LOGO_ACCESS"] = LOGO_FOLDER
app.config["DESC_FOLDER"] = DESC_FOLDER
app.config["RESUME_FOLDER"] = RESUME_FOLDER
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
app.config["MAX_CONTENT_LENGTH"] = 30 * 1024  # limit for image files
app.secret_key = "asdfq3495basdfbsdpo2451"


#################################
#############WEBPAGE#############
#################################


@app.route("/favicon.ico")
def favicon():
    return send_from_directory(
        os.path.join(app.root_path, "static"), "favicon.ico", mimetype="image/vnd.microsoft.icon"
    )

Example #16
0
from flask import Flask
from flask_socketio import SocketIO
from celery import Celery
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.debug = False
app.config["MAX_CONTENT_LENGTH"] = 1000 ** 3

app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///cache/flask.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)

import flaskApp.models

db.create_all()

app.config["CELERY_BROKER_URL"] = "amqp://guest@localhost//"
app.config["CELERY_RESULT_BACKEND"] = "amqp://"
celery = Celery(app.import_name, backend=app.config["CELERY_RESULT_BACKEND"], broker=app.config["CELERY_BROKER_URL"])
celery.conf.update(app.config)
TaskBase = celery.Task


class ContextTask(TaskBase):
    abstract = True

    def __call__(self, *args, **kwargs):
        with app.app_context():
            return TaskBase.__call__(self, *args, **kwargs)
Example #17
0
    assets.url = parser.get("webserver", "static_url")

if parser.getboolean("webserver", "force_https"):
    try:
        from flask_sslify import SSLify

        sslify = SSLify(app, permanent=True)
    except ImportError:
        pass

if parser.getboolean("application", "debug"):
    app.debug = True

Scss(app, static_dir="static/css", asset_dir="static/sass", load_paths=["static/sass"])
app.secret_key = parser.get("application", "secret_key")
app.config["MAX_CONTENT_LENGTH"] = parser.get("webserver", "uploadsize") * 1024 * 1024
APPLICATION_NAME = parser.get("application", "name")

client = MongoClient()
db = client.pastedirectory


def static_url_for(filename):
    if parser.has_option("webserver", "static_url"):
        return parser.get("webserver", "static_url") + "/" + filename
    else:
        return url_for("static", filename=filename)


app.jinja_env.globals.update(static_url_for=static_url_for)
Example #18
0
        f.provide_automatic_options = False
        return update_wrapper(wrapped_function, f)

    return decorator


FILE_EXTS = ["jpeg", "jpg", "png", "gif", "webp", "webm"]
THUMBNAILABLE = ["jpeg", "jpg", "png", "gif"]
UPLOAD_FOLDER = "static/img/"
THUMBNAIL_FOLDER = "static/thumbnail/"

THUMBNAIL_MAX_AXIS_SIZE = 250

app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 16777216

db = redis.StrictRedis(host="localhost", port=6379, db=0)


def is_valid_file(fn):
    return "." in fn and fn.split(".")[-1] in FILE_EXTS


def file_extension(fn):
    return fn.split(".")[-1]


def img(ifn):
    return url_for("static", filename="img/" + ifn)
Example #19
0
import time
from flask import Flask, redirect, request, url_for, abort
from flask import render_template, send_file
from dropbox import client, rest, session
from xhtml2pdf import pisa
from cStringIO import StringIO
from werkzeug import secure_filename
from flask.ext.sqlalchemy import SQLAlchemy

APP_KEY = "0y9r8zwiz5mbyyj"
APP_SECRET = "s4gexoj4x1gt65s"
WORKING_FOLDER = "/Captaciones"

# init
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 5 * 1024 * 1024  # 6 Mb
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ["DATABASE_URL"]

db = SQLAlchemy(app)
sess = None
request_token = None
dropbox_client = None
flushed = True  # state variable.


class Token(db.Model):
    __tablename__ = "tokens"
    tokens_id = db.Column(db.Integer, primary_key=True)
    key = db.Column(db.String(50), unique=True)
    secret = db.Column(db.String(50), unique=True)
Example #20
0
# and send_from_directory will help us to send/show on the
# browser the file that the user just uploaded
from flask import Flask, render_template, request, redirect, url_for
from flask import send_from_directory
from werkzeug import secure_filename
from flask import jsonify


# Initialize the Flask application
app = Flask(__name__)

# This is the path to the upload directory
app.config["UPLOAD_FOLDER"] = "uploads/"
# These are the extension that we are accepting to be uploaded
app.config["ALLOWED_EXTENSIONS"] = set(["png", "jpg", "jpeg", "gif"])
app.config["MAX_CONTENT_LENGTH"] = 2 * 1024 * 1024  # 2MB

# If the file you are trying to upload is too big, you'll get this message
@app.errorhandler(413)
def request_entity_too_large(error):
    message = "The file is too large, my friend.<br>"
    maxFileSizeKB = app.config["MAX_CONTENT_LENGTH"] / (1024)
    message += "The biggest I can handle is " + str(maxFileSizeKB) + "KB"
    message += "<a href='" + url_for("index") + "'>Try again</a>"
    return message, 413


# For a given file, return whether it's an allowed type or not
def allowed_file(filename):
    return "." in filename and filename.rsplit(".", 1)[1] in app.config["ALLOWED_EXTENSIONS"]
Example #21
0
from flask import Flask

app = Flask(__name__)
app.debug = True  # Switch to False for production
app.config["MAX_CONTENT_LENGTH"] = 8388608  # Limit file upload to 8MB (8x1024x1024)

from flask_rest.utils.error_handlers import *
from flask_rest.utils.monitor_handlers import *
from flask_rest.utils.router import register_handlers

register_handlers("v1")  # Register all resources in version 1 of the API
register_handlers("v2")  # Register all resources in version 2 of the API
Example #22
0
from flask import Flask, render_template, request, jsonify, make_response
from info import classify2
from math import e
from redis import Redis
from config import STATS_KEY, HOST, RHOST, RPASS, RPORT
from cors import crossdomain
from datetime import datetime
import json

app = Flask(__name__)
app.debug = False
app.config["MAX_CONTENT_LENGTH"] = 1 << 20  # 1 MB max request size
conn = Redis(RHOST, RPORT, password=RPASS)


def percentage_confidence(conf):
    return 100.0 * e ** conf / (1 + e ** conf)


def today():
    return datetime.now().strftime("%Y-%m-%d")


def get_sentiment_info(text):
    flag, confidence = classify2(text)
    if confidence > 0.5:
        sentiment = "Positive" if flag else "Negative"
    else:
        sentiment = "Neutral"
    conf = "%.4f" % percentage_confidence(confidence)
    return (sentiment, conf)
Example #23
0
### END IMPORTS

# Connect to db
engine = create_engine("sqlite:///icgdb.db")
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()


# SETUP AND CONFIGURATION FOR FILE(IMAGE) UPLOAD
UPLOAD_FOLDER = os.path.abspath("static/pics")
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
ALLOWED_EXTENSIONS = set(["png", "jpg", "jpeg", "gif"])
app.config["MAX_CONTENT_LENGTH"] = 100 * 1024  # limit size to 100kb


def checkExtension(filename):
    return "." in filename and filename.rsplit(".", 1)[1] in ALLOWED_EXTENSIONS


def uploadFile():
    file = request.files["game-image"]
    if file and checkExtension(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))
        return filename


# OAUTH SETUP FOR GOOGLE
Example #24
0
from logging.handlers import RotatingFileHandler
from flask import Flask, url_for, request, redirect
from werkzeug import secure_filename

LOG_FILE = "flask-server.log"
ALLOWED_EXTENSIONS = set(["txt", "pdf", "png", "jpg", "jpeg", "gif"])

app = Flask(__name__, static_folder="src", static_url_path="/src")

logFilehandler = RotatingFileHandler(LOG_FILE, maxBytes=10000, backupCount=1)
logFilehandler.setLevel(logging.DEBUG)
app.logger.addHandler(logFilehandler)
# app.logger.warning(request.headers)

app.config["UPLOAD_FOLDER"] = "./"
app.config["MAX_CONTENT_LENGTH"] = 10 * 1024 * 1024  # 10MB MAX Upload size


def is_file_allowed(filename):
    return ("." in filename) and (filename.rsplit(".", 1)[1] in ALLOWED_EXTENSIONS)


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


@app.route("/upload", methods=["GET", "POST"])
def upload_file():
    if request.method == "POST":
        file_key = request.files.iterkeys().next()
Example #25
0
# and follow the directions to install

from config import *

app = Flask(__name__)
app.config.from_object(__name__)

if USESSL:
    from OpenSSL import SSL

    ctx = SSL.Context(SSL.SSLv23_METHOD)
    ctx.use_privatekey_file("ssl/ssl.key")
    ctx.use_certificate_file("ssl/ssl.cert")

MAX_MEGABYTES = 2
app.config["MAX_CONTENT_LENGTH"] = MAX_MEGABYTES * 1024 * 1024

ACCEPTED_MIMETYPES = [
    "text/plain",
    "text/csv",
    "application/vnd.ms-excel",
    "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
]

ERROR_MESSAGES = {
    404: "The requested resource cannot be found. Please check the API documentation and try again.",
    401: "You are not authenticated to use this resource. Please provide a valid app_id and app_key pair.",
    413: "The file that was submitted is too large. Please submit a file smaller than %i megabytes." % MAX_MEGABYTES,
    415: "The file that was submitted is an unsupported type. Please submit valid plain text, CSV, or an Excel spreadsheet.",
    500: "An error has occurred in the analysis. Please contact support@gosynapsify.com for assistance.",
    400: "The request is missing required parameters or otherwise malformed. Please check the API documentation and try again.",
Example #26
0
    _printer.configure(config)


if __name__ == "__main__":
    # configure the overall logging
    logging.basicConfig(
        filename=T_BONE_LOG_FILE, level=logging.DEBUG, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    )
    # Comment following lines in order to enable logging (/var/log/t_bone.log)
    logging.disable(logging.DEBUG)
    logging.disable(logging.INFO)

    logging.info("Starting print server")
    # somehow we can get several initializations - hence we store a global printer
    try:
        if not os.path.exists(UPLOAD_FOLDER):
            os.mkdir(UPLOAD_FOLDER)
        if not _printer:
            create_printer()
        logging.info("configured, starting web interface")
        # this has to be configured somewhere (json??)
        app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
        app.config["MAX_CONTENT_LENGTH"] = MAX_CONTENT_LENGTH
        app.run(host="0.0.0.0", port=80, debug=True, use_reloader=False)
    except KeyboardInterrupt:
        _printer.stop()
        logging.warning("Printer stopped due to KeyboardInterrupt exception")
    finally:
        # reset the printer
        _printer = None
    logging.info("Quitting print server")
Example #27
0
import os

from flask import abort, Flask, jsonify, redirect, render_template, request

from . import getconfig, util
from .filekeeper import delete_files, insert_link_to_latest, parse_docfiles, unpack_project

app = Flask(__name__)

app.config["MAX_CONTENT_LENGTH"] = getconfig.max_content_mb * 1024 * 1024


@app.route("/hmfd", methods=["POST", "DELETE"])
def hmfd():
    if getconfig.readonly:
        return abort(403)

    if request.method == "POST":
        if not request.files:
            return abort(400, "Request is missing a zip file.")
        unpack_project(util.get_filestream_from_request(request), request.form, getconfig.docfiles_dir)
    else:
        assert request.method == "DELETE"
        delete_files(
            request.args["name"],
            request.args.get("version"),
            getconfig.docfiles_dir,
            request.args.get("entire_project"),
        )
    return jsonify({"success": True})
        response = make_response(json.dumps("Successfully disconnected."), 200)
        response.headers["Content-Type"] = "application/json"
        flash("Successfully logged out.")
        return redirect(url_for("showRestaurants"))
    else:
        response = make_response(json.dumps("Failed to revoke token for given user.", 400))
        response.headers["Content-Type"] = "application/json"
        flash("Failed to revoke token for given user.")
        return redirect(url_for("showRestaurants"))


# Image Uploads
UPLOAD_FOLDER = "/var/www/menuApp/static/images"
ALLOWED_EXTENSIONS = set(["png", "jpg", "jpeg", "gif"])
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
app.config["MAX_CONTENT_LENGTH"] = 1 * 1024 * 1024  # 1 MB limit on file size

# Define allowable file upload extensions
def allowed_file(filename):
    return "." in filename and filename.rsplit(".", 1)[1] in ALLOWED_EXTENSIONS


@app.route("/static/images/<filename>")
def uploaded_file(filename):
    return send_from_directory(app.config["UPLOAD_FOLDER"], filename)


# Begin API Endpoints
# All restaurants
@app.route("/restaurants/JSON")
def restaurantsJSON():
Example #29
0
app = Flask(__name__, static_url_path="/content", static_folder="content")

datamgr = DataManager()
datamgr.load()

puzzmgr = PuzzleManager(datamgr)
puzzmgr.load()

ADMIN_PASSWORD = "puzzles"

# Setup web app configurations
app.config["SOLUTION_FOLDER"] = "solutions/"
if not os.path.exists(app.config["SOLUTION_FOLDER"]):
    os.makedirs(app.config["SOLUTION_FOLDER"])

app.config["MAX_CONTENT_LENGTH"] = 10 * 1024  # 10KB


########## Routes ###########


@app.route("/", methods=["GET", "POST"])
def home():
    try:
        if request.method == "GET":
            teamname = request.cookies.get("teamname")
            if not teamname:  # not set
                return render_template("team_login.html")

            return render_template(
                "home.html",
Example #30
0
from serverside_sessions import create_managed_session
from StringIO import StringIO
from werkzeug import secure_filename
import pandas

root = os.path.dirname(os.path.realpath(__file__)) + os.sep

app = Flask(__name__)
app.secret_key = "v\xfc\x9d\xfb\xa2\xc7uj\x97F\xc2\xb2\x14\xa4\xaa\xef\x8e\xedz\xe4\xc0daI"
app.debug = True
# Server-side session handeling
app.config["SESSION_PATH"] = root + "_SESSION_DATA" + os.sep
app.session_interface = create_managed_session(app)
# File uploads
app.config["UPLOAD_FOLDER"] = root + "_UPLOADS" + os.sep
app.config["MAX_CONTENT_LENGTH"] = 5 * 1024 * 1024  # 5 MB limit
ALLOWED_EXTENSIONS = set(["xml"])


def allowed_file(filename):
    return "." in filename and filename.rsplit(".", 1)[1] in ALLOWED_EXTENSIONS


class DataNotLoaded(Exception):
    pass


try:
    GBA = imp.load_source("GBA", root + ".." + os.sep + "GreenButtonActuator.py")
except:
    debug_info = "<pre>" + str(traceback.format_exc()) + "</pre>"