Example #1
0
    def make_response(self, data, status_code, headers):
        if not data:
            Flask.response_class(
                "",
                mimetype=self.mimetype
            ), status_code, headers

        # if the status code is not a success code
        if status_code % 100 == 4 and self.error_type:
            response_data = self.error_type()
        else:
            if not self.send_type:
                raise EncodeError(
                    "Data could not be encoded into a protobuf message. No "
                    "protobuf message type specified to send."
                )
            response_data = self.send_type()

        copy_dict_to_pb(
            instance=response_data,
            dictionary=data
        )

        return Flask.response_class(
            response_data.SerializeToString(),
            mimetype=self.mimetype
        ), status_code, headers
Example #2
0
def disconnect():
    """Closes the ZeroDB connection."""
    if 'username' in session:
        username = session.pop('username')
        if username in dbs:
            del dbs[username]
    return Flask.response_class(status=204)
def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_object(config_filename)
    app.response_class = MyResponse

    from app.users.models import db
    from app.color.models import db
    from app.size.models import db
    from app.product.models import db
    from app.category.models import db

    db.init_app(app)

    # Blueprints   
    from app.users.views import users
    from app.color.views import color
    from app.size.views import size
    from app.product.views import product
    from app.category.views import category

    app.register_blueprint(users, url_prefix='/api/v1/users')
    app.register_blueprint(color, url_prefix='/api/v1/color')
    app.register_blueprint(size, url_prefix='/api/v1/size')
    app.register_blueprint(product, url_prefix='/api/v1/product')
    app.register_blueprint(category, url_prefix='/api/v1/category')
    

    return app
    
Example #4
0
        def to_response(*args, **kwargs):

            request.data_dict = self.parse_request_data(request)
            try:
                result = fn(*args, **kwargs)
            except JsonDictKeyError:
                abort(400)

            # Similar to flask's app.route, returned werkzeug responses are
            # passed directly back to the caller
            if isinstance(result, Response):
                return result

            # If the view method returns a default flask-style tuple throw
            # an error as when making rest API's the view method more likely
            # to return dicts and status codes than strings and headres
            if (isinstance(result, tuple) and (
                len(result) == 0 or
                not isinstance(result[0], dict)
            )):
                raise EncodeError(
                    "Pbj does not support flask's default tuple format "
                    "of (response, headers) or (response, headers, "
                    "status_code). Either return an instance of "
                    "flask.response_class to override pbj's response "
                    "encoding or return a tuple of (dict, status_code) "
                    "or (dict, status_code, headers)."
                )

            # Verify the server can respond to the client using
            # a mimetype the client accepts. We check after calling because
            # of the nature of Http 406
            mimetype = self.response_mimetype(request)
            if not mimetype:
                abort(406)  # Not Acceptable

            # If result is just an int, it must be a status code, so return
            # the response with no data and a status code
            if isinstance(result, int):
                return Flask.response_class("", mimetype=mimetype), result, []

            data, status_code, headers = _result_to_response_tuple(result)

            if not isinstance(data, dict):
                raise EncodeError(
                    "Methods decorated with api must return a dict, int "
                    "status code or flask Response."
                )

            return self.codecs[mimetype].make_response(
                data,
                status_code,
                headers
            )
Example #5
0
def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_object(config_filename)
    app.response_class = MyResponse

    db.init_app(app)

    # Blueprints
    from app.auth.views import auth
    app.register_blueprint(auth, url_prefix='/api/v1/auth')

    return app
Example #6
0
def create_app(set_config=set_config):
    app = Flask(__name__)
    set_config(app)

    db.init_app(app)
    app.db = db

    register_uris(app)

    app.response_class = ApiResponse

    return app
Example #7
0
def delete(model_name, oid):
    """Deletes an object based on its model name and objectID."""
    db = session_db_or_403()
    model = model_or_404(model_name)

    try:
        with transaction.manager:
            db[model].remove(oid)
    except KeyError:
        abort(404)

    return Flask.response_class(status=204)
