Beispiel #1
0
import os
from datetime import datetime
from flask import Flask, render_template, redirect, url_for, request, session, flash, Markup, jsonify
from functools import wraps
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import and_, select
from models import *


app = Flask(__name__)
app.config.from_object(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///shopping_cart.db"
app.secret_key = "aswa23ewd4rfeiu7"

app.config["UPLOAD_FOLDER"] = "static/images/stock"

ALLOWED_EXTENSIONS = ["png", "jpg", "jpeg", "gif"]


db = SQLAlchemy(app)


def login_required(f):
    @wraps(f)
    def wrap(*args, **kwargs):
        if "logged_in" in session:
            return f(*args, **kwargs)
        else:
            message = Markup("<span class='error'> You need to log in to perform this action. </span>")
            flash(message)
            return redirect(url_for("login"))
Beispiel #2
0
def send_to_indico():

    path = os.path.dirname(os.path.abspath(__file__)) + "/static/img/pictures/" + session['name']

    selfie_list = []
    for f in os.listdir(path):
        new_path = os.path.join(path, f)
        if os.path.isfile(new_path) and f[f.index('.')+1:] in ALLOWED_EXTENSIONS:
            selfie_list.append(new_path)
    print selfie_list

    emotion_scores = indicoio.batch_fer(selfie_list, api_key="0f73d0a7c698469192cbd74886b48615")

    emotions = []
    emotion_values = []
    [emotions.extend(snapshot.keys()+['break']) for snapshot in emotion_scores]
    [emotion_values.extend(snapshot.values()+[0]) for snapshot in emotion_scores]

    print 'emotions', emotions, '\n', 'emotion_values', emotion_values
    return json.dumps({'scores': emotion_values, 'labels': emotions})


if __name__ == '__main__':
    app.config["UPLOAD_FOLDER"] = "/static/img/pictures/"
    app.config["SESSION_TYPE"] = "filesystem"

    app.secret_key = "woah it's a secret!"
    sess.init_app(app)

    app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 5000)), processes=2)
Beispiel #3
0
'''
create app instance
'''

import os

from flask import Flask, jsonify, abort, make_response, render_template
from flask_httpauth import HTTPBasicAuth

app = Flask(__name__, static_url_path="")   # pylint: disable=invalid-name
app.config.from_object("config")
app.debug = True
auth = HTTPBasicAuth()  # pylint: disable=invalid-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(["txt", "pdf", "png", "jpg", "jpeg", "gif", "py"])
# create upload folder if not exist
if not os.path.exists(app.config["UPLOAD_FOLDER"]):
    os.makedirs(app.config["UPLOAD_FOLDER"])

# redefine jinja start/end string to avoid conflict with AngularJS
app.jinja_env.variable_start_string = "{[{ "
app.jinja_env.variable_end_string = " }]}"

# use different static/templates folder with different mode
if not app.debug:
    app.template_folder = "build/templates"
    app.static_folder = "build/static"
else:
Beispiel #4
0
from flask import Flask, request, Response, abort, jsonify
from hashlib import md5
import magic
from dropbox_sync import *
from PIL import Image
import thread

app = Flask(__name__)
folder_name = os.getcwd()+"/storage"
port = os.getenv('VCAP_APP_PORT', '8080')

app.config["UPLOAD_FOLDER"]='storage/'
app.config["ALLOWED_EXTENSION"]=set(['jpg','jpeg','png','gif','bmp'])
app.config["MAX_FILE_SIZE"]= 5000000 #5MB
def validate_ext(file):
    mimetype = magic.from_buffer(file.stream.read(),mime=True)
    ext = mimetype.rsplit('/',1)[1]
    result = ext in app.config["ALLOWED_EXTENSION"]
    return result
def validate_size(file):
    chunk = 10
    data = None
    size = 0
    while data != b'':
        data = file.read(chunk)
        size+= len(data)
        if (size> app.config["MAX_FILE_SIZE"]):
            return False
    return True
def resize(filename):
    #fad
Beispiel #5
0
import os
from flask import Flask
from hashids import Hashids
from flask_sqlalchemy import SQLAlchemy

basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
app.config["DEBUG"] = True
app.config["SECRET_KEY"] = "secret"
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///" + os.path.join(os.getcwd(), 'onsmash.db')
app.config["UPLOAD_FOLDER"] = os.path.join(os.getcwd(), "THUMBNAILS")
app.config["ALLOWED_EXTENSIONS"] = ['png', 'jpg', 'jpeg', 'gif']

