Example #1
0
def init_app():
    # db_path = '/Users/linmingwang/twitter/db.sqlite'
    # db_path = '/var/www/twitter/db.sqlite'
    db_path = '/home/lin/twitter.db.sqlite'

    # 初始化并配置 flask
    app = Flask(__name__)
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024
    app.secret_key = 'TODO fixme'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///{}'.format(db_path)
    # 初始化 db
    db.init_app(app)
    db.app = app

    @app.template_filter('formatted_time')
    def formatted_time(timestamp):
        t = timestamp
        format = '%Y/%m/%d %H:%M'
        t = time.localtime(timestamp)
        ft = time.strftime(format, t)
        return ft

    # 必须在函数中 import 蓝图
    # 否则循环引用(因为蓝图中 import 了 model, model 引用了这个文件里面目的 db)
    from .api import api as api
    # 注册蓝图
    app.register_blueprint(api)
    # 把 app 引用返回
    return app
Example #2
0
def create_app():
    app = Flask(__name__)
    app.config['MAX_CONTENT_LENGTH'] = \
        int(os.environ.get('MAX_CONTENT_LENGTH', 32 * 1024))
    app.config['WEBSTORAGE_KEY_EXPIRATION_TIME'] = \
        int(os.environ.get('WEBSTORAGE_KEY_EXPIRATION_TIME', 600))
    CORS(app)
    return app
Example #3
0
def create_app(config):
    #create_structure()

    # Define the WSGI application object
    app = Flask(__name__)
    app.config['MAX_CONTENT_LENGTH'] = 200 * 1024 * 1024  # 200MB

    # Configurations
    app.config.from_object(settings[config])
    settings[config].init_app(app)

    if not app.testing:
        logo()
        check_version()
    check_configs()
    if app.testing:
        init_logging('info')
    else:
        init_logging('debug')
    #log.setLevel(logging.DEBUG)
    init_modules()
    # Init All Flask Add-ons
    bootstrap.init_app(app)
    #pagedown.init_app(app)
    db.init_app(app)
    mail.init_app(app)
    if app.config['USE_LDAP'] == 'yes':
        # LDAP Login
        # TODO : Test out LDAP
        app.add_url_rule('/login', 'login', ldap.login, methods=['GET', 'POST'])
        ldap.init_app(app)
    else:
        login_manager.login_view = 'auth.login'
        login_manager.init_app(app)

    if not app.debug and not app.testing and not app.config['SSL_DISABLE']:
        try:
            from flask.ext.sslify import SSLify
            sslify = SSLify(app)
        except ImportError:
            from flask.ext.sslify import SSLify
            raise MaliceDependencyError("Unable to import Flask-SSLify "
                                  "(install with `pip install Flask-SSLify`)")

    # Register blueprint(s)
    from .malice import malice as malice_blueprint
    app.register_blueprint(malice_blueprint)

    from .mod_auth import mod_auth as auth_module
    app.register_blueprint(auth_module, url_prefix='/auth')

    # from app.mod_api.controller import mod_api as api_module
    # app.register_blueprint(api_module, url_prefix='/api/v1')

    return app
Example #4
0
def web():
    """Malice PExecutable Web Service"""

    # set up logging
    init_logging(logging.ERROR)

    app = Flask(__name__)
    app.config['UPLOAD_FOLDER'] = '/malware'
    app.config['OUTPUT_FOLDER'] = '/malware/dump'
    app.config['PEID_PATH'] = os.path.join(path[0], 'peid/UserDB.TXT')
    # app.config['UPLOAD_FOLDER'] = 'test/web'
    app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

    @app.errorhandler(400)
    def bad_request(error):
        return 'Bad requests: you must upload a malware', 400

    @app.errorhandler(500)
    def server_error(exception):
        return 'Internal Server Error: \n{}'.format(exception), 500

    @app.route('/scan', methods=['GET', 'POST'])
    def upload():
        if request.method == 'POST':
            # check if the post request has the file part
            if 'malware' not in request.files:
                return redirect(request.url)
            upload_file = request.files['malware']
            # if user does not select file, browser also
            # submit an empty part without filename
            if upload_file.filename == '':
                abort(400)
            if upload_file:
                filename = secure_filename(upload_file.filename)
                file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                upload_file.save(file_path)
                try:
                    pe_results = MalPEFile(file_path, peid_db_path=app.config['PEID_PATH']).run()
                    # pe_results['markdown'] = json2markdown(pe_results)
                    return jsonify(pe_results), 200
                except Exception as e:
                    log.exception("failed to run malice plugin: {}".format('pescan'))
                    return e, 500
                finally:
                    try:
                        os.remove(file_path)
                    except OSError as e:
                        log.exception("failed to remove file {} - {}".format(e.filename, e.strerror))

        return "Please upload malware to me... I thirst."

    # start web service
    app.run(host='0.0.0.0', port=3993)