Example #8
0
def create_app(config=None, app_name=None):

    if app_name is None:
        app_name = DEFAULT_APPNAME

    app = Flask(app_name, static_folder=None)
    app.response_class = JSONTypeResponse

    configure_app(app, config)
    configure_db(app)
    configure_api(app)

    return app
def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_object(config_filename)
    app.response_class = MyResponse

    from app.users.models import db
    db.init_app(app)

    # Blueprints
    from app.users.views import users
    app.register_blueprint(users, url_prefix='/api/v1/users')

    return app
Example #10
0
def create_app(configuration):
    app = Flask(__name__)
    app.config.from_object(configuration)
    app.response_class = MyResponse

    db.init_app(app)

    # Blueprints
    from app.resources.resources import bucket_list
    app.register_blueprint(bucket_list, url_prefix='/api/v1')

    # Gzip response
    compress.init_app(app)
    return app
Example #11
0
File: pb.py Project: GermainZ/pb
def create_app(config_filename='config.yaml'):
    app = Flask(__name__)
    app.response_class = TextResponse
    app.url_map.converters['id'] = IDConverter
    app.url_map.converters['sha1'] = SHA1Converter

    load_yaml(app, config_filename)
    init_db(app)
    init_cache(app)

    app.register_blueprint(paste)
    app.register_blueprint(url)

    return app
Example #12
0
def connect():
    """Opens a ZeroDB connection.

    A JSON object containing a valid 'username' and 'passphrase' should be
    sent as the request body. Additionally, a 'host' and optional 'port' can
    be supplied to specify the ZeroDB server location; otherwise defaults will
    be used.

    The response will contain an authorization cookie that should be used
    in future requests.
    """
    data = request.get_json()
    username = data.get('username')
    passphrase = data.get('passphrase')

    if zeo_socket:
        socket = zeo_socket
    else:
        host = data.get('host')
        port = data.get('port')
        if host and port:
            socket = (host, port)
        elif host:
            socket = host
        else:
            socket = None

    if not (username and passphrase and socket):
        resp = jsonify(error="Incomplete login information.")
        resp.status_code = 400
        return resp

    try:
        db = zerodb.DB(socket, username=username, password=passphrase)
    except Exception as ex:
        resp = jsonify(error=str(ex),
                       error_class=ex.__class__.__name__)
        resp.status_code = 400
        return resp

    session['username'] = username
    dbs[username] = db

    return Flask.response_class(status=204)
Example #13
0
def app(view_and_schema):
    view_class, schema, _ = view_and_schema
    blueprint = FlumpBlueprint('flump', __name__)
    blueprint.register_flump_view(view_class, '/user/')

    app = Flask(__name__)
    app.response_class = FlumpTestResponse
    app.config['SERVER_NAME'] = 'localhost'
    app.config['SERVER_PROTOCOL'] = 'http'
    app.config['DEBUG'] = True
    app.config['TESTING'] = True

    app.register_blueprint(blueprint, url_prefix='/tester')

    ctx = app.app_context()
    ctx.push()
    try:
        yield app
    finally:
        ctx.pop()
Example #14
0
def get_application():
    application = Flask('rtmpt')
    application.config.update({
        'SECRET_KEY': 'secret_key',
        'RMPT_INTERVALS': (b'\x01', b'\x03', b'\x05', b'\x09', b'\x11', b'\x21'),
        'RTMP_FAIL_RAMPUP': 10,
        'RTMP_SERVER': ('127.0.0.1', 1935),
        'RTMPT_DEFAULT_CONTENT_TYPE': 'application/x-fcs',
        'RTMP_BUFFER_SIZE': 8 * 1024,
        'RTMP_TIMEOUT': 0.020,
    })
    # application.config.from_object(
        # os.environ.get('SETTINGS_MODULE', 'rtmpt.settings').strip())

    application.response_class = RTMPTResponse

    # Installed Apps
    from .views import application as bp
    application.register_blueprint(bp, url_prefix='')
    
    return application