db = SQLAlchemy(app)
hashids = Hashids(salt=app.config["SECRET_KEY"])

import views
import models
Beispiel #6
0
from flask import Flask, render_template, request, g, make_response, redirect, url_for
import os
import subprocess
import psycopg2
from werkzeug import secure_filename

ALLOWED_EXTENSIONS = set(['py'])
app = Flask(__name__)
app.config["UPLOAD_FOLDER"] = 'temp'

okCmds = frozenset(["python"])

@app.route('/<cmd>/<script>/')
def runCmd(cmd, script):

    if cmd in okCmds:
    	print cmd, script
        o = subprocess.check_output([cmd,script])
        return o
    else:
        return ( cmd + ' is not an ok command.' )

@app.route('/<cmd>/<script>/<input_file>/<id>')
def runCmdWithInput(cmd, script, input_file, id):

    if cmd in okCmds and script == "rmg":
        script = "scripts/rmg.py"
        input_file = "temp/input.py"
        o = subprocess.call([cmd, script, input_file])
        if o == 0:
            # crete file binary
Beispiel #7
0
import json
import os

try:
    import mysql.connector as mydb
except:
    import pymysql as mydb

con = mydb.connect(user="root", password="123456", database="zpf")
cur = con.cursor()


app = Flask(__name__)
app.secret_key = "A0Zr98j/3yX R~XHH!jmN]LWX/,?RT"

app.config["UPLOAD_FOLDER"] = "/opt/testpy/51reboot/uploads/"
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:123456@localhost/zpf"
ALLOWED_EXTENSIONS = set(["txt", "pdf", "png", "jpg", "jpeg", "gif"])
# app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True   ##自动提交
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = True
db = SQLAlchemy(app)


"""

class Userlist(db.Model):
        __tablename__ = 'userlist1'
        id = db.Column(db.Integer, primary_key = True)
        user = db.Column(db.String(255))
        password = db.Column(db.String(255))
Beispiel #8
0
import json
import os
from flask import Flask, redirect, url_for, render_template, request
from werkzeug import secure_filename
import indicoio

#hi

app = Flask(__name__)
ALLOWED_EXTENSIONS = set(["png","jpg","jpeg"])
app.config["UPLOAD_FOLDER"] = "pictures/"

foo = ""

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

@app.route('/', methods=['GET', 'POST'])
def index():
  global foo
  if request.method == 'POST':
      file = request.files['file']
      if file and allowed_file(file.filename):
          filename = secure_filename(file.filename)
          foo = request.form['name']
          path = os.path.dirname(os.path.abspath(__file__)) + "/pictures/" + foo
          if not os.path.exists(path):          
              os.makedirs(path)
          app.config["UPLOAD_FOLDER"] = path
          file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
Beispiel #9
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):
        if g.user is None and request.method == "POST":
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    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 #11
0

@site.route("/status")
def status():
    return render_template("status.html",
                           loggedin=session.get("loggedin", False))


@site.route("/upload", methods=["GET", "POST"])
def upload():
    if not session.get("loggedin", False):
        return '''Nothing to see here, move along.''', 403
    if request.method == "POST":
        file = request.files["file"]
        if file and allowed_file(file.filename):
            filename = secure_filename(os.path.basename(file.filename))
            file.save(os.path.join(site.config["UPLOAD_FOLDER"], filename))
            return redirect((os.path.join(DISPLAY_URL, filename)))
        else:
            return render_template("upload.html", uploaded=True, success=False)
    else:
        return render_template("upload.html", uploaded=False)
    return


if __name__ == "__main__":
    load_users("users.json")
    site.secret_key = os.urandom(24)
    site.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
    site.run()
Beispiel #12
0
UPLOAD_FOLDER = "C:/Users/Princewill/Flaskapp/farmexport/app/static/img/productpics/"

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

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("/show")
def show_entries():
    form = PostForm()
Beispiel #13
0
from flask import Flask, url_for, redirect, request, render_template, send_from_directory
from flask.ext.sqlalchemy import SQLAlchemy
from model import *
from werkzeug import secure_filename

import os

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

if not os.path.exists("data/media"):
    os.makedirs("data/media")

app = Flask(__name__)
app.config["UPLOAD_FOLDER"] = "data/media"
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///data/test.db"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

with app.app_context():
    db.init_app(app)
    db.drop_all()
    db.create_all()

    # sample data
    sample_courses = [
        Course("chemistry", "This is a thing that has to do with chemistry", "chemistry.png"),
        Course("physics", "This is a thing that has to do with physics", "physics.png"),
        Course("programming", "This is a thing that has to do with programming", "programming.png"),
    ]
    for course in sample_courses:
        db.session.add(course)
    db.session.commit()
Beispiel #14
0
    return json_data


# Upload new file
@app.route("/upload", methods=["GET", "POST"])
def upload_file():
    if request.method == "POST":
        file_ = request.files["file"]
        author = request.headers.get("x-webauth-ldap-cn")
        common_name = request.form.get("common_name")
        description = request.form.get("description")
        if file_:
            print(file_.__dict__)
            filename = secure_filename(file_.filename)
            filepath = os.path.join(json_config["upload_folder"], filename)
            file_hash = None
            if not os.path.exists(filepath):
                file_.save(filepath)
                file_hash = hash_file(filepath)
                return jsonify(add_file(file_hash, filename, common_name, description, author))
            else:
                return "ERROR FILE EXISTS!!!!", 409


with open(sys.argv[1]) as json_file:
    json_config = json.load(json_file)

app.config["UPLOAD_FOLDER"] = json_config["upload_folder"]
app.config["MAX_CONTENT_LENGTH"] = 10 * 1024 * 1024  # 10 Megabytes
app.run(debug=json_config["debug"], port=json_config["port"])
Beispiel #15
0
#----------------------------------------
# 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):
  """Serves up raw result files