def create_app(config_name):
    application = Flask(__name__)
    application.config['DM_ENVIRONMENT'] = config_name

    init_app(
        application,
        configs[config_name],
        db=db,
        search_api_client=search_api_client
    )

    if not application.config['DM_API_AUTH_TOKENS']:
        raise Exception("No DM_API_AUTH_TOKENS provided")

    # FIXME: The service broker adds a 'reconnect' parameter that's rejected by Postgres and
    # doesn't seem to be in the Postgres documentation anyway.  We need to patch the broker to fix
    # the username stability issue anyway.
    import os
    if 'DATABASE_URL' in os.environ:
        application.config['SQLALCHEMY_DATABASE_URI'] = os.environ['DATABASE_URL'].replace('reconnect=true', '')

    url_prefix = application.config['URL_PREFIX']
    url_prefix_v2 = application.config['URL_PREFIX_V2']
    from .main import main as main_blueprint
    application.register_blueprint(main_blueprint, url_prefix=url_prefix)
    from .status import status as status_blueprint
    application.register_blueprint(status_blueprint, url_prefix=url_prefix)
    from .api import api as api_blueprint
    application.register_blueprint(api_blueprint, url_prefix=url_prefix_v2)
    from .admin import blueprint as admin_blueprint
    application.register_blueprint(admin_blueprint.admin)

    application.json_encoder = CustomEncoder

    # maximum POST request length http://flask.pocoo.org/docs/0.12/patterns/fileuploads/#improving-uploads
    application.config['MAX_CONTENT_LENGTH'] = 32 * 1024 * 1024  # 32 megabytes

    swag.init_app(application)

    if application.config['DEBUG']:
        # enable raise to raise exception on ORM misconfigured queries
        # application.config['NPLUSONE_RAISE'] = True
        application.config['NPLUSONE_LOGGER'] = logging.getLogger('app.nplusone')
        application.config['NPLUSONE_LOG_LEVEL'] = logging.ERROR
        NPlusOne(application)
        application.wsgi_app = SQLTapMiddleware(application.wsgi_app)

    return application
Example #6
0
def create_app(create_db=False):
    """Creates an app by registering blueprints in the modules directory
    and loading the configuration

    """

    app = Flask(__name__)
    app.secret_key = os.urandom(24)
    register_blueprints(app, "modules", ["modules"])

    app.config["SQLALCHEMY_DATABASE_URI"] = conf.DB
    # Maximum 3Mo pour les images
    app.config['MAX_CONTENT_LENGTH'] = 3 * 1024 * 1024

    db.init_app(app)
    db.app = app

    if create_db:
        db.create_all()

    return app
Example #7
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 #8
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 #9
0
from flask import Flask, json, jsonify, abort, request, send_from_directory, _app_ctx_stack
from userlib import generator
import merger.bulkmerge as bulkmerge
import merger.unitmerge as unitmerge
from database.dbconn import get_db, ItemNotFound
from userlib.reciever import validate_prefs, validate_work

import traceback
import sys


log = logging.getLogger(__name__)
logging.basicConfig()  # TODO consider file based config

app = Flask(__name__, static_url_path='')
app.config['MAX_CONTENT_LENGTH'] = 5 * 1024 * 1024  # Max upload of 5MB


@app.teardown_appcontext
def close_db_connection(exception):
    """Closes the database again at the end of the request."""
    top = _app_ctx_stack.top
    if hasattr(top, 'db_conn'):
        log.debug('here')
        top.db_conn.close()

@app.route('/static/<path:path>')
def static_page(path):
    return send_from_directory('static', path)