def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_object(config_filename)
    app.response_class = MyResponse

    from app.models import db
    db.init_app(app)

    # Blueprints   
    from app.users.views import users
    app.register_blueprint(users, url_prefix='/api/v1/users')
    
    @app.after_request
    def after_request(response):
        response.headers.add('Access-Control-Allow-Origin', '*')
        response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
        response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
        return response

    return app
    
 def test_delete_session(self):
     sessint = self.session_interface
     sid = sessint.generate_sid()
     key = self.prefix + sid
     val = pickle.dumps(dict(a='a1', b='b1'))
     ten_seconds = 10
     self.redis.setex(key, ten_seconds, val)
     with self.app.test_request_context('/'):
         current_request = request._get_current_object()
         cookie_name = self.app.session_cookie_name
         current_request.cookies = {cookie_name: sid}
         sess = sessint.open_session(self.app, current_request)
         sess.clear()
         resp = Flask.response_class()
         resp = self.app.process_response(resp)
         val1 = self.redis.get(key)
         sessint.save_session(self.app, sess, resp)
         val2 = self.redis.get(key)
         cookie = resp.headers.get('Set-Cookie')
         self.assertIsNotNone(val1)
         self.assertIsNone(val2)
         self.assertIn('session=;', cookie)
 def test_save_session(self):
     sessint = self.session_interface
     sid = sessint.generate_sid()
     key = self.prefix + sid
     val = pickle.dumps(dict(a='a1', b='b1'))
     ten_seconds = 10
     self.redis.setex(key, ten_seconds, val)
     with self.app.test_request_context('/'):
         current_request = request._get_current_object()
         cookie_name = self.app.session_cookie_name
         current_request.cookies = {cookie_name: sid}
         sess = sessint.open_session(self.app, current_request)
         newval = 'b1-modified'
         sess['b'] = newval
         resp = Flask.response_class()
         resp = self.app.process_response(resp)
         sessint.save_session(self.app, sess, resp)
         val = self.redis.get(key)
         val = pickle.loads(val)
         cookie = resp.headers.get('Set-Cookie')
         self.assertEqual(newval, val['b'])
         self.assertIn('session='+sid, cookie)
Example #18
0
def create_app(config_filename):
    app = Flask(__name__)
    app.config.from_object(config_filename)
    app.response_class = MyResponse

    #Init Flask-SQLAlchemy
    from app.basemodels import db
    db.init_app(app)

    # Blueprints
    from app.followers.views import followers
    app.register_blueprint(followers, url_prefix='/followers')

    from app.statistics.views import statistics
    app.register_blueprint(statistics, url_prefix='/statistics')

    from app.tweets.views import tweets
    app.register_blueprint(tweets, url_prefix='/tweets')

    from app.users.views import users
    app.register_blueprint(users, url_prefix='/users')

    return app
Example #19
0
def create_app():
    app = Flask(__name__, static_folder='../public/', static_url_path='/public')
    app.response_class = ResponseJSON
    app.config.from_pyfile(config.FLASK_CONFIG_PATH)

    # change debug output formatter to a pretty one-liner
    format = Formatter("%(levelname)6s | %(relativeCreated)6d | %(filename)s:%(lineno)d | %(message)s")
    app.logger.handlers[0].setFormatter(format)

    # resolve paths relative to this file
    app_path = path.dirname(__file__)
    app.config.update({
        'RECORDINGS_PATH': path.realpath(app_path + '/../public/recordings/'),
        'PATH_USER_PROFILE_IMAGE': path.realpath(app_path + '/../public/profile_images/'),
        'PATH_ASSETS': path.realpath(app_path + '/../public/assets/'),
        'PATH_PUBLIC': path.realpath(app_path + '/../public/'),
    })

    # sanity checks
    if not path.isdir(app.config['RECORDINGS_PATH']):
        raise Exception("Recordings path does not exist: " + app.config['RECORDINGS_PATH'])

    if not path.isdir(app.config['PATH_USER_PROFILE_IMAGE']):
        raise Exception("User profile images path does not exist: " + app.config['PATH_USER_PROFILE_IMAGE'])

    # app.json_encoder = MongoJsonEncoder

    # setup database and session storage
    # db settings come from flask.ini
    # and same engine is used for storing sessions
    mongo = MongoEngine()
    mongo.init_app(app)
    app.session_interface = MongoEngineSessionInterface(mongo)

    # toolbar = DebugToolbarExtension(app)

    return app, mongo
