Beispiel #1
0
def create_application():
    global app

    if not config.check():
        return None

    if not os.path.exists(config.get("webapp", "cache_dir")):
        os.makedirs(config.get("webapp", "cache_dir"))

    app = Flask(__name__)
    app.secret_key = "?9huDM\\H"
    app.config["UPLOAD_FOLDER"] = "/home/davidb/sandbox/supysonic/uploads"

    app.teardown_appcontext(teardown_db)

    if config.get("webapp", "log_file"):
        import logging
        from logging.handlers import TimedRotatingFileHandler

        handler = TimedRotatingFileHandler(config.get("webapp", "log_file"), when="midnight")
        if config.get("webapp", "log_level"):
            mapping = {
                "DEBUG": logging.DEBUG,
                "INFO": logging.INFO,
                "WARNING": logging.WARNING,
                "ERROR": logging.ERROR,
                "CRTICAL": logging.CRITICAL,
            }
            handler.setLevel(mapping.get(config.get("webapp", "log_level").upper(), logging.NOTSET))
        app.logger.addHandler(handler)

    from supysonic import frontend
    from supysonic import api

    return app
Beispiel #2
0
def draw_user(username):
    user = User.query.filter_by(username=username).first()
    form = PostForm(user=user)
    event = Event.get_current(user=user)

    print form.prompts.data
    if form.validate_on_submit():

        post = Post(user=user)
        post.name = form.name.data

        post.age = form.age.data
        post.gender = form.gender.data
        post.body = form.body.data
        post.passion = form.passion.data
        post.event = event
        post.platform = request.user_agent.platform
        post.browser = request.user_agent.browser
        post.prompt = Prompt.query.filter_by(id=form.prompts.data).first()
        post.user = user

        post.image_uri = form.image_uri.data
        details_concat = ("-").join([str(form.age.data), form.gender.data, form.passion.data])
        details_space = details_concat.split(" ")
        deets = ("-").join(details_space).lower()
        image_file = post.event.name_slug + deets
        app = Flask(__name__)
        APP_ROOT = os.path.dirname(os.path.abspath(__file__))
        UPLOAD_FOLDER = os.path.join(APP_ROOT, "/var/www/html/newlynpolls/app/static/data/images")
        app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER

        post.image_file = image_file
        data_full = form.image_uri.data
        try:
            data = data_full.split(",")[1]
        except:
            pass
        else:
            fh = open((os.path.join(app.config["UPLOAD_FOLDER"], image_file + ".png")), "wb")
            fh.write(data.decode("base64"))
            fh.close()
        db.session.add(post)
        db.session.commit()
        flash("Submitted")
        return redirect(url_for("poll.cheers_user", user=user.username, event=post.event.name_slug))

    return render_template(
        "poll/poll.html", form=form, user=user, event=event, draw=True, return_to="/poll/" + user.username + "/draw"
    )
Beispiel #3
0
def setup_server():
    http_server = Flask(__name__)
    http_server.debug = True
    http_server.threaded = True
    http_server.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER

    @http_server.route("/upload", methods=["GET", "POST"])
    def upload_file():
        if request.method == "POST":
            file = request.files["file"]
            if file and allowed_file(file.filename):
                # Save posted .zip file
                filename = secure_filename(file.filename)

                compressed_file_path = os.path.join(http_server.config["UPLOAD_FOLDER"], filename)

                file.save(compressed_file_path)

                # Uncompress content of zip file
                tmp_zip_dir = compressed_file_path + "_contents/"
                os.mkdir(tmp_zip_dir)
                unzip(compressed_file_path, tmp_zip_dir)

                # Analyze included image file (assumed one raw image)
                tmp_raw_files = glob.glob(tmp_zip_dir + "*.raw")
                tmp_raw_path = "file://" + tmp_raw_files[0]

                decision = analyze_image(tmp_raw_path, WORKLIST, signatures.dictionary)

                try:
                    send_email(decision, request.remote_addr)
                except BaseException:
                    print "Notification error - Check that the SMTP server is configured properly"
                    print decision

                return json.dumps({"status": "ok"})
            return json.dumps({"status": "error", "message": "No dump file supplied."})

    http_server.run(host="0.0.0.0")