Example #10
0
        print "Enabling data upload."
        upload_dir = os.path.realpath(sys.argv[i+1]) + "/"
        print "Saving temporary data in " + upload_dir
    if carg == '--bokeh_url':
        bokeh_url = sys.argv[i+1]
    if carg == '--port':
        port = int(sys.argv[i+1])
        
print "Looking for bokeh-server on " + bokeh_url

app = Flask('tlac_web')

ALLOWED_EXTENSIONS = set(['txt', 'dat','tsv'])

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 0.1 * 1024 * 1024 # 0.1MB
app.config['UPLOAD_FOLDER'] = upload_dir
app.config['PORT'] = port

################################################################################

def get_data_prefix(sid, mydir):        
    if mydir is not None:
        if "*" in sid:
            print "Problem encountered. sid=",sid
            sid = make_session_id()
        data_prefix = mydir + sid
    else:
        data_prefix = None

    return data_prefix
Example #11
0
from flask import send_from_directory
from PIL import Image                           # Image()
from resizeimage import resizeimage             # resize_width()
from werkzeug import secure_filename            # secure_filemane()
from flask_wtf import FlaskForm                 # FlaskForm
from flask_wtf.file import FileField            # FileField()
from flask_wtf.file import FileRequired         # FileRequired()
from wtforms.validators import ValidationError  # ValidationError()
import imghdr                                   # what()
import os                                       # join(), listdir()


app = Flask(__name__)

# App config
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024                         # 16Mb max per upload
app.config['ALLOWED_EXTENSIONS'] = ('bmp', 'gif', 'png', 'jpg', 'jpeg')     # Allowed file extensions to be uploaded
app.config['UPLOAD_DIR'] = 'uploads/'                                       # Upload directory
app.config['THUMBN_DIR'] = 'thumbnails/'                                    # Thumbnails directory
app.config['THUMBN_SIZE'] = [300, 300]                                      # Thumbnails size in px
app.secret_key = '1RK+3588rZaM081C/c6fhTIvNOzb1L9K9nP0ojX3O7b7wJjAz5/I7EICH3m+/530/sW7iotaUK4R'




# Custom validator
# Check that the file is a real image,
# Check that the file has a valid image extension
def validate_file(alwd_ext):

    def _validate_file(form, field):
Example #12
0
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():
    ''' Create anti-forgery state token '''
Example #13
0
import os.path
import logging
from flask import Flask

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
app = Flask(__name__)
app.config['SECRET_KEY'] = '@|3*0)ae%w'
WWW_DIR = os.path.join(os.path.abspath(app.root_path+'/../'),'www')
logger.info('WWW_DIR'+WWW_DIR)

if not os.path.isdir(WWW_DIR):
    os.mkdir(WWW_DIR)
UPLOAD_FOLDER = os.path.join(WWW_DIR,'uploads')
if not os.path.isdir(UPLOAD_FOLDER):
    os.mkdir(UPLOAD_FOLDER)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
_img_dir = os.path.join(UPLOAD_FOLDER,'imgs')
if not os.path.isdir(_img_dir):
    os.mkdir(_img_dir)
app.config['IMG_UPLOAD_FOLDER'] = _img_dir
_questions_dir = os.path.join(UPLOAD_FOLDER,'questions')
if not os.path.isdir(_questions_dir):
    os.mkdir(_questions_dir)
app.config['QUESTIONS_UPLOAD_FOLDER'] = _questions_dir
app.config['MAX_CONTENT_LENGTH'] = 1*1024*1024 # max upload file size i 1M

import flask_seed.plugins
import flask_seed.views

Example #14
0
# By Pavlo Bazilinskyy <pavlo.bazilinskyy@gmail.com>
import os
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.mail import Mail
from config import basedir, EMAIL_SYSTEM
if not os.environ.get('HEROKU'):
	from config_secret import ADMINS, MAIL_SERVER, MAIL_PORT, MAIL_USERNAME, \
    MAIL_PASSWORD

app = Flask(__name__)
app.config.from_object('config')
app.config['MAX_CONTENT_LENGTH'] = 512 * 1024 * 1024 # Max file upload size
db = SQLAlchemy(app)
lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'
mail = Mail(app)