Example #20
0
def make_app():
    cors = CORS(origins=[
        'https://app.communityshare.us:443', # production app
        'http://communityshare.localhost:5000', # local dev angular app
        'http://communityshare.localhost:8000', # local dev elm app
        'https://dmsnell.github.io/cs-elm/', # live elm app
    ])
    compress = Compress()
    webpack = Webpack()
    app = Flask(__name__, template_folder='../static/')
    app.response_class = JsonifyDictResponse

    app.config['SQLALCHEMY_DATABASE_URI'] = config.DB_CONNECTION
    app.config['WEBPACK_ASSETS_URL'] = config.WEBPACK_ASSETS_URL
    app.config['WEBPACK_MANIFEST_PATH'] = config.WEBPACK_MANIFEST_PATH

    cors.init_app(app)
    compress.init_app(app)
    webpack.init_app(app)

    if config.SSL != 'NO_SSL':
        flask_sslify.SSLify(app)
        app.wsgi_app = ReverseProxied(app.wsgi_app)

    register_user_routes(app)
    register_search_routes(app)
    register_conversation_routes(app)
    register_share_routes(app)
    register_survey_routes(app)
    register_email_routes(app)
    register_statistics_routes(app)

    community_share.api.register_routes(app)

    @app.teardown_appcontext
    def close_db_connection(exception):
        store.session.remove()

    @app.errorhandler(BadRequest)
    def handle_bad_request(error):
        return str(error), HTTPStatus.BAD_REQUEST

    app.errorhandler(Unauthorized)(jsonify_with_code(HTTPStatus.UNAUTHORIZED))
    app.errorhandler(Forbidden)(jsonify_with_code(HTTPStatus.FORBIDDEN))
    app.errorhandler(NotFound)(jsonify_with_code(HTTPStatus.NOT_FOUND))
    app.errorhandler(InternalServerError)(jsonify_with_code(HTTPStatus.INTERNAL_SERVER_ERROR))

    @app.route('/static/build/<path:filename>')
    def build_static(filename):
        return send_from_directory(
            app.root_path + '/../static/build/',
            filename,
            cache_timeout=YEAR_IN_SECONDS,
        )

    @app.route('/static/js/<path:filename>')
    def js_static(filename):
        return send_from_directory(app.root_path + '/../static/js/', filename)

    @app.route('/static/fonts/<path:filename>')
    def fonts_static(filename):
        return send_from_directory(app.root_path + '/../static/fonts/', filename)

    @app.route('/static/css/<path:filename>')
    def css_static(filename):
        return send_from_directory(app.root_path + '/../static/css/', filename)

    @app.route('/static/templates/footer.html')
    def footer_template():
        return render_template('templates/footer.html', config=config)

    @app.route('/static/templates/<path:filename>')
    def templates_static(filename):
        return send_from_directory(app.root_path + '/../static/templates/', filename)

    @app.route('/')
    def index():
        logger.debug('rendering index')
        return render_template('index.html', config=config)

    return app
Example #21
0
from Manager.ProxyManager import ProxyManager

app = Flask(__name__)


class JsonResponse(Response):

    @classmethod
    def force_type(cls, response, environ=None):
        if isinstance(response, (dict, list)):
            response = jsonify(response)

        return super(JsonResponse, cls).force_type(response, environ)


app.response_class = JsonResponse

api_list = {
    'get': u'get an usable proxy',
    # 'refresh': u'refresh proxy pool',
    'get_all': u'get all proxy from proxy pool',
    'delete?proxy=127.0.0.1:8080': u'delete an unable proxy',
    'get_status': u'proxy statistics'
}


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

Example #22
0
# -*- coding: utf-8 -*-
from .responses import JSONResponse, connection_error, authenticate
from .utils import encode_auth
from .crawler import Crawler
from .exceptions import AuthError
from urllib3.exceptions import MaxRetryError
from flask import Flask, request, jsonify, make_response
from functools import wraps


app = Flask(__name__)
app.response_class = JSONResponse