Beispiel #16
0
from flask import Flask
from flask.ext.mongoengine import MongoEngine

import datetime
import os

app = Flask(__name__)
app.config["MONGODB_SETTINGS"] = {'DB': "jotter"}
app.config["SECRET_KEY"] = "backtoussr"
app.config["UPLOAD_FOLDER"] = os.path.join(os.getcwd(), "uploads")

db = MongoEngine(app)

if __name__ == '__main__':
    app.run()


@app.context_processor
def utility_processor():
    def format_runtime(runtime):
        if runtime:
            runtime = str(datetime.timedelta(seconds=int(float(runtime))))
        return runtime

    def format_result(result):
        if result:
            result = 'Passed' if result == '1' else 'Failed'
        return result
    return dict(format_runtime=format_runtime, format_result=format_result)

Beispiel #17
0
import os

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager

app = Flask(__name__)
# app.secret_key = os.urandom(24) # Flask-Login secret key
app.secret_key = "clogicVeslo"
app.logger.info("secret key " + app.secret_key)
# app.config['SQLALCHEMY_DATABASE_URI'] = "postgresql://clogic:ok154288tmddlf@localhost/Veslo" # db uri
app.config[
    "SQLALCHEMY_DATABASE_URI"
] = "postgresql://itnpxmghkouqge:DrNcaRJ86jmr4IwHi9NK3mzHfP@ec2-54-83-204-159.compute-1.amazonaws.com:5432/d5inl38ocf5nlu"  # db server uri
app.config["UPLOAD_FOLDER"] = "index/static/image"

import logging
from logging import StreamHandler

file_handler = StreamHandler()
file_handler.setLevel(logging.WARNING)
app.logger.addHandler(file_handler)

db = SQLAlchemy(app)
login_manager = LoginManager()
login_manager.init_app(app)

# import db table
from index.models import user
from index.models import meeting
Beispiel #18
0
from flask import Flask
from flask.ext.mongoengine import MongoEngine

app = Flask(__name__)
app.config["MONGODB_SETTINGS"] = {'DB': "auctions_db"}
app.config["SECRET_KEY"] = "Q0xfC4nGO7"
app.config["UPLOAD_FOLDER"] = '/tmp/img_uploads'

db = MongoEngine(app)


def register_blueprints(app):
    # Prevents circular imports
    from auction.views import auctions
    app.register_blueprint(auctions)

register_blueprints(app)

if __name__ == '__main__':
    app.debug = True
    app.run()
Beispiel #19
0
import sys
from reach_tools import reach_tools

from RTKLIB import RTKLIB
from port import changeBaudrateTo230400