if not app.debug and os.environ.get('HEROKU') is None:
    import logging
    from logging.handlers import RotatingFileHandler
    file_handler = RotatingFileHandler('tmp/wordsforsound.log', 'a',
                                       1 * 10024 * 1024, 10)
    file_handler.setLevel(logging.INFO)
    file_handler.setFormatter(logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
    app.logger.addHandler(file_handler)
    app.logger.setLevel(logging.INFO)
    app.logger.info('wordsforsound')
Example #15
0
import boto

from werkzeug import secure_filename

# Python Image Library
import StringIO

# conn = boto.connect_s3()

# for json needs
import json
from flask import jsonify

app = Flask(__name__)   # create our flask app
app.config['CSRF_ENABLED'] = False #Cross Site Request Forgery - our forms are good....no security needed...Turning it on causes error because there's not a module.
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16 megabyte file upload

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

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


#----------	S3 Boto Connections -----------
from boto.s3.connection import S3Connection
from boto.s3.key import Key
conn = S3Connection(os.environ.get('AWS_ACCESS_KEY_ID'),os.environ.get('AWS_SECRET_ACCESS_KEY'))
app.logger.debug("Connecting to AWS")
Example #16
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
import requests
from hammock import Hammock as GendreAPI

app = Flask(__name__)
app.debug = False
app.config['MAX_CONTENT_LENGTH'] = (1 << 20) # 1 MB max request size
#conn = Redis(RHOST, RPORT, password=RPASS)
sentiment_dict = {'neg': 'Negative', 'pos': 'Positive', 'neutral': 'Neutral'}

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):
	#  limited api for 1000 requests/day
	try:
		response = requests.post('http://text-processing.com/api/sentiment/', data={'text': text})
	except requests.exceptions.ConnectionError as e:
		response = False
	print "fakhir2", response
	if response and response.status_code == 200:
import os
import numpy as np
import cv2
import subprocess as sp
import shutil
from flask import Flask, render_template, request, send_from_directory

UPLOAD_FOLDER = 'uploads/'
ALLOWED_EXTENSIONS = set(['png','webm', 'mkv', 'flv', 'vob', 'ogv', 'ogg', 'drc', 'gif', 'gifv', 'mng', 'avi', 'mov', 'qt', 'wmv', 'rm', 'rmvb', 'asf', 'mp4', 'm4p', 'm4v', 'mpg', 'mp2', 'mpeg', 'mpe', 'mpv', 'm2v', 'm4v', 'svi', '3gp', '3g2', 'mxf', 'roq', 'nsv', 'flv', 'f4v', 'f4p', 'f4a', 'f4b', 'yuv']) # https://en.wikipedia.org/wiki/Video_file_format

# Initialize the Flask application
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 # File size limit = 100M

def hologram(infile, outfile, screen_below_pyramid=False):
    '''Transform infile video to a hologram video with no audio track and save to outfile'''
    capture = cv2.cv.CaptureFromFile(infile)
    # nbFrames = int(cv2.cv.GetCaptureProperty(capture, cv2.cv.CV_CAP_PROP_FRAME_COUNT))
    width = int(cv2.cv.GetCaptureProperty(capture, cv2.cv.CV_CAP_PROP_FRAME_WIDTH))
    height = int(cv2.cv.GetCaptureProperty(capture, cv2.cv.CV_CAP_PROP_FRAME_HEIGHT))
    fps = cv2.cv.GetCaptureProperty(capture, cv2.cv.CV_CAP_PROP_FPS)
    # duration = (nbFrames / float(fps))

    length = request.form['length']
    d = request.form['d']
    padding = request.form['padding']
    assert 0 < int(length) <= 5000, 'Length is not in (0, 5000].'
    assert 0 < int(d) < int(length) / 2, 'd is not in (0, length/2).'
    assert 0 <= 2 * int(padding) < min(2 * int(d), int(length) / 2 - int(d)), 'Padding is too large.'
    length, d, padding = map(int, [length, d, padding])
Example #18
0
import urllib2,json
import hashlib
import sqlite_interface
import image
import os
import urllib
from datetime import date
from flask import Flask, render_template, session, request, redirect, url_for

app = Flask(__name__)

UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024 #max filesize limit of 10mb
flaskPath = os.path.dirname(__file__)
uploadPath = os.path.join(flaskPath, UPLOAD_FOLDER)