Beispiel #4
0
def create_app(config_object=ProdConfig):
    """An application factory, as explained here:
        http://flask.pocoo.org/docs/patterns/appfactories/

    :param config_object: The configuration object to use.
    """
    app = Flask(__name__)
    KVSessionExtension(RedisStore(redis.StrictRedis()), app)
    app.config.from_object(config_object)
    app.config["UPLOAD_FOLDER"] = "uploads"
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
    register_extensions(app)
    register_blueprints(app)
    register_errorhandlers(app)
    ALLOWED_EXTENSIONS = ["txt", "pdf", "png", "jpg", "jpeg"]

    #    app.config['UPLOADED_PHOTOS_DEST'] = '/tmp/testuploadext'
    #    upload_user_image = UploadSet('user_image', IMAGES)
    #    upload_poster_image = UploadSet('user_poster', IMAGES)
    #    configure_uploads(app, photos)

    moment = Moment(app)
    # sslify = SSLify(app)
    return app
Beispiel #5
0
        self.app = app

    def __call__(self, environ, start_response):
        stream = LimitedStream(environ["wsgi.input"], int(environ["CONTENT_LENGTH"] or 0))
        environ["wsgi.input"] = stream
        app_iter = self.app(environ, start_response)
        try:
            stream.exhaust()
            for event in app_iter:
                yield event
        finally:
            if hasattr(app_iter, "close"):
                app_iter.close()


app.config["UPLOAD_FOLDER"] = "static/Uploads"
app.wsgi_app = StreamConsumingMiddleware(app.wsgi_app)


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


@app.route("/upload", methods=["GET", "POST"])
def upload():
    if request.method == "POST":
        file = request.files["file"]
        extension = os.path.splitext(file.filename)[1]
        f_name = str(uuid.uuid4()) + extension
        file.save(os.path.join(app.config["UPLOAD_FOLDER"], f_name))
Beispiel #6
0
import json
import os
from flask import Flask, request, redirect
from flask import render_template
from spiderCtrl import SpiderCtrl

app = Flask(__name__)

app.config["UPLOAD_FOLDER"] = "/tmp"
app.config["MAX_CONTENT_LENGTH"] = 100 * 1024


def allowed_file(name):
    return True
    return name.split(".")[-1] == "json"


def secure_filename(name):
    return name.replace("..", "").split("/")[-1]


@app.route("/")
def upload_form():
    return render_template("upload.tpl")


@app.route("/upload", methods=["POST"])
def upload():
    if request.content_length >= app.config["MAX_CONTENT_LENGTH"]:
        return render_template("upload.tpl")
    file = request.files["file"]
Beispiel #7
0
from flask import Flask, render_template, send_from_directory, redirect, request, url_for
from werkzeug import secure_filename
import datetime, os

# Create new application
app = Flask(__name__)

# Debugging is okay for now
app.debug = True

uploadFolder = "uploads"
allowedFileExtension = set(["json", "py"])

app.config["UPLOAD_FOLDER"] = uploadFolder


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


@app.route("/uploads", methods=["GET", "POST"])
def uploadFile():
    if request.method == "POST":
        file = request.files["uploadFile"]
        if file:
            filename = secure_filename(file.filename)
            print os.path.join(app.config["UPLOAD_FOLDER"], filename)
            file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))
            print "File Found!"
            return True
#!/usr/bin/env python
# vim: set fileencoding=utf-8 filetype=python :

import os
from flask import Flask, request, redirect, url_for
from flask import send_from_directory
from flask import render_template
from werkzeug import secure_filename

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

app = Flask(__name__)
app.config["UPLOAD_FOLDER"] = os.path.join(os.path.dirname(__file__), "uploads")


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


@app.route("/", methods=["GET", "POST"])
def index():
    return render_template("index.html")


@app.route("/uploads", methods=["POST"])
def upload_file():
    file = request.files["file"]
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))
        file_url = "/uploads/%s" % filename
from sqlalchemy.orm import sessionmaker
from setup import Base, Category, Item
from flask import session as login_session
import random
import string
from oauth2client.client import flow_from_clientsecrets
from oauth2client.client import FlowExchangeError
import httplib2
import json
from flask import make_response
import requests

app = Flask(__name__)