from threading import Thread
from flask import Flask, render_template, session, request, send_file
from flask.ext.socketio import SocketIO, emit, disconnect
from subprocess import check_output

app = Flask(__name__)
app.template_folder = "."
app.debug = False
app.config["SECRET_KEY"] = "secret!"
app.config["UPLOAD_FOLDER"] = "../logs"

socketio = SocketIO(app)

# configure Ublox for 230400 baudrate!
changeBaudrateTo230400()
rtk = RTKLIB(socketio)

# at this point we are ready to start rtk in 2 possible ways: rover and base
# we choose what to do by getting messages from the browser

@app.route("/")
def index():
    rtk.logm.updateAvailableLogs()
    return render_template("index.html", logs = rtk.logm.available_logs, system_status = reach_tools.getSystemStatus())
Beispiel #20
0
from flask import abort, Flask, g, jsonify, redirect, render_template, request
from flask import url_for
from werkzeug import secure_filename

#! Temp coding hack, need to install when finished
#sys.path.append("E:\\prog\\flask-fedora-commons")
sys.path.append("C:\\Users\\jernelson\\Development\\flask-fedora")
from flask_fedora_commons import Repository

from string import Template

TEMP_UPLOADS = 'files/temp' # Probably not needed
ALLOWED_EXTENSIONS = set(["PDF", "MP3"])

editor = Flask(__name__)
editor.config["UPLOAD_FOLDER"] = 'files/temp'
editor.config.from_pyfile('editor.cfg')
repo = Repository(editor)

TEMP_UPLOADS = 'files/temp'
ALLOWED_EXTENSTIONS = set(["pdf", "mp3"])

# fedora_base = 'http://172.25.1.108:8080/rest/'
fedora_base = 'http://localhost:8080/rest/schema/'
fcrepo = rdflib.Namespace('http://fedora.info/definitions/v4/repository#')
literal_set = set(['Text', 'Number', 'Date'])
schema_json = json.load(open('schema_org.json'))
schema_ns = rdflib.Namespace('http://schema.org/')
namespaces = [('schema', str(schema_ns))]

def allowed_file(filename):
Beispiel #21
0
def create_app(debug=False):

    # -----------------------------
    # Create App
    # -----------------------------
    # instantiate the Flask app, __name__ tells Flask what belongs to the application
    app = Flask(__name__, static_url_path='/static')
    app.debug = debug

    # I make it so you can build URLs in javascript using Flask's url_for
    # rather than having to hardcode anything.
    # http://stewartjpark.com/Flask-JSGlue/
    jsglue = JSGlue(app)

    # -----------------------------------
    # Set up a Logger for your application
    # -----------------------------------
    # log = standard Pythong logging thing you create here -- then add it to the Flask handler
    # app.logger.addHandler(log)
    # use your logger with app.logger.info('this is info'), don't use print statements inside Flask

    # ----------------------------------
    # Load an appropriate Flask configuration file for a debug or production version
    # ----------------------------------
    if app.debug:
        server_config_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'configuration', 'localhost.cfg')
    else:
        pass
        # Load a configuration file for a production version of your app!
        # server_config_file = /path/to/production/config/file

    # app.logger.info('Loading config file: {0}'.format(server_config_file))
    app.config.from_pyfile(server_config_file)

    # ----------------------------
    # Manually add any configuration parameters
    # ----------------------------
    app.config["UPLOAD_FOLDER"] = os.environ.get("MYAPP_DATA_DIR", None)

    # ----------------------------
    # Global Error Handlers
    # ----------------------------
    @app.errorhandler(404)
    def this_is_the_wrong_page(e):
        error = {}
        error['title'] = 'MyApp | Page Not Found'
        error['page'] = request.url
        return render_template('errors/page_not_found.html', **error), 404

    # ----------------------------------
    # Web Route Registration - Import and register all your blueprints here
    # ----------------------------------
    from myapp.controllers.index import index_page
    from myapp.controllers.examples import example_page

    url_prefix = '/myapp'  # I can prefix all routes with a name
    app.register_blueprint(index_page, url_prefix=url_prefix)
    app.register_blueprint(example_page, url_prefix=url_prefix)

    # Register all custom Jinja filters in the file.
    app.register_blueprint(jinjablue)

    return app