secretKeyFile = os.path.join(flaskPath, "secret_key")
adminKey = open(secretKeyFile, 'r').read().rstrip()
# DO NOT ADD SECRET KEY TO GIT REPO


def setup():
    galleries = sqlite_interface.getAllGalleries()
    for gallery, year in galleries:
        try:
            filesystem_interface.createGallery(year, gallery)
        except:
            print "Files already made"

@app.route("/")
Example #19
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 #20
0
# -*- coding: utf-8 -*-
"""
flask 实现文件上传
"""
import os
from flask import Flask, request, redirect, url_for
from flask import send_from_directory
from werkzeug import secure_filename
from werkzeug import SharedDataMiddleware

UPLOAD_FOLDER = r'C:\\'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  #限制文件大小

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':
        file = request.files['file']
        print('type(file)',type(file))
        print('file.filename',type(file.filename),file.filename)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            print('filename',type(filename),filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
Example #21
0
    :license: BSD (See LICENSE for details)
"""

from flask import Flask
from pymongo import Connection

VERSION = '0.0.6'

DEBUG = True
PATH = 'http://0.0.0.0:5000'
UP_FOLDER = '/Users/leo/Desktop/git/bombolone/static/image/'
PORT = 5000

ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif', 'PNG', 'JPG', 'bmp'])
EXTENSIONS_REQUEST = {'png', 'jpg', 'jpeg', 'gif', 'css', 'js'}

SECRET_KEY = '\xfb\x12\xdf\xa1@i\xd6>V\xc0\xbb\x8fp\x16#Z\x0b\x81\xeb\x16'

# Create application and configuration
app = Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024 # 10 Mb Max Upload

# Create db - The first step when working with PyMongo is to create  
# a Connection to the running mongod instance. 
connection = Connection()
db = connection.bombolone
app.test_request_context().push()

Example #22
0
from flask_login import LoginManager, current_user, login_user, logout_user
from flask_cors import CORS
# modules
from . import mymlh
from . import models
from . import settings
from . import utilities

# Load app
app = Flask(__name__)

# Configure app
app.config['SQLALCHEMY_DATABASE_URI'] = URL(**settings.DATABASE)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['UPLOAD_FOLDER'] = settings.UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = settings.MAX_UPLOAD_SIZE_MB * 1024 * 1024
app.config['DEBUG'] = settings.DEBUG
app.secret_key = settings.SECRET_KEY

# Verbose logging in PROD
if app.debug is False:
    handler = StreamHandler(sys.stdout)
    handler.setLevel(logging.DEBUG)
    app.logger.addHandler(handler)

# Load sub-modules
CORS(app)
models.db.init_app(app)
login_manager = LoginManager()
login_manager.init_app(app)
Example #23
0
import logging

from flask import Flask, request, redirect, url_for, jsonify, render_template
from werkzeug.utils import secure_filename
from elasticsearch import Elasticsearch
from elasticsearch import helpers
from uuid import uuid4
import tempfile

from forms import PEPForm
from es_setup import es, INDEX, DOC_TYPE
from readers import read_csv


app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # max 16MB


ALLOWED_EXTENSIONS = set(['csv'])
def allowed_file(filename):
	return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


def bulk_create(objs):
	actions = []
	for obj in objs:
		if 'uuid' not in obj:
			obj['uuid'] = uuid4()
		action = {
			"_index": INDEX,
			"_type": DOC_TYPE,
Example #24
0
# 504 bit session key
application.secret_key  = '?KzNp>j0-7ec;4c9zG]@tjrBy3uCZNeEsDFm*!%buG7A97?#3ANL*97;D?(jpe9'

# Config MySQL
# Don't run as root in production!

application.config['MYSQL_USER'] = 'root'
application.config['MYSQL_PASSWORD'] = 'pythondev'
application.config['MYSQL_DB'] = 'PixelGram'
application.config['MYSQL_HOST'] = 'localhost'
mysql.init_app(application)

# Define uploads folder and allowed file types - Should not be changed for now!
application.config['UPLOAD_FOLDER'] = 'static/uploads'
application.config['MAX_CONTENT_LENGTH'] = 10 * 1024 * 1024
ALLOWED_EXTENSIONS = set(['jpg'])

# Check the uploads folder exists, otherwise create it
print("INFO: Checking if upload folder exists")
if not os.path.exists(application.config['UPLOAD_FOLDER']):
    try:
        print("WARN: Upload folder does not exist, creating it")
        os.makedirs(application.config['UPLOAD_FOLDER'])
    except Exception as e:
        print(e)
        
def allowed_file(filename):
    return '.' in filename and \
            filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
Example #25
0
import sys
import urllib
import re
from flask import (Flask, request, session, g, redirect,
                   url_for, render_template, flash, 
                   abort, send_from_directory, jsonify)
from flask.ext.sqlalchemy import SQLAlchemy
from werkzeug import secure_filename

ALLOWD_EXTENSIONS = set(['wmv', 'avi', 'flv'])
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'
app.config['UPLOAD_FOLDER'] = os.path.join(CURRENT_DIR, 'data/')
app.config['MAX_CONTENT_LENGTH'] = 1 * 1024 * 1024 * 1024 # 1G まで

db = SQLAlchemy(app)

class Movie(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    filename = db.Column(db.Text)
    mp4_filename = db.Column(db.Text)
    path = db.Column(db.Text)
    state = db.Column(db.Integer)

db.create_all()


@app.route('/')
def index():
Example #26
0
Makes RPC calls to other code which crunches stuff, and passes the results back to the client.
"""
import sys
import traceback
from flask import Flask
from flask import make_response, render_template, request, json, url_for
jsonify = json.jsonify

import rpc_lib
from rpc_clients import GenQuote, IssueProtobond
import global_storage

app = Flask(__name__)
# Restrict uploading files larger than 10kB.
# Tokens are ~1kB, but this prevents cat GIF uploads.
app.config['MAX_CONTENT_LENGTH'] = 10 * 1024

@app.route('/')
@app.route('/index')
def index():
	return render_template('seller.html', REDEEMER_URL=global_storage.REDEEMER_URL)

@app.route('/Dryer21Client.py')
def download_client():
	response = make_response(render_template(
		'Dryer21Client.py.template',
		CryptoVars=global_storage.CryptoVars,
	))
	response.headers['Content-Disposition'] = 'attachment; filename=Dryer21Client.py'
	return response
Example #27
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 #28
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)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
root_url = config['Root_URL']
Debug = config['Debug']
realhost = config['realhost']
basepath = os.path.join(config['MediaRoot'])