# path to image uploads directory
app.config["UPLOAD_FOLDER"] = "static/img/"

# file extensions allowed for image uploads
app.config["ALLOWED_EXTENSIONS"] = set(["png", "jpg", "jpeg", "gif"])

# using an engine to bind our application and have access to the
# objects it exposes
engine = create_engine("sqlite:///catalog.db")
Base.metadata.bind = engine

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

CLIENT_ID = json.loads(open("client_secrets.json", "r").read())["web"]["client_id"]
APPLICATION_NAME = "Catalog App"
def build_app(funcMD, service, port_number, web_debug, output_name_postfix):
    import os
    from flask import Flask, request, redirect, url_for, send_from_directory, render_template
    from werkzeug import secure_filename
    from flaskext.uploads import UploadSet
    import csv
    import json

    UPLOAD_FOLDER = "uploads/"
    ALLOWED_EXTENSIONS = set(funcMD["supported_file_type"])
    files = UploadSet(extensions=tuple(ALLOWED_EXTENSIONS))

    app = Flask(__name__)
    app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
    ARGV_LIST = None

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

    @app.route("/", methods=["GET", "POST"])
    def upload_file():
        if request.method == "POST":
            f = request.files["file"]
            if f and allowed_file(f.filename):
                filename = resolve(f.filename)
                f.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))
                if funcMD["input_type"] == "upload_first":
                    return redirect(url_for("argv_input", filename=filename))
                elif funcMD["input_type"] == "auto":
                    argv_list = get_argv()
                    return redirect(url_for("uploaded_file", filename=filename, argv_list=argv_list))
            else:
                return "Unsupported file extension or no file selected"
        if funcMD["input_type"] == "upload_first":
            return render_template("upload_file.html", allowed=ALLOWED_EXTENSIONS, type="upload", data=funcMD)
        elif funcMD["input_type"] == "auto":
            return render_template("upload_file.html", allowed=ALLOWED_EXTENSIONS, type="auto", data=funcMD)

    @app.route("/argv_input/<filename>", methods=["GET", "POST"])
    def argv_input(filename):
        if request.method == "POST":
            argv_list = get_argv()
            return redirect(url_for("uploaded_file", filename=filename, argv_list=argv_list))
        columns = []
        with open(UPLOAD_FOLDER + filename) as f:
            reader = csv.reader(f)
            columns = list(reader.next())
        return render_template("upload_file.html", columns=columns, type="process", data=funcMD)

    @app.route("/uploads/<filename>")
    @app.route("/uploads/<filename>/<argv_list>")
    def uploaded_file(filename, argv_list=None):
        inputFile = UPLOAD_FOLDER + filename
        input_argv = []
        for argv in json.loads(argv_list):
            if argv[1] == "string":
                input_argv.append(str(argv[0]))
            elif argv[1] == "integer":
                input_argv.append(int(argv[0]))
        inputFile = service.main(inputFile, input_argv)
        return download(filename)

    @app.route("/savename/<original_filename>")
    def resolve(original_filename):
        name = files.resolve_conflict(UPLOAD_FOLDER, secure_filename(original_filename))
        return name

    def get_argv():
        argv_list = []
        for param in funcMD["parameter"]:
            argv_list.append((request.form[param["name"]], param["type"]))
        argv_list = json.dumps(argv_list)
        global ARGV_LIST
        ARGV_LIST = argv_list
        return argv_list

    @app.route("/download/<filename>")
    def download(filename):
        filename = filename.split(".")[0] + output_name_postfix
        return send_from_directory(
            app.config["UPLOAD_FOLDER"], filename, as_attachment=True, attachment_filename=filename
        )

    app.run(port=port_number, debug=web_debug)
Beispiel #11
0
from flask import Flask, request, g, session, flash, redirect, url_for, render_template, abort, send_file
from functools import wraps
import os
import pymongo
from werkzeug import secure_filename
import re
import datetime
import tempfile
import shutil
import json
import rpm

app = Flask(__name__)
app.secret_key = "my secret key"
app.config["UPLOAD_FOLDER"] = "/home/tom/vboxshare/fur/packages"
app.config["MAX_CONTENT_LENGTH"] = 8 * 1024 * 1024