@app.errorhandler(404)
def not_found(e=None):
    """Return a JSON with error on 404, instead of ugly HTML"""
    return make_response(jsonify({"errore": u"Una o più risorse non trovate."}), 404)


def requires_auth(f):
    """Decorator for authentication"""

    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if (not auth) or (not auth.username) or (not auth.password):
            return authenticate()
        return f(*args, **kwargs)

    return decorated
Example #23
0
from urllib import urlencode
import os

from flask import Flask, redirect, request
import requests

from pylexa.app import alexa_blueprint, handle_launch_request
from pylexa.intent import handle_intent
from pylexa.response import (
    AlexaResponseWrapper, LinkAccountCard, PlainTextSpeech, Response, SimpleCard
)


app = Flask(__name__)
app.register_blueprint(alexa_blueprint)
app.response_class = AlexaResponseWrapper

AWS_VENDOR_ID = os.getenv('AWS_VENDOR_ID')
SLACK_CLIENT_ID = os.getenv('SLACK_CLIENT_ID')
SLACK_CLIENT_SECRET = os.getenv('SLACK_CLIENT_SECRET')
SLACK_CHANNEL = os.getenv('SLACK_CHANNEL', 'botstuff')


@app.before_request
def log_request_json():
    print request.headers
    print request.json


@handle_launch_request
def handle_launch(request):
Example #24
0
app = Flask(__name__)

#config object, load oduction from envvar
app.config.from_object(config)

db = redis.StrictRedis(db=0)

photos = UploadSet('photos', IMAGES)
configure_uploads(app, photos)

# 32 mb max upload size
patch_request_class(app, 32 * 1024 * 1024)

#boiler plate json response
RESP_DICT = {'data': [], 'status': 404}
resp = app.response_class(mimetype='application/json')


def return404():
    #this does not overwrite global vars
    RESP_DICT = {'data': [], 'status': 404}
    resp.data = json.dumps(RESP_DICT)
    resp.status_code = 404
    return resp


def return400():
    #this does not overwrite global vars
    RESP_DICT['status'] = 400
    RESP_DICT['data'] = ['Invalid request!']
    resp.data = json.dumps(RESP_DICT)
Example #25
0
File: app.py Project: isaced/istour
import models

class MyResponse(Response):
    def __init__(self, response=None, **kwargs):
        kwargs['headers'] = ''
        headers = kwargs.get('headers')
        # 跨域控制
        origin = ('Access-Control-Allow-Origin', '*')
        if headers:
            headers.add(*origin)
        else:
            headers = Headers([origin])
        kwargs['headers'] = headers
        return super().__init__(response, **kwargs)

app.response_class = MyResponse

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

@app.route('/cities')
def cities():
    obj_list = models.City.query.all()
    return render_template('list.html',title='城市', obj_list=obj_list)

@app.route('/city_add', methods=['POST'])
def city_add():
    print('Call city_add....')
    city_name = request.form['obj_name']
    print(city_name)
Example #26
0
from flask import Flask, Response
from ricecrew import settings

class XhtmlResponse(Response):
    default_mimetype = 'application/xhtml+xml'