Beispiel #22
0
from flask import Flask, request, make_response, render_template, Response
from flask_bootstrap import Bootstrap
from flask_wtf import Form
from flask_wtf.file import FileField, FileAllowed
from werkzeug import secure_filename
from wtforms import PasswordField, RadioField, TextField
from wtforms.validators import DataRequired

from tasks import process_user_csv, process_access_levels_csv
from access_levels import dump_access_levels_csv


app = Flask(__name__)

# TODO put them somewhere secure
app.config["UPLOAD_FOLDER"] = tempfile.gettempdir()
app.config["SECRET_KEY"] = os.environ.get('XIT_SECRET', 'secret-key')

bs = Bootstrap()
bs.init_app(app)


class CsvUploadForm(Form):
    xplan_url = TextField(
        'XPLAN URL',
        validators=[DataRequired()])
    xplan_username = TextField(
        'Username',
        validators=[DataRequired()])
    xplan_password = PasswordField(
        'Password',
from functools import wraps
import os
import werkzeug
import sqlite3

from flask import Flask, render_template, request, session, redirect, flash, url_for, _app_ctx_stack
from werkzeug.security import check_password_hash, generate_password_hash

app = Flask(__name__)
app.secret_key = "Development Key"

app.config["DATABASE"] = "data.db"
app.config["UPLOAD_FOLDER"] = "static/uploads"

ALLOWED_EXTENSIONS = set(['mp3'])


def sanitize_song_title(song):
    new_song = song.strip("'")
    return new_song.replace(" ", "_")


def retrieve_user_info(username):
    return query_db("SELECT * FROM user_data WHERE username=?", [username], one=True)


def get_db():
    """Opens a new database connection if there is none yet for the current application context."""
    top = _app_ctx_stack.top
    if not hasattr(top, 'sqlite_db'):
        top.sqlite_db = sqlite3.connect(app.config["DATABASE"])
Beispiel #24
0
GPIO.setwarnings(False)
GPIO.cleanup()
GPIO.setup(relay, GPIO.OUT)
GPIO.setup(red_led, GPIO.OUT)
GPIO.setup(green_led, GPIO.OUT)
GPIO.setup(switch, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.output(relay, 0)
GPIO.output(red_led, 0)
GPIO.output(green_led, 0)

upload_folder = "./uploads"
allowed_ext = set(["txt", "gcode"])

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

curr_error = adc.read_adc_voltage(2) - 2.4


def allow_file(filename):
    return "." in filename and filename.rsplit(".", 1)[1] in allowed_ext


@app.route("/", methods=["GET", "POST"])
def index():
    if request.method == "POST":
        global pps
        file = request.files["file"]
        if file and allow_file(file.filename):
            filename = "job.gcode"
Beispiel #25
0
from datetime import datetime
from functools import wraps

from flask import Flask, request, session, render_template, redirect, \
    url_for, escape
from werkzeug import secure_filename
from models import db, Manga, Chapter, Page
from admin import ADMIN_USERNAME, ADMIN_PASSWORD, SECRET_KEY, SEND_TWEETS, \
    TWITTER_WIDGET_ID, TWITTER_LINK, CONSUMER_KEY, CONSUMER_SECRET, \
    ACCESS_TOKEN, ACCESS_TOKEN_SECRET

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

application = Flask(__name__)
application.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
application.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///tmp/reader.db"
application.secret_key = SECRET_KEY

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
twitter_api = tweepy.API(auth)

db.init_app(application)

#===============================================================================
# ** Helper Methods
#===============================================================================

def allowed_file(filename):
    return "." in filename and filename.rsplit(".", 1)[1] in ALLOWED_EXTENSIONS
Beispiel #26
0
from flask import Flask, render_template, request, redirect, url_for, session, abort, send_file
from werkzeug import secure_filename
from flask import jsonify
import os
import filecmp
import uuid
import sqlite3
from flask import g
from datetime import datetime
import conf
import subprocess as sp

ALLOWED_EXTENSIONS = set(["pdb"])

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


def get_db():
    db = getattr(g, "_database", None)
    if db is None:
        is_new = not os.path.exists(conf.DATABASE)
        db = g._database = sqlite3.connect(conf.DATABASE)
        # initialize?
        if is_new:
            init_db()
    return db


def init_db():
Beispiel #27
0

def prepare_config():
    app.config["config_files"] = {"dh_ready": False,
                                  "server_cert_ready": False,
                                  "server_key_ready": False,
                                  "ca_cert_ready": False,
                                  "config_ready": False,
                                  }

    app.config["service_built"] = False
    app.config["service_running"] = False

if __name__ == "__main__":

    opts, _ = getopt.getopt(sys.argv[1:], "a:p:w:", ["working-dir="])

    host = "127.0.0.1"
    port = 9094
    for opt, arg in opts:
        if opt in ("-w", "--working-dir"):
            working_dir = arg
        elif opt == "-a":
            host = arg
        elif opt == "-p":
            port = int(arg)

    app.config["UPLOAD_FOLDER"] = working_dir
    prepare_config()
    app.run(host=host, port=port, debug=True)
Beispiel #28
0
from flask import Flask, render_template, jsonify, request, send_from_directory
from flask.ext.socketio import SocketIO, emit

import time
import json
import threading
import random

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

socketio = SocketIO(app)

songs1 = [{"lat": "37.8716", "lng": "-122.2727", "songName": "Billie Jean", "artistName": "Michael Jackson", "youtubeLink": "https://www.youtube.com/watch?v=Zi_XLOBDo_Y"},
        {"lat": "37.3382", "lng": "-121.8863", "songName": "Big Pimpin'", "artistName": "Jay Z", "youtubeLink": "https://www.youtube.com/watch?v=Cgoqrgc_0cM"},
        {"lat": "36.9741", "lng": "-122.0308", "songName": "Everybody Wants to Rule the World", "artistName": "Tears for Fears", "youtubeLink": "https://www.youtube.com/watch?v=ST86JM1RPl0"},
        {"lat": "36.0083", "lng": "-119.9618", "songName": "American Ride", "artistName": "Toby Keith", "youtubeLink": "https://www.youtube.com/watch?v=zNDcAWNscg8"},
        {"lat": "34.4208", "lng": "-119.6982", "songName": "Headlines", "artistName": "Drake", "youtubeLink": "https://www.youtube.com/watch?v=cimoNqiulUE"},
        {"lat": "34.0522", "lng": "-118.2437", "songName": "Jumpman", "artistName": "Drake", "youtubeLink": "https://www.youtube.com/watch?v=NiM5ARaexPE"}]

songs = json.load(open('html_parser/dump.json'))

maps = {"billboard": songs}


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

@app.route("/")
def index():
    #return get_tweets()
    return render_template("index.html")
Beispiel #29
0
DB_NAME = "soundsgood"
DB_USERNAME = "yeasoundsgooddev"
DB_PASSWORD = "yeas0undsg00d"
DB_HOST_ADDRESS = "ds035127.mongolab.com:35127/soundsgood"

UPLOAD_FOLDER = "data/uploads"
ALLOWED_EXTENSIONS = set(["wav"])

# initialization
app = Flask(__name__)
app.config.update(
    DEBUG = True,
)

app.config["SECRET_KEY"] = "\xeeIm\n\xb4K\x8e\xfc\x1el\x9cj\xf7\x1a\xe9\xceQ\x80\xc7\x1e;\x01\xf9\xe5"
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER

# database
app.config["MONGODB_DB"] = DB_NAME
connect(DB_NAME, host='mongodb://' + DB_USERNAME + ':' + DB_PASSWORD + '@' + DB_HOST_ADDRESS)
db = MongoEngine(app)

@app.route("/upload", methods=["GET", "POST"])
def upload():
    if request.method == "POST":
        file = request.files["file"]
        file_name = file.filename
        sound = Sound.get_sound(file_name)
        if not sound:
          sound = Sound()
        file_type = file_name.rsplit(".", 1)[1]
Beispiel #30
0
import os
from flask import Flask, render_template, request
import dropbox

app = Flask(__name__)
app.debug = True
app.config["UPLOAD_FOLDER"] = "/var/www/vineetbansal/uploads"


@app.route("/")
def root():
    return render_template("base.html")


@app.route("/upload", methods=["GET", "POST"])
def upload():
    if request.method == "POST":
        access_token = open("/var/www/vineetbansal/dropbox_token.txt", "r").readline().strip()
        client = dropbox.client.DropboxClient(access_token)
        for key, file in request.files.iteritems():
            # file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename)) # regular upload
            client.put_file(file.filename, file)

    return render_template("upload.html")