def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if g.user is None:
            return redirect(url_for("login"))
        return f(*args, **kwargs)

    return decorated_function


def login_required_post(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
def db_delete_file(filename):
    """Deletes file metadata from the database."""

    query = "DELETE FROM ytfs_meta WHERE filename = '{0}'".format(filename)
    cursor.execute(query)
    db.commit()  # Save changes back to DB


def load_config():
    global SERV_PORT, DATA_DIR, DB_HOST, DB_PORT, DB_USER, DB_PASSWD, DB_DB
    config_data = None

    with open(CONFIG_FILE) as config:
        config_data = load(config)

    SERV_PORT = int(config_data["server"]["port"])
    DATA_DIR = config_data["server"]["data_dir"]
    DB_HOST = config_data["db"]["host"]
    DB_PORT = config_data["db"]["port"]
    DB_USER = config_data["db"]["username"]
    DB_PASSWD = config_data["db"]["password"]
    DB_DB = config_data["db"]["db"]


if __name__ == "__main__":
    load_config()
    app.config["UPLOAD_FOLDER"] = DATA_DIR
    db, cursor = db_connect()
    if db:
        print("Connected to database!")
    app.run(host="0.0.0.0", port=SERV_PORT)
Beispiel #13
0
# cleanup data to start with and
# create data/config and data/kickstarts
if not os.path.exists("data/config"):
    os.makedirs("data/config")
else:
    shutil.rmtree("data/config")
    os.makedirs("data/config")

if not os.path.exists("data/kickstarts"):
    os.makedirs("data/kickstarts")
else:
    shutil.rmtree("data/kickstarts")
    os.makedirs("data/kickstarts")

app.config["UPLOAD_FOLDER"] = "data/kickstarts/"

# Entry point for the Web application
@app.route("/build", methods=["GET", "POST"])
@login_required
def build():
    form = BuildConfigForm(request.form)
    if request.method == "POST":
        BuildConfigForm.pre_validate(form, request)

        if form.validate():
            parse_data(app, request, form)
            # Fire the build job in a separate process
            buildjob = Process(target=delegate)
            buildjob.start()
Beispiel #14
0
from flask import Flask, request, session, redirect, url_for, render_template, make_response, abort
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:
Beispiel #15
0
import os, shutil, sys
from flask import Flask, request, render_template, jsonify, send_from_directory
from flask.ext.assets import Environment, Bundle
from werkzeug import secure_filename
from snipper import *
import file_helpers

# TODO: refactor this goddamn thing

app = Flask(__name__)
app.config["UPLOAD_FOLDER"] = file_helpers.UPLOAD_FOLDER
app.config["TMP_FOLDER"] = file_helpers.TMP_FOLDER
app.config["ALLOWED_EXTENSIONS"] = file_helpers.ALLOWED_EXTENSIONS
app.config["MAX_CONTENT_LENGTH"] = 20 * 1024 * 1024

# assets
assets = Environment(app)
js = Bundle(
    "vendor/js/jquery-1.7.2.min.js",
    "vendor/js/jquery-ui-1.8.21.custom.min.js",
    "vendor/js/jquery.iframe-transport.js",
    "vendor/js/jquery.fileupload.js",
    "vendor/js/underscore.js",
    "vendor/js/backbone.js",
    filters="rjsmin",
    output="gen/packed.js",
)

coffee = Bundle("assets/js/*.coffee", filters="coffeescript", output="gen/application.js")

sass = Bundle("assets/css/*.sass", filters="sass", output="gen/application.css")
Beispiel #16
0
from logging.handlers import RotatingFileHandler
import time
import inspect


app = Flask(__name__)
socketio = SocketIO(app)

logging.basicConfig(filename="app.log", level=logging.DEBUG)

app.logger.info("##########################################")
app.logger.info("### NEW STARTUP")

app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///../craftbeerpi.db"
app.config["SECRET_KEY"] = "craftbeerpi"
app.config["UPLOAD_FOLDER"] = "./upload"

## Create Database
db = SQLAlchemy(app)
manager = flask.ext.restless.APIManager(app, flask_sqlalchemy_db=db)
## Import modules (Flask Blueprints)
from .base.views import base

## Create Database
db.create_all()

## Register modules (Flask Blueprints)
app.register_blueprint(base, url_prefix="/base")


@app.route("/")
import os
from werkzeug import secure_filename
from flask.ext.uploads import UploadSet, IMAGES, configure_uploads
from datetime import datetime
import time

mail = Mail()
app = Flask(__name__)
app.secret_key = "a_random_Transformer_secret_key_$%#!@"
app.config["SQLALCHEMY_DATABASE_URI"] = "postgresql+psycopg2://trans:transformer@localhost/mydatabase"
app.config["MAIL_SERVER"] = "smtp.gmail.com"
app.config["MAIL_PORT"] = 465
app.config["MAIL_USE_SSL"] = True
app.config["MAIL_USERNAME"] = "Transformingthings@gmail.com"
app.config["MAIL_PASSWORD"] = "nonmenclature"
app.config["UPLOAD_FOLDER"] = os.path.realpath(".") + "/static/img/productpics/"  # UPLOAD_FOLDER
mail.init_app(app)
from models import User

photos = UploadSet("photos", IMAGES)


@app.teardown_appcontext
def shutdown_session(exception=None):
    db_session.remove()


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

    if "email" not in session:
Beispiel #18
0
import os

# We'll render HTML templates and access data sent by POST
# using the request object from flask. Redirect and url_for
# will be used to redirect the user once the upload is done
# 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, send_from_directory

# Initialize the Flask application
app = Flask(__name__)

# This is the path to the upload directory
app.config["UPLOAD_FOLDER"] = "c:\\test"
# These are the extension that we are accepting to be uploaded
app.config["ALLOWED_EXTENSIONS"] = set(["txt", "pdf", "png", "jpg", "jpeg", "gif"])


# 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"]


# This route will show a form to perform an AJAX request
# jQuery is loaded to execute the request and update the
# value of the operation
@app.route("/")
def index():
    return render_template("index.html")

Beispiel #19
0
from flask import Flask

ALLOWED_EXTENSIONS = set(["xls"])
ADMIN_USERNAME = "admin"
ADMIN_PASSWORD = "test"
SECRET_KEY = "A0Zr98j/3yX R~XHH!jmN]LWX/,?RT"

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://feod:feod@localhost/feod"
app.config["UPLOAD_FOLDER"] = "/var/tmp/"
app.secret_key = SECRET_KEY
Beispiel #20
0
import gridfs
import os
import smtplib
from apscheduler.schedulers.background import BackgroundScheduler
from fabric.context_managers import settings
from fabric.api import *
from datetime import datetime
from flask import request
from fabric.api import *
import pysolr
from flask.ext.cors import CORS


app = Flask(__name__)
CORS(app)
app.config["UPLOAD_FOLDER"] = "pem_file_uploads/"
db = MongoClient(r"mongodb://facetube:F%40ceTuB3@128.199.157.171:27017/facetube")
solr = pysolr.Solr("http://ec2-52-24-94-113.us-west-2.compute.amazonaws.com:8983/solr/hackers", timeout=10)
client_db = db["hackers"]
fs = gridfs.GridFS(client_db)
scheduler = BackgroundScheduler()
scheduler.start()


def to_json(data):
    """Convert Mongo object(s) to JSON"""
    return json.dumps(data, default=json_util.default)


def send_mail(recepients, error_log):
    sender = "noreply@techjam.com"
Beispiel #21
0
"""
Note: setting these variables through the local environment & using os.environ to access them is preferred for security reasons
"""
app.config["MAIL_SERVER"] = ""
app.config["MAIL_PORT"] = ""
app.config["MAIL_USE_TLS"] = True
app.config["MAIL_USERNAME"] = "test@test.com"
app.config["MAIL_PASSWORD"] = "testpw"

app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + os.path.join(basedir, "data.sqlite")
# app.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL']
# uncomment this line if you want to use Heroku, comment instead the one before it
app.config["SQLALCHEMY_COMMIT_ON_TEARDOWN"] = True

app.config["UPLOAD_FOLDER"] = "./static/balls"

app.permanent_session_lifetime = timedelta(seconds=60)
app.config["SECRET_KEY"] = "veryhard2guess"
# be more original

FTP_USER = "222"
FTP_PASS = "333"
FTP_HOST = "ftp.ftp.com"
# again, environmental variables are preferred
manager = Manager(app)
bootstrap = Bootstrap(app)
db = SQLAlchemy(app)
mail = Mail(app)
db.drop_all()
Beispiel #22
0
from parser import allowed_file, Parser


# ----------------------------------------
# initialization
# ----------------------------------------

APP = Flask(__name__)
APP.logger.setLevel(logging.INFO)
# Keep passwords and credentials in a .creds file
if os.path.exists(".creds"):
    CREDS = json.load(open(".creds"))

    APP.config.update(DEBUG=True)

APP.config["UPLOAD_FOLDER"] = os.path.join(APP.root_path, "raw_data")
APP.logger.info(APP.config["UPLOAD_FOLDER"])
# ----------------------------------------
# controllers
# ----------------------------------------


@APP.route("/favicon.ico")
def favicon():
    """Route favicon to all pages
  """
    return send_from_directory(os.path.join(APP.root_path, "static"), "ico/favicon.ico")


@APP.route("/raw_results/<filename>")
def uploaded_results(filename):
Beispiel #23
0
from datetime import date
from flask import Flask, render_template, request, session, flash, redirect, url_for
import os
from pymongo import MongoClient
from werkzeug import secure_filename

import config
import secrets
import utils

app = Flask(__name__)
app.secret_key = secrets.secret_key
app.config["UPLOAD_FOLDER"] = config.UPLOAD_FOLDER

client = MongoClient()

state = {"currentTheme": "no theme", "currentSubject": "no subject"}


@app.route("/")
@utils.require_login
def home():
    templateArgs = {"currentTheme": state["currentTheme"], "currentSubject": state["currentSubject"]}

    return render_template("home.html", **templateArgs)


@app.route("/set-theme", methods=["GET", "POST"])
@utils.require_login
def setTheme():
    templateArgs = {"currentTheme": state["currentTheme"], "currentSubject": state["currentSubject"]}
Beispiel #24
0
        return send_file(filepath, as_attachment=True)
    except botocore.exceptions.ClientError as e:
        return render_template("show_error.html", error_msg=str(e.response["Error"]))


def upload_file_to_s3(bucket_name, filename):
    """
    create a S3Transfer to upload the file to S3
    """
    transfer = S3Transfer(client)
    transfer.upload_file(os.path.join(app.config["UPLOAD_FOLDER"], filename), bucket_name, filename)


def remove_temp_file(filename):
    """
    remove the temporary file
    """
    filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
    if os.path.exists(filepath) and os.path.isfile(filepath):
        os.unlink(filepath)


if __name__ == "__main__":
    # a temp folder for uploading
    app.config["UPLOAD_FOLDER"] = cfg.SITE_UPLOAD_TMP_FOLDER

    # limit the upload file size
    app.config["MAX_CONTENT_LENGTH"] = 64 * 1024 * 1024

    # run flask app according to specific setting
    app.run(host=cfg.SITE_ADDRESS, port=cfg.SITE_PORT, debug=cfg.SITE_DEBUG)
Beispiel #25
0
google = oauth.remote_app(
    "google",
    base_url="https://www.google.com/accounts/",
    authorize_url="https://accounts.google.com/o/oauth2/auth",
    request_token_url=None,
    request_token_params={"scope": "https://www.googleapis.com/auth/userinfo.email", "response_type": "code"},
    access_token_url="https://accounts.google.com/o/oauth2/token",
    access_token_method="POST",
    access_token_params={"grant_type": "authorization_code"},
    consumer_key=GOOGLE_CLIENT_ID,
    consumer_secret=GOOGLE_CLIENT_SECRET,
)


# 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(["txt", "pdf", "png", "jpg", "jpeg", "gif"])


# 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"]


# This route will show a form to perform an AJAX request
# jQuery is loaded to execute the request and update the
# value of the operation
@app.route("/")
def index():
    return render_template("login.html")
# -*- coding: utf-8 -*-
import os
from flask import Flask, request, redirect, render_template, url_for, send_from_directory

UPLOAD_FOLDER = "/files"
PHISICAL_ROOT = os.path.dirname(os.path.abspath(__file__))
ALLOWED_EXTENSIONS = set(["PNG", "png", "JPG", "jpg", "jpeg", "gif"])

app = Flask(__name__)
app.config["UPLOAD_FOLDER"] = PHISICAL_ROOT + UPLOAD_FOLDER


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


@app.route("/files/<path:filename>")
def download_file(filename):
    return send_from_directory(app.config["UPLOAD_FOLDER"], filename, as_attachment=True)


@app.route("/", methods=["GET"])
def index():
    if request.method == "GET":
        file_list = os.listdir(app.config["UPLOAD_FOLDER"])
        files = []
        for one_file in file_list:
            if one_file == ".gitkeep":
                continue
            dic_file = {}
            link = url_for("download_file", filename=one_file, _external=True)
Beispiel #27
0
from flask import Flask, request, jsonify, redirect, url_for, render_template, send_from_directory
from werkzeug import secure_filename

import html
import helpers
import os
import sys

mynode = ""
config = helpers.get_config(sys.argv)  # Load settings from config.py

CONTENT_FOLDER = config["app"]["content_folder"]  # The folder where UL/DL happen
LEN_CONTENT_FOLDER = len(CONTENT_FOLDER) - 1

app = Flask(__name__)
app.config["UPLOAD_FOLDER"] = CONTENT_FOLDER  # Tell flask that this is where all uploads are supposed to go


@app.route("/dl/<path:filename>")  # Legacy support, remove this in the future
@app.route("/download_file/<path:filename>")
def download_file(filename):
    """
    Used for downloading files to client
    """
    filename = html.unescape(filename)  # Convert HTML sequences to their characters &amp; -> &
    return send_from_directory(CONTENT_FOLDER, filename, as_attachment=True)  # Send file to client


@app.route("/download_directory/<path:dirname>")
def download_directory(dirname):
    """
    return user.id


def get_new_state():
    """The 'state' is used as a nonce. It is sent to the client when the page is rendered
    and it is required on next request. Not all requests use it, but those altering data do.
    Nonce is refreshed on each interaction on which is requested, client needs to make sure it is
    updated.
    Returns:
        string: The new state or nonce.
    """
    state = "".join(random.choice(string.ascii_uppercase + string.digits) for x in xrange(32))
    return state


# http://flask.pocoo.org/docs/0.10/patterns/fileuploads/
def allowed_file(filename):
    """
    True if the filename's extension is one of the allowed extensions.
    Args:
        filename(str): The name of the file.
    Returns:
        bool: True if the file's extension is allowed, false otherwise.
    """
    return "." in filename and filename.rsplit(".", 1)[1] in ALLOWED_EXTENSIONS


if __name__ == "__main__":
    app.secret_key = CLIENT_ID
    app.config["UPLOAD_FOLDER"] = "./static/images/"
    app.run(host="0.0.0.0", port=5000)
Beispiel #29
0
import os
from flask import Flask, request, redirect, render_template, url_for
from werkzeug import secure_filename

UPLOAD_FOLDER = "."
ALLOWED_EXTENSIONS = set(["txt", "pdf", "png", "jpg", "jpeg", "gif", "py"])

app = Flask(__name__)
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER


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


@app.route("/upload_post", methods=["POST"])
def upload_file():
    if request.method == "POST":
        f = request.files["fileupload"]
        filename = secure_filename(f.filename)
        f.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))
        return "okay, uploaded"


@app.route("/get_test")
def get_test():
    user = request.args.get("user")
    return render_template("get_test.html", user=user)


@app.route("/post_test", methods=["GET", "POST"])
import uuid
import json
import os
import utils.CVFuncs as CVFuncs
from flask import Flask, render_template, request
from utils import Image
from werkzeug import secure_filename

app = Flask(__name__, static_url_path="/static")
try:
    os.mkdir("/tmp/sceneflask")
except:
    pass
app.config["UPLOAD_FOLDER"] = "/tmp/sceneflask"
app.config["ALLOWED_EXTENSIONS"] = set(["png", "jpg", "jpeg", "gif"])

OUTPUT_IMAGE_PATH = os.path.abspath("./static/output_imgs")


def hello():
    return render_template("home.html")


@app.route("/")
def make_upload_form():
    job_id = uuid.uuid4()
    return render_template("submit_job.html", job_id=job_id)


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