app = Flask(__name__)
app.config.from_object(settings)
app.response_class = XhtmlResponse
Example #27
0
def app(request):
    app = Flask(__name__)
    app.response_class = Response
    app.debug = True
    app.config['SECRET_KEY'] = 'secret'
    app.config['TESTING'] = True
    app.config['LOGIN_DISABLED'] = False
    app.config['WTF_CSRF_ENABLED'] = False

    for opt in ['changeable', 'recoverable', 'registerable',
                'trackable', 'passwordless', 'confirmable']:
        app.config['SECURITY_' + opt.upper()] = opt in request.keywords

    if 'settings' in request.keywords:
        for key, value in request.keywords['settings'].kwargs.items():
            app.config['SECURITY_' + key.upper()] = value

    mail = Mail(app)
    app.mail = mail

    @app.route('/')
    def index():
        return render_template('index.html', content='Home Page')

    @app.route('/profile')
    @login_required
    def profile():
        return render_template('index.html', content='Profile Page')

    @app.route('/post_login')
    @login_required
    def post_login():
        return render_template('index.html', content='Post Login')

    @app.route('/http')
    @http_auth_required
    def http():
        return 'HTTP Authentication'

    @app.route('/http_custom_realm')
    @http_auth_required('My Realm')
    def http_custom_realm():
        return render_template('index.html', content='HTTP Authentication')

    @app.route('/token', methods=['GET', 'POST'])
    @auth_token_required
    def token():
        return render_template('index.html', content='Token Authentication')

    @app.route('/multi_auth')
    @auth_required('session', 'token', 'basic')
    def multi_auth():
        return render_template('index.html', content='Session, Token, Basic auth')

    @app.route('/post_logout')
    def post_logout():
        return render_template('index.html', content='Post Logout')

    @app.route('/post_register')
    def post_register():
        return render_template('index.html', content='Post Register')

    @app.route('/admin')
    @roles_required('admin')
    def admin():
        return render_template('index.html', content='Admin Page')

    @app.route('/admin_and_editor')
    @roles_required('admin', 'editor')
    def admin_and_editor():
        return render_template('index.html', content='Admin and Editor Page')

    @app.route('/admin_or_editor')
    @roles_accepted('admin', 'editor')
    def admin_or_editor():
        return render_template('index.html', content='Admin or Editor Page')

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

    @app.route('/page1')
    def page_1():
        return 'Page 1'
    return app
from flask import Flask, jsonify
from werkzeug.wrappers import Response
from werkzeug.wsgi import DispatcherMiddleware

app = Flask(__name__)
json_page = Flask(__name__)


class JSONResponse(Response):
    @classmethod
    def force_type(cls, rv, environ=None):
        if isinstance(rv, dict):
            rv = jsonify(rv)
        return super(JSONResponse, cls).force_type(rv, environ)

json_page.response_class = JSONResponse


@json_page.route('/hello/')
def hello():
    return {'message': 'Hello World!'}


@app.route('/')
def index():
    return 'The index page'


app.wsgi_app = DispatcherMiddleware(app.wsgi_app, OrderedDict((
    ('/json', json_page),
)))
Example #29
0
        success = True

    return app.response_class(json.dumps({'login_result': success}), content_type='application/json')


@app.route('/nest/devices', methods=['GET'])
def list_devices():

    try:
        nest.check_login()
    except (LogInException, NotFoundException), ex:
        _log.error(ex.message)
        abort(401, ex.message)

    devices = map(lambda device: device.name, nest.list_devices())
    return app.response_class(json.dumps({'devices': devices}), content_type='application/json')


@app.route('/device/<deviceid>/<property>/<value>', methods=['PUT'])
def set_value(deviceid, property, value):

    _log.info('{0} {1} {2}'.format(deviceid, property, value))
    success = False
    try:
        nest.check_login()
        success = nest.set_property(deviceid, property, value)

    except LogInException, ex:
        _log.error(ex.message)
        abort(401, ex.message)
    except (NotFoundException, AttributeError), ex:
Example #30
0
app = Flask(__name__)
_log = get_logger(__name__)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
nest = NestIntegration()


@app.route('/homekit/devices', methods=['GET'])
def list_devices():
    try:
        res = requests.get("{0}/{1}".format(HOMEKIT_URL,"devices"))
    except (LogInException, NotFoundException), ex:
        _log.error(ex.message)
        abort(401, ex.message)

    toret = res.json() if res.content != '' else {"error": "error"}
    return app.response_class(json.dumps(toret), content_type='application/json')

@app.route('/homekit/<room_name>/devices', methods=['GET'])
def list_room_devices(room_name):

    try:
        res = requests.get("{0}/{1}/{2}".format(HOMEKIT_URL,"room", room_name))
        print res.json()
    except (LogInException, NotFoundException), ex:
        _log.error(ex.message)
        abort(401, ex.message)

    toret = res.json() if res.content != '' else {"error": "error"}
    return app.response_class(json.dumps(toret), content_type='application/json')

@app.route('/homekit/property/<room>/<accessory>/<service>/<property>', methods=['POST'])