app = Flask(__name__)
logging.basicConfig(level=logging.DEBUG)

app.config['LDAP_SERVER'] = config['ldap_server']
app.config['LDAP_PORT'] = int(config['ldap_port'])
app.config['LDAP_PROTOCOL_VERSION'] = 3
app.config['LDAP_BASE_DN'] = config['ldap_basedn']
app.config['LDAP_BASE_SEARCH'] = config.get('ldap_search', raw=True)
# Max must be the same as the nginx parameter client_max_body_size
# if nginx is used in front
app.config['MAX_CONTENT_LENGTH'] = 3 * 1024 * 1024
app.config['LDAP_SERVER_CONN'] = ldap3.Server(app.config['LDAP_SERVER'], port=app.config['LDAP_PORT'], use_ssl=False, get_info='NO_INFO')


def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    retval = None
    Flag = False
    try:
        conn = ldap3.Connection(app.config['LDAP_SERVER_CONN'], 'mail=%s,%s' % (username, app.config['LDAP_BASE_DN']), password, auto_bind=False)
        conn.bind()
        if not conn:
            return False
        # Add the LDAP search
Example #30
0
from werkzeug.utils import secure_filename

from curl2share import config
from curl2share import utils

if config.storage == 's3':
    from curl2share.storages.s3 import S3
    from curl2share.storages.redis import Redis
    s3 = S3()
elif config.storage == 'file':
    from curl2share.storages.filesystem import FileSystem
    fs = FileSystem()

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = config.max_file_size * 1024 * 1024
app.config['RATELIMIT_HEADERS_ENABLED'] = True

logger = logging.getLogger(__name__)

limiter = Limiter(app, key_func=get_remote_address)


@app.errorhandler(400)
def bad_request(err):
    ''' HTTP 400 code '''
    logger.error('Invalid request: {} {}.'.format(request.method,
                                                  request.path))
    return make_response('Bad Request', 400)