Пример #1
0
def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    formatter = logging.Formatter(
        "[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s")
    handler = RotatingFileHandler('schedulingsystem.log',
                                  maxBytes=10000000,
                                  backupCount=5)
    handler.setLevel(logging.WARNING)
    handler.setFormatter(formatter)
    app.logger.addHandler(handler)

    api = Api(app, catch_all_404s=True)
    api.handle_error = handle_scheduling_exception
    db.init_app(app)
    migrate.init_app(app, db)

    from schedulingsystem import models
    from schedulingsystem.meetingroom.api import MeetingRoomItemApi, MeetingRoomListApi
    from schedulingsystem.user.api import UserItemApi, UserListApi
    from schedulingsystem.scheduling.api import SchedulingListApi, SchedulingItemApi

    api.add_resource(MeetingRoomListApi, '/meetingroom')
    api.add_resource(MeetingRoomItemApi, '/meetingroom/<int:id>')
    api.add_resource(UserListApi, '/user')
    api.add_resource(UserItemApi, '/user/<int:id>')
    api.add_resource(SchedulingListApi, '/scheduling')
    api.add_resource(SchedulingItemApi, '/scheduling/<int:id>')

    return app
Пример #2
0
 def handle_error(self, e):
     """Transform a Flask-RESTful parsing error (HTTP 400) in a 412 with the inner error
         message."""
     if hasattr(e, 'code') and hasattr(e, 'data'):
         if e.code == 400 and ('message' in e.data):
             r = self.make_response({'error': e.data['message']}, 412)
             r.headers['Content-type'] = 'application/json'
             return r
     return Api.handle_error(self, e)
Пример #3
0
def create_app():

    logger.debug("Starting app")

    # create main blueprint
    api_bp = Blueprint("api", __name__)

    # create the api - flask_restful
    api = Api(api_bp)

    # Let's define a custom error handler of the API
    def custom_handle_error(self, e):
        abort(e.code, description=str(e))

    api.handle_error = custom_handle_error

    # create and configure the app
    app = Flask(__name__)
    app.config.from_object(config)
    CORS(app)

    @app.errorhandler(Exception)
    def _handle_api_error(ex):

        if isinstance(ex, APIException):
            return jsonify(ex.to_dict()), ex.status_code
        else:
            logger.exception(ex)

            return jsonify({
                'title':
                "INTERNAL SERVER ERROR",
                'description':
                "Something went wrong handling the request: {}".format(
                    type(ex)),
                'code':
                201
            }), 500

    # Still outside the context.
    # Let's attach it to app
    with app.app_context():

        app.register_blueprint(api_bp)

        from wld.blueprints import listener_bp
        from wld.blueprints.routes import initialize_routes
        initialize_routes(api)

        app.register_blueprint(listener_bp)

    return app
Пример #4
0
def create_app():
    from src.controllers.common import errors
    # flask app config
    app = Flask(__name__)
    CORS(app)
    app.config.from_object(Config)
    # Database()
    app.app_context().push()
    api = Api(app, errors=errors.errors)

    # Register api endpoint
    api.add_resource(MovieSuggestController, '/movie')

    flask_restfull_default_handle_error = api.handle_error

    def webapi_default_error_handler(error):
        '''Default error handler'''
        try:
            if error.custom_message is not None:
                if error.api_code is not None:
                    code = '{}.{}'.format(
                        error.api_code,
                        api.errors[error.__class__.__name__]['code'])
                else:
                    code = api.errors[error.__class__.__name__]['code']

                return {
                    'message': error.custom_message,
                    'status': api.errors[error.__class__.__name__]['status'],
                    'code': code
                }, getattr(error, 'code', 500)
            else:
                return flask_restfull_default_handle_error(error)
        except:
            return flask_restfull_default_handle_error(error)

    api.handle_error = webapi_default_error_handler
    return app
Пример #5
0
from flask import Blueprint, render_template, request, url_for, redirect, flash, session, g, jsonify
from sqlalchemy import or_, and_
from models.userinfo import Userinfo
from models.movie_info import Movieinfo
from models.comments import Comments
from models.base import db
from flask_restful import Resource, Api, reqparse
from libs.handler import default_error_handler

api = Api()
api.handle_error = default_error_handler

movie_bp = Blueprint('movie', __name__)


# 电影列表
@movie_bp.route('/movie')
def movie():
    # page
    # 当前页数
    # per_page
    # 每页显示的条�?
    # error_out
    # 是否打印错误信息
    page = int(request.args.get('page', 1))
    per_page = int(request.args.get('per_page', 10))  # 这里�?0 决定每页显示的数目,可自行调�?
    paginate = Movieinfo.query.order_by(Movieinfo.movieid).paginate(
        page, per_page, error_out=False)
    movies = paginate.items  #  拿到分页后的数据

    context = {
Пример #6
0
    def put(self, title=None):
        form = request.form
        content = form.get('content')
        return get_storage_client().create_article(title=title,
                                                   content=content), 201

    @marshal_with(responses.Article.resource_fields)
    def post(self, title=None):
        data = request.form
        content = data.get('content')
        new_title = data.get('title')
        return get_storage_client().update_article(title,
                                                   new_title=new_title,
                                                   content=content), 200


api.add_resource(Article, '/article/<title>', endpoint='article/<title>')
api.add_resource(Articles, '/articles', endpoint='articles')


def handle_invalid_usage(error):
    response = error.__dict__
    return json.dumps(response), response.get('status_code', 500)


api.handle_error = handle_invalid_usage

if __name__ == '__main__':
    init_db()
    app.run(host='0.0.0.0', port=8080)
    """Handle the /readiness REST API call."""
    return jsonify({}), 200


@api_v1.route('/liveness')
def liveness():
    """Handle the /liveness REST API call."""
    # Check database connection
    current_app.logger.debug("Liveness probe - trying to connect to database "
                             "and execute a query")
    rdb.session.query(Ecosystem).count()
    return jsonify({}), 200


api_v1.coreapi_http_error_handler = handle_http_error
rest_api_v1.handle_error = handle_http_error


def get_item_skip(page, per_page):
    """Get the number of items to skip for the first page-1 pages."""
    return per_page * page


def get_item_relative_limit(page, per_page):
    """Get the maximum possible number of items on one page."""
    return per_page


def get_item_absolute_limit(page, per_page):
    """Get the total possible number of items."""
    return per_page * (page + 1)