コード例 #1
0
def create_app(config_filename=None):
    """create app."""
    app = FlaskAPI(__name__)
    per_page = int(os.getenv('BUKUSERVER_PER_PAGE', str(views.DEFAULT_PER_PAGE)))
    per_page = per_page if per_page > 0 else views.DEFAULT_PER_PAGE
    app.config['BUKUSERVER_PER_PAGE'] = per_page
    url_render_mode = os.getenv('BUKUSERVER_URL_RENDER_MODE', views.DEFAULT_URL_RENDER_MODE)
    if url_render_mode not in ('full', 'netloc'):
        url_render_mode = views.DEFAULT_URL_RENDER_MODE
    app.config['BUKUSERVER_URL_RENDER_MODE'] = url_render_mode
    app.config['SECRET_KEY'] = os.getenv('BUKUSERVER_SECRET_KEY') or os.urandom(24)
    app.config['BUKUSERVER_DB_FILE'] = os.getenv('BUKUSERVER_DB_FILE')
    bukudb = BukuDb(dbfile=app.config['BUKUSERVER_DB_FILE'])
    app.app_context().push()
    setattr(flask.g, 'bukudb', bukudb)

    @app.shell_context_processor
    def shell_context():
        """Shell context definition."""
        return {'app': app, 'bukudb': bukudb}

    app.jinja_env.filters['netloc'] = lambda x: urlparse(x).netloc  # pylint: disable=no-member

    Bootstrap(app)
    admin = Admin(
        app, name='Buku Server', template_mode='bootstrap3',
        index_view=views.CustomAdminIndexView(
            template='bukuserver/home.html', url='/'
        )
    )
    # routing
    #  api
    app.add_url_rule('/api/tags', 'get_tags', tag_list, methods=['GET'])
    app.add_url_rule('/api/tags/<tag>', 'update_tag', tag_detail, methods=['GET', 'PUT'])
    app.add_url_rule('/api/network_handle', 'networkk_handle', network_handle_detail, methods=['POST'])
    app.add_url_rule('/api/bookmarks', 'bookmarks', bookmarks, methods=['GET', 'POST', 'DELETE'])
    app.add_url_rule('/api/bookmarks/refresh', 'refresh_bookmarks', refresh_bookmarks, methods=['POST'])
    app.add_url_rule('/api/bookmarks/<id>', 'bookmark_api', bookmark_api, methods=['GET', 'PUT', 'DELETE'])
    app.add_url_rule('/api/bookmarks/<id>/refresh', 'refresh_bookmark', refresh_bookmark, methods=['POST'])
    app.add_url_rule('/api/bookmarks/<id>/tiny', 'get_tiny_url', get_tiny_url, methods=['GET'])
    app.add_url_rule('/api/bookmarks/<id>/long', 'get_long_url', get_long_url, methods=['GET'])
    app.add_url_rule(
        '/api/bookmarks/<starting_id>/<ending_id>',
        'bookmark_range_operations', bookmark_range_operations, methods=['GET', 'PUT', 'DELETE'])
    app.add_url_rule('/api/bookmarks/search', 'search_bookmarks', search_bookmarks, methods=['GET', 'DELETE'])
    #  non api
    admin.add_view(views.BookmarkModelView(
        bukudb, 'Bookmarks', page_size=per_page, url_render_mode=url_render_mode))
    admin.add_view(views.TagModelView(
        bukudb, 'Tags', page_size=per_page))
    admin.add_view(views.StatisticView(
        bukudb, 'Statistic', endpoint='statistic'))
    return app
コード例 #2
0
ファイル: server.py プロジェクト: multiparadigma/Buku
def create_app(config_filename=None):
    """create app."""
    app = FlaskAPI(__name__)
    per_page = int(os.getenv('BUKUSERVER_PER_PAGE', str(views.DEFAULT_PER_PAGE)))
    per_page = per_page if per_page > 0 else views.DEFAULT_PER_PAGE
    app.config['BUKUSERVER_PER_PAGE'] = per_page
    url_render_mode = os.getenv('BUKUSERVER_URL_RENDER_MODE', views.DEFAULT_URL_RENDER_MODE)
    if url_render_mode not in ('full', 'netloc'):
        url_render_mode = views.DEFAULT_URL_RENDER_MODE
    app.config['BUKUSERVER_URL_RENDER_MODE'] = url_render_mode
    app.config['SECRET_KEY'] = os.getenv('BUKUSERVER_SECRET_KEY') or os.urandom(24)
    bukudb = BukuDb()
    app.app_context().push()
    setattr(flask.g, 'bukudb', bukudb)

    @app.shell_context_processor
    def shell_context():
        """Shell context definition."""
        return {'app': app, 'bukudb': bukudb}

    app.jinja_env.filters['netloc'] = lambda x: urlparse(x).netloc  # pylint: disable=no-member

    Bootstrap(app)
    admin = Admin(
        app, name='Buku Server', template_mode='bootstrap3',
        index_view=views.CustomAdminIndexView(
            template='bukuserver/home.html', url='/'
        )
    )
    # routing
    #  api
    app.add_url_rule('/api/tags', 'get_tags', tag_list, methods=['GET'])
    app.add_url_rule('/api/tags/<tag>', 'update_tag', tag_detail, methods=['GET', 'PUT'])
    app.add_url_rule('/api/network_handle', 'networkk_handle', network_handle_detail, methods=['POST'])
    app.add_url_rule('/api/bookmarks', 'bookmarks', bookmarks, methods=['GET', 'POST', 'DELETE'])
    app.add_url_rule('/api/bookmarks/refresh', 'refresh_bookmarks', refresh_bookmarks, methods=['POST'])
    app.add_url_rule('/api/bookmarks/<id>', 'bookmark_api', bookmark_api, methods=['GET', 'PUT', 'DELETE'])
    app.add_url_rule('/api/bookmarks/<id>/refresh', 'refresh_bookmark', refresh_bookmark, methods=['POST'])
    app.add_url_rule('/api/bookmarks/<id>/tiny', 'get_tiny_url', get_tiny_url, methods=['GET'])
    app.add_url_rule('/api/bookmarks/<id>/long', 'get_long_url', get_long_url, methods=['GET'])
    app.add_url_rule(
        '/api/bookmarks/<starting_id>/<ending_id>',
        'bookmark_range_operations', bookmark_range_operations, methods=['GET', 'PUT', 'DELETE'])
    app.add_url_rule('/api/bookmarks/search', 'search_bookmarks', search_bookmarks, methods=['GET', 'DELETE'])
    #  non api
    admin.add_view(views.BookmarkModelView(
        bukudb, 'Bookmarks', page_size=per_page, url_render_mode=url_render_mode))
    admin.add_view(views.TagModelView(
        bukudb, 'Tags', page_size=per_page))
    admin.add_view(views.StatisticView('Statistic', endpoint='statistic'))
    return app
コード例 #3
0
def create_app(config_name):
    from app.models.category import Category
    from app.models.recipe import Recipe
    from app.models.recipeAuth import RecipeApp
    app = FlaskAPI(__name__, instance_relative_config=True)
    app.config.from_object(
        app_config[config_name]
    )  #app.config.from_object(app_config['development'])
    app.config.from_pyfile('config.py')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)
    CORS(app)
    with app.app_context():
        db.create_all()

    # Blueprints
    # import the authentication blueprint and register it on the app
    from .auth import auth_blueprint
    app.register_blueprint(auth_blueprint)

    # import the category blueprint and register it on the app
    from .categories import category_api
    app.register_blueprint(category_api)

    # import the recipe blueprint and register it on the app
    from .recipes import recipe_api
    app.register_blueprint(recipe_api)

    return app
コード例 #4
0
def create_app(config_name):
    from backend.app.models.UDIS import UDIS
    from backend.app.models.Dollars import Dollars

    app = FlaskAPI(__name__, instance_relative_config=True)
    CORS(app)
    app.config.from_object(app_config['development'])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)
    with app.app_context():
        db.create_all()

    @app.route('/UDIS/', methods=['GET'])
    def udis():
        schema = UrlQuerySchema()

        errors = schema.validate(request.args)

        if errors:
            abort(400, str(errors))

        args = request.args

        udis = UDIS.get_udis_from_range(args.get('start_date', ''),
                                        args.get('end_date', ''))
        values = [udi.get('value') for udi in udis]
        _max, _min, avg = StatsUtils.max_min_avg(values)

        response = {'data': udis, 'max': _max, 'min': _min, 'avg': avg}
        response = jsonify(response)
        response.status_code = 200
        return response

    @app.route('/dollars/', methods=['GET'])
    def dolars():
        schema = UrlQuerySchema()

        errors = schema.validate(request.args)

        if errors:
            abort(400, str(errors))

        args = request.args

        dollars = Dollars.get_dollars_from_range(args.get('start_date', ''),
                                                 args.get('end_date', ''))
        values = [dollar.get('value') for dollar in dollars]
        _max, _min, avg = StatsUtils.max_min_avg(values)

        response = {'data': dollars, 'max': _max, 'min': _min, 'avg': avg}
        response = jsonify(response)
        response.status_code = 200
        return response

    return app
コード例 #5
0
ファイル: __init__.py プロジェクト: patlub/BucketListAPI
def create_app(config_name):
    app = FlaskAPI(__name__, instance_relative_config=True)
    app.config.from_object(application_config[config_name])
    app.config.from_pyfile('config.py')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    CORS(app)
    db.init_app(app)
    with app.app_context():
        db.create_all()

    return app
コード例 #6
0
ファイル: __init__.py プロジェクト: darialukash/flask-app
def create_app(configure=ConfProd):
    app = FlaskAPI(__name__)
    app.config.from_object(configure)
    db.init_app(app)
    migrate.init_app(app, db)

    @app.route('/')
    def index():
        return 'Hello World!'

    from . import models
    from .models import Person

    with app.app_context() as context:
        context.push()
        db.create_all()

        @app.route('/database', methods=['GET', 'POST'])
        @set_parsers(JSONParser)
        def examlpe():

            if request.method == "GET":
                content = {
                    'Persons in DB': len(db.session.query(Person).all())
                }
                return content
            elif request.method == "POST":
                try:
                    content = request.data
                    name = content['name']
                    age = content['age']
                    newPerson = Person(name, age)
                    newPerson.save()
                    db.session.commit()
                    print(db.session.query(Person)[-1])
                    return content

                except KeyError:
                    return content

    return app
コード例 #7
0
ファイル: server.py プロジェクト: wkrea/Buku
def create_app(db_file=None):
    """create app."""
    app = FlaskAPI(__name__)
    per_page = int(os.getenv('BUKUSERVER_PER_PAGE', str(views.DEFAULT_PER_PAGE)))
    per_page = per_page if per_page > 0 else views.DEFAULT_PER_PAGE
    app.config['BUKUSERVER_PER_PAGE'] = per_page
    url_render_mode = os.getenv('BUKUSERVER_URL_RENDER_MODE', views.DEFAULT_URL_RENDER_MODE)
    if url_render_mode not in ('full', 'netloc'):
        url_render_mode = views.DEFAULT_URL_RENDER_MODE
    app.config['BUKUSERVER_URL_RENDER_MODE'] = url_render_mode
    app.config['SECRET_KEY'] = os.getenv('BUKUSERVER_SECRET_KEY') or os.urandom(24)
    disable_favicon = os.getenv('BUKUSERVER_DISABLE_FAVICON', 'false')
    app.config['BUKUSERVER_DISABLE_FAVICON'] = \
        False if disable_favicon.lower() in ['false', '0'] else bool(disable_favicon)
    open_in_new_tab = os.getenv('BUKUSERVER_OPEN_IN_NEW_TAB', 'false')
    app.config['BUKUSERVER_OPEN_IN_NEW_TAB'] = \
        False if open_in_new_tab.lower() in ['false', '0'] else bool(open_in_new_tab)
    app.config['BUKUSERVER_DB_FILE'] = os.getenv('BUKUSERVER_DB_FILE') or db_file
    bukudb = BukuDb(dbfile=app.config['BUKUSERVER_DB_FILE'])
    app.app_context().push()
    setattr(flask.g, 'bukudb', bukudb)

    @app.shell_context_processor
    def shell_context():
        """Shell context definition."""
        return {'app': app, 'bukudb': bukudb}

    app.jinja_env.filters['netloc'] = lambda x: urlparse(x).netloc  # pylint: disable=no-member

    Bootstrap(app)
    admin = Admin(
        app, name='Buku Server', template_mode='bootstrap3',
        index_view=views.CustomAdminIndexView(
            template='bukuserver/home.html', url='/'
        )
    )
    # routing
    #  api
    tag_api_view = ApiTagView.as_view('tag_api')
    app.add_url_rule('/api/tags', defaults={'tag': None}, view_func=tag_api_view, methods=['GET'])
    app.add_url_rule('/api/tags/<tag>', view_func=tag_api_view, methods=['GET', 'PUT'])
    bookmark_api_view = ApiBookmarkView.as_view('bookmark_api')
    app.add_url_rule('/api/bookmarks', defaults={'rec_id': None}, view_func=bookmark_api_view, methods=['GET', 'POST', 'DELETE'])
    app.add_url_rule('/api/bookmarks/<int:rec_id>', view_func=bookmark_api_view, methods=['GET', 'PUT', 'DELETE'])
    app.add_url_rule('/api/bookmarks/refresh', 'refresh_bookmark', refresh_bookmark, defaults={'rec_id': None}, methods=['POST'])
    app.add_url_rule('/api/bookmarks/<int:rec_id>/refresh', 'refresh_bookmark', refresh_bookmark, methods=['POST'])
    app.add_url_rule('/api/bookmarks/<int:rec_id>/tiny', 'get_tiny_url', get_tiny_url, methods=['GET'])
    app.add_url_rule('/api/network_handle', 'network_handle', handle_network, methods=['POST'])
    bookmark_range_api_view = ApiBookmarkRangeView.as_view('bookmark_range_api')
    app.add_url_rule(
        '/api/bookmarks/<int:starting_id>/<int:ending_id>',
        view_func=bookmark_range_api_view, methods=['GET', 'PUT', 'DELETE'])
    bookmark_search_api_view = ApiBookmarkSearchView.as_view('bookmark_search_api')
    app.add_url_rule('/api/bookmarks/search', view_func=bookmark_search_api_view, methods=['GET', 'DELETE'])
    #  non api
    admin.add_view(views.BookmarkModelView(
        bukudb, 'Bookmarks', page_size=per_page, url_render_mode=url_render_mode))
    admin.add_view(views.TagModelView(
        bukudb, 'Tags', page_size=per_page))
    admin.add_view(views.StatisticView(
        bukudb, 'Statistic', endpoint='statistic'))
    return app
コード例 #8
0
ファイル: server.py プロジェクト: vishalbelsare/Buku
def create_app(db_file=None):
    """create app."""
    app = FlaskAPI(__name__)
    per_page = int(os.getenv('BUKUSERVER_PER_PAGE', str(views.DEFAULT_PER_PAGE)))
    per_page = per_page if per_page > 0 else views.DEFAULT_PER_PAGE
    app.config['BUKUSERVER_PER_PAGE'] = per_page
    url_render_mode = os.getenv('BUKUSERVER_URL_RENDER_MODE', views.DEFAULT_URL_RENDER_MODE)
    if url_render_mode not in ('full', 'netloc'):
        url_render_mode = views.DEFAULT_URL_RENDER_MODE
    app.config['BUKUSERVER_URL_RENDER_MODE'] = url_render_mode
    app.config['SECRET_KEY'] = os.getenv('BUKUSERVER_SECRET_KEY') or os.urandom(24)
    app.config['BUKUSERVER_DISABLE_FAVICON'] = \
        get_bool_from_env_var('BUKUSERVER_DISABLE_FAVICON', True)
    app.config['BUKUSERVER_OPEN_IN_NEW_TAB'] = \
        get_bool_from_env_var('BUKUSERVER_OPEN_IN_NEW_TAB', False)
    app.config['BUKUSERVER_DB_FILE'] = os.getenv('BUKUSERVER_DB_FILE') or db_file
    reverse_proxy_path = os.getenv('BUKUSERVER_REVERSE_PROXY_PATH')
    if reverse_proxy_path:
        if not reverse_proxy_path.startswith('/'):
            print('Warning: reverse proxy path should include preceding slash')
        if reverse_proxy_path.endswith('/'):
            print('Warning: reverse proxy path should not include trailing slash')
        app.config['REVERSE_PROXY_PATH'] = reverse_proxy_path
        if ReverseProxyPrefixFix:
            ReverseProxyPrefixFix(app)
        else:
            raise ImportError('Failed to import ReverseProxyPrefixFix')
    bukudb = BukuDb(dbfile=app.config['BUKUSERVER_DB_FILE'])
    app.app_context().push()
    setattr(flask.g, 'bukudb', bukudb)

    @app.shell_context_processor
    def shell_context():
        """Shell context definition."""
        return {'app': app, 'bukudb': bukudb}

    app.jinja_env.filters['netloc'] = lambda x: urlparse(x).netloc  # pylint: disable=no-member

    Bootstrap(app)
    admin = Admin(
        app, name='buku server', template_mode='bootstrap3',
        index_view=views.CustomAdminIndexView(
            template='bukuserver/home.html', url='/'
        )
    )
    # routing
    #  api
    tag_api_view = ApiTagView.as_view('tag_api')
    app.add_url_rule('/api/tags', defaults={'tag': None}, view_func=tag_api_view, methods=['GET'])
    app.add_url_rule('/api/tags/<tag>', view_func=tag_api_view, methods=['GET', 'PUT'])
    bookmark_api_view = ApiBookmarkView.as_view('bookmark_api')
    app.add_url_rule('/api/bookmarks', defaults={'rec_id': None}, view_func=bookmark_api_view, methods=['GET', 'POST', 'DELETE'])
    app.add_url_rule('/api/bookmarks/<int:rec_id>', view_func=bookmark_api_view, methods=['GET', 'PUT', 'DELETE'])
    app.add_url_rule('/api/bookmarks/refresh', 'refresh_bookmark', refresh_bookmark, defaults={'rec_id': None}, methods=['POST'])
    app.add_url_rule('/api/bookmarks/<int:rec_id>/refresh', 'refresh_bookmark', refresh_bookmark, methods=['POST'])
    app.add_url_rule('/api/bookmarks/<int:rec_id>/tiny', 'get_tiny_url', get_tiny_url, methods=['GET'])
    app.add_url_rule('/api/network_handle', 'network_handle', handle_network, methods=['POST'])
    bookmark_range_api_view = ApiBookmarkRangeView.as_view('bookmark_range_api')
    app.add_url_rule(
        '/api/bookmarks/<int:starting_id>/<int:ending_id>',
        view_func=bookmark_range_api_view, methods=['GET', 'PUT', 'DELETE'])
    bookmark_search_api_view = ApiBookmarkSearchView.as_view('bookmark_search_api')
    app.add_url_rule('/api/bookmarks/search', view_func=bookmark_search_api_view, methods=['GET', 'DELETE'])
    bookmarklet_view = BookmarkletView.as_view('bookmarklet')
    app.add_url_rule('/bookmarklet', view_func=bookmarklet_view, methods=['GET'])
    #  non api
    admin.add_view(views.BookmarkModelView(
        bukudb, 'Bookmarks', page_size=per_page, url_render_mode=url_render_mode))
    admin.add_view(views.TagModelView(
        bukudb, 'Tags', page_size=per_page))
    admin.add_view(views.StatisticView(
        bukudb, 'Statistic', endpoint='statistic'))
    return app
コード例 #9
0
def create_app(test_cfg=None):
    app = FlaskAPI(__name__, instance_relative_config=True)
    app.config.from_mapping(
        SECRET_KEY=os.urandom(16),
        DATABASE=os.path.join(app.instance_path, 'sccontroller.sqlite'),
        JWT_EXPIRATION_DELTA=timedelta(hours=1)
    )

    if test_cfg is None:
        app.config.from_pyfile('config.py')
    else:
        app.config.from_mapping(test_cfg)

    if not 'NODE' in app.config:
        print('Specify eth node address in instance/config.py')
        exit(-1)
    if not 'DEFAULT_ACCOUNT' in app.config:
        print ('Specify default eth account in instance/config.py')
        exit(-1)

    try:
        if not 'v0.6.2' in  get_installed_solc_versions():
            install_solc('v0.6.2')
            set_solc_version('v0.6.2')
    except Exception as e:
        print('Unable to install solc v0.6.2: ' + str(e))
        exit(-1)

    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    def authenticate(username, password):
        user = auth.get_user(username)
        if user and check_password_hash(user.password, password):
            return user

    def identity(payload):
        user_id = payload['identity']
        return auth.get_user_by_id(user_id)


    jwt = JWT(app, authenticate, identity)

    @app.errorhandler(400)
    def custom400(error):
        response = Response(
            response=json.dumps({'error': error.description['message']}),
            status=400, mimetype='application/json')
        return response

    @app.errorhandler(503)
    def custom503(error):
        response = Response(
            response=json.dumps({'error': error.description['message']}),
            status=503, mimetype='application/json')
        return response

    @app.route('/templates')
    @jwt_required()
    def templates():
        """Return templates"""

        try:
            templates = Template.all()

            return [{
                'id': it.id,
                'name': it.name,
                'description': it.description,
                'parameters_list': [param for param in it.parameters_list if param['name'] != "refund"]
            } for it in templates], status.HTTP_200_OK
        except KeyError as e:
            abort(status.HTTP_400_BAD_REQUEST, {'message': str(e)})

    @app.route('/templates/<int:id>')
    @jwt_required()
    def template(id):
        """Return template info by id

        Keyword arguments:
        id -- id of the template
        """

        try:
            template = Template.by_id(id)

            return {
                'id': template.id,
                'name': template.name,
                'description': template.description,
                'parameters_list': [param for param in template.parameters_list if param['name'] != "refund"]
            }, status.HTTP_200_OK
        except KeyError as e:
            abort(status.HTTP_400_BAD_REQUEST, {'message': str(e)})

    @app.route('/create-cotract', methods=['POST'])
    @jwt_required()
    def create_contract():
        """Create and deploy contract from template with params

        Data arguments:
        template_id -- id of the template
        parameters -- params dict key=value (keys as keys from templates parameters_list)
        """

        try:
            data = request.get_json(True)
            if not 'template_id' in data or not 'parameters' in data:
                abort(status.HTTP_400_BAD_REQUEST, {'message': "invalid parameters for request"})
            scc = SCContoller.get_scc()

            contract = scc.generate(data['template_id'], data['parameters'], current_identity)
            if scc.w3.eth.getBalance(scc.w3.eth.defaultAccount) < scc.deploy_gas_cost(contract):
                abort(status.HTTP_503_SERVICE_UNAVAILABLE, {'message': 'Not enough gas in system to deploy'})
            scc.deploy(contract)

            return {"id": contract.id}, status.HTTP_200_OK
        except KeyError as e:
            abort(status.HTTP_400_BAD_REQUEST, {'message': str(e)})
        except ValueError as e:
            abort(status.HTTP_400_BAD_REQUEST, {'message': str(e)})

    @app.route('/contracts')
    @jwt_required()
    def get_contracts():
        """Return contracts info"""

        try:
            contracts = Contract.all(current_identity)

            return [{
                'id': contract.id,
                'template_id': contract.template.id,
                'address': contract.address,
                'status': contract.get_status(),
                'creator_guide': contract.template.creator_guide,
                'users_guide': contract.template.users_guide,
            } for contract in contracts], status.HTTP_200_OK
        except KeyError as e:
            abort(status.HTTP_400_BAD_REQUEST, {'message': str(e)})

    @app.route('/contracts', methods=['POST'])
    @jwt_required()
    def get_contracts_by_id():
        """Return contracts info by ids

        Keyword arguments:
        ids -- array of ids of the contracts
        """

        try:
            data = request.get_json(True)
            if not 'ids' in data:
                abort(status.HTTP_400_BAD_REQUEST, {'message': "invalid parameters for request"})
            contracts = [Contract.by_id(id, current_identity) for id in data['ids']]

            return [{
                'id': contract.id,
                'template_id': contract.template.id,
                'address': contract.address,
                'status': contract.get_status(),
                'creator_guide': contract.template.creator_guide,
                'users_guide': contract.template.users_guide,
            } for contract in contracts], status.HTTP_200_OK
        except KeyError as e:
            abort(status.HTTP_400_BAD_REQUEST, {'message': str(e)})

    @app.route('/contracts/<int:id>')
    @jwt_required()
    def get_contract(id):
        """Return contract info by id

       Keyword arguments:
       id -- id of the contract
       """

        try:
            contract = Contract.by_id(id, current_identity)

            return {
                'id': contract.id,
                'template_id': contract.template.id,
                'address': contract.address,
                'status': contract.get_status(),
                'creator_guide': contract.template.creator_guide,
                'users_guide': contract.template.users_guide,
            }, status.HTTP_200_OK
        except KeyError as e:
            abort(status.HTTP_400_BAD_REQUEST, {'message': str(e)})

    @app.route('/contracts/<int:id>/destroy')
    @jwt_required()
    def destroy_contract(id):
        """Destroy the contract by id and return success of the destruction

        Keyword arguments:
        id -- id of the contract
        """
        try:
            SCContoller.get_scc().destruct(Contract.by_id(id, current_identity))

            return '', status.HTTP_204_NO_CONTENT
        except KeyError as e:
            abort(status.HTTP_400_BAD_REQUEST, {'message': str(e)})

    from . import db, auth, template_controller
    db.init_app(app)
    auth.init_app(app)
    template_controller.init_app(app)

    def handle_event(event):
        status = event['args']['cur_status']
        address = event['address']
        try:
            contract = Contract.by_address(address)
            contract.set_status(status)
        except (KeyError, ReferenceError):
            pass

    def log_loop(event_filters, poll_interval):
        with app.app_context():
            while True:
                for event_filter in event_filters:
                    for event in event_filter.get_new_entries():
                        handle_event(event)
                time.sleep(poll_interval)

    with app.app_context():
        try:
            scc = SCContoller.get_scc()
            event_filters = [scc.event_filter(template) for template in Template.all()]
            worker = Thread(target=log_loop, args=(event_filters, 5), daemon=True)
            worker.start()
        except sqlite3.DatabaseError:
            db.init_db()
            scc = SCContoller.get_scc()
            event_filters = [scc.event_filter(template) for template in Template.all()]
            worker = Thread(target=log_loop, args=(event_filters, 5), daemon=True)
            worker.start()
        except ConnectionError as e:
            print(str(e))
            exit(-1)
        except ValueError as e:
            print(str(e))
            exit(-1)

    return app
コード例 #10
0
ファイル: routes.py プロジェクト: Kalela/BrightEvents
def create_app(config_name):
    """Create the api flask app"""
    from webapi.models import User, Event, Rsvp

    api = Blueprint('api', __name__)
    app = FlaskAPI(__name__, instance_relative_config=True)
    CORS(app)
    Swagger(app, template_file="docs.yml")

    app.config.from_pyfile('config.py')
    app.config.from_object(app_config[config_name])
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
    mail = Mail(app)
    db.init_app(app)

    s = URLSafeTimedSerializer(app.config['SECRET_KEY'])
    with app.app_context():
        db.create_all()

    @app.errorhandler(404)
    def not_found_error(error):
        """404 error handler."""
        return jsonify({
            "error":
            "Page not found. Make sure you typed in the route correctly."
        }), 404

    @app.errorhandler(500)
    def internal_server_error(error):
        """500 error handler."""
        return jsonify({"error": "Internal Server Error"}), 500

    @app.route('/', methods=['GET'])
    def index():
        """Render docs"""
        return redirect("/apidocs")

    def token_required(f):
        """Accept function with token"""
        @wraps(f)
        def decorated(*args, **kwargs):
            """Check if token is genuine"""
            token = None

            if 'x-access-token' in request.headers:
                token = request.headers['x-access-token']

            if not token:
                return jsonify({"message": "Token is missing!"}), 401
            try:
                data = jwt.decode(token, app.config['SECRET_KEY'])
                current_user = User.query.filter_by(
                    public_id=data['public_id']).first()
            except:
                return jsonify({"message": "Token is invalid"}), 401
            return f(current_user, *args, **kwargs)

        return decorated

    @api.route('/auth/register', methods=['POST'])
    def register():
        """Add new users to data"""
        result = register_helper(User)
        return jsonify(result[0]), result[1]

    @api.route('/auth/login', methods=['POST'])
    def login():
        """Login registered users"""
        result = login_helper(User, app, db)
        return jsonify(result[0]), result[1]

    @api.route('/auth/logout', methods=['POST'])
    @token_required
    def logout(current_user):
        """Log out users"""
        result = logout_helper(current_user, db)
        return jsonify(result[0]), result[1]

    # @api.route('/auth/reset-password', methods=['POST'])
    # def reset_password():
    #     """Reset users password"""
    #     result = reset_password_helper(current_user, db)
    #     return result[0], result[1]

    @api.route('/search', methods=['GET'])
    def search():
        """Implement search"""
        result = search_helper(Event)
        return jsonify(result[0]), result[1]

    @api.route('/emails', methods=['GET', 'POST'])
    def handle_emails():
        """Handle functionality around email sending"""
        email = request.data['email'].strip()
        user = User.query.filter_by(email=email).first()
        option = \
            request.data['option'].strip() # have a <select> in the frontend
        token = s.dumps(email, salt='email-confirm')

        msg = Message('Reset password',
                      sender=app.config['ADMINS'][0],
                      recipients=[email])
        link = 'http://*****:*****@api.route('/confirm_email/<option>/<token>', methods=['POST'])
    def confirm_email(option, token):
        try:
            email = s.loads(token, salt='email-confirm', max_age=3600)
            if option == "reset-password":
                result = reset_password_helper(email, User, db)
                return jsonify(result[0]), result[1]
            elif option == "confirm-account":
                return jsonify(confirm_account_helper(
                    email, db)[0]), confirm_account_helper(email, db)[1]
        except SignatureExpired:
            return jsonify({"message": "The token is expired!"}), 409

    @api.route('/events', methods=['GET'])
    def view_events():
        """View a list of events"""
        result = get_events_helper(Event)
        return jsonify(result[0]), result[1]

    @api.route('/events/<username>/<eventname>', methods=['GET'])
    def get_single_event(username, eventname):
        result = get_single_event_helper(username, eventname, Event)
        return jsonify(result[0]), result[1]

    @api.route('/events', methods=['POST'])
    @token_required
    def create_event(current_user):
        """Add events"""
        result = create_events_helper(current_user, Event)
        return jsonify(result[0]), result[1]

    @api.route('/events/<user_public_id>', methods=['GET'])
    @token_required
    def online_user_events(current_user, user_public_id):
        """Online users can view their events"""
        result = online_user_events_helper(current_user, user_public_id, Event)
        return jsonify(result[0]), result[1]

    @api.route('/events/<eventname>', methods=['PUT', 'DELETE', 'GET'])
    @token_required
    def event_update(current_user, eventname):
        """Edit existing events"""
        result = event_update_delete_helper(current_user, eventname, db, Event)
        return jsonify(result[0]), result[1]

    @api.route('/events/<eventname>/rsvp', methods=['POST', 'GET', 'DELETE'])
    @token_required
    def rsvps(current_user, eventname):
        """Send RSVPs to existing events"""
        result = rsvps_helper(current_user, eventname, Rsvp, Event)
        return jsonify(result[0]), result[1]

    app.register_blueprint(api, url_prefix='/api/v2')
    return app
コード例 #11
0
def create_app(config_name):
    from models import db, User, Tost, Propagation

    app = FlaskAPI(__name__)
    app.config.from_object(app_config[config_name])

    db.init_app(app)
    with app.app_context():
        db.create_all()
        db.session.commit()

    auth = HTTPBasicAuth()

    @app.route("/signup", methods=["POST"])
    def signup():
        encoding = get_header_encoding(request)
        email = str(request.data.get("email", ""))
        signup_token = str(request.data.get("signup_token", ""))
        user = User.query.filter_by(_user_email=email).first()

        if user:
            response = compose_response(
                {
                    "code": 10,
                    "msg": "already signed up with that email"
                },
                encoding=encoding)
            response.status_code = 400
            return response

        user = User(email=email, signup_token=signup_token)
        user.save()
        response = compose_response(
            {
                "user": {
                    "id": str(user._user_auth_token),
                    "email": str(user._user_email)
                }
            },
            encoding=encoding)
        response.status_code = 200
        return response

    @app.route("/login", methods=["POST"])
    def login():
        encoding = get_header_encoding(request)
        auth_token = str(request.data.get("auth_token", ""))
        user = User.query.filter_by(_user_auth_token=auth_token).first()

        if not (user and user._user_auth_token == auth_token):
            response = compose_response({
                "code": 20,
                "msg": "invalid token"
            },
                                        encoding=encoding)
            response.status_code = 400
            return response

        response = compose_response(
            {
                "user": {
                    "id": str(user._user_auth_token),
                    "email": str(user._user_email)
                }
            },
            encoding=encoding)
        response.status_code = 200
        return response

    def filter_ppgn_by_user_id(user_id):
        return Propagation.query.filter_by(ppgn_user_id=user_id)\
                                .filter_by(_ppgn_disabled=False)\
                                .filter_by(_ppgn_ancestor_disabled=False)\
                                .all()

    def create_tost_summary(ppgn_token, tost, body, encoding=None):
        return compose_response(
            {
                "tost": {
                    "access-token": str(ppgn_token),
                    "creator-id": str(tost.tost_creator_user_id),
                    "created-at": str(tost.tost_create_timestamp),
                    "updator-id": str(tost._tost_updator_user_id),
                    "updated-at": str(tost._tost_update_timestamp),
                    "body": str(body)
                }
            },
            encoding=encoding)

    @app.route("/tost", methods=["GET", "POST"])
    @auth.login_required
    def tost():
        encoding = get_header_encoding(request)
        email, auth_token = get_header_auth(request)
        user = User.query.filter_by(_user_auth_token=auth_token).first()

        if request.method == "GET":
            ppgns = filter_ppgn_by_user_id(user.user_id)

            result = {}
            for ppgn in ppgns:
                tost = Tost.query.filter_by(tost_id=ppgn.ppgn_tost_id).first()
                result[str(ppgn._ppgn_token)] = str(tost._tost_body[:32])

            response = compose_response(result, encoding=encoding)
            response.status_code = 200
            return response

        elif request.method == "POST":
            body = str(request.data.get("body", ""))
            creation_token = str(request.data.get("creation_token", ""))

            if not body:
                response = compose_response(
                    {
                        "code": 30,
                        "msg": "invalid",
                        "field": {
                            "tost": {
                                "body": "must not be blank"
                            }
                        }
                    },
                    encoding=encoding)
                response.status_code = 400
                return response

            tost = Tost(body, user.user_id, creation_token)
            tost.save()

            ppgn = Propagation(tost.tost_id, user.user_id)
            ppgn.save()

            response = create_tost_summary(ppgn._ppgn_token, tost, body,
                                           encoding)
            response.status_code = 200
            return response

    def get_tost_by_token(ppgn_token):
        ppgn = Propagation.query.filter_by(_ppgn_token=ppgn_token).first()
        return Tost.query.filter_by(tost_id=ppgn.ppgn_tost_id).first()

    def get_ppgn_by_token(ppgn_token):
        return Propagation.query.filter_by(_ppgn_token=ppgn_token)\
                                .filter_by(_ppgn_disabled=False)\
                                .filter_by(_ppgn_ancestor_disabled=False)\
                                .first()

    def get_ppgn_by_user_tost(user_id, tost_id):
        return Propagation.query.filter_by(ppgn_user_id=user_id)\
                                .filter_by(ppgn_tost_id=tost_id)\
                                .filter_by(_ppgn_disabled=False)\
                                .filter_by(_ppgn_ancestor_disabled=False)\
                                .first()

    def review_access_token(access_token, user_id):
        ppgn = get_ppgn_by_token(access_token)

        # case 1: propagation invalid
        if not ppgn:
            return 1, None

        user_ppgn = get_ppgn_by_user_tost(user_id, ppgn.ppgn_tost_id)

        # case 2: user visits resource for the first time
        if not user_ppgn:
            new_ppgn = Propagation(ppgn.ppgn_tost_id, user_id, ppgn.ppgn_id,
                                   ppgn._ppgn_rank + 1)
            new_ppgn.save()

            return 2, new_ppgn._ppgn_token

        # case 3: user is creator of tost that propagation points to
        if ppgn.ppgn_id == user_ppgn.ppgn_id:
            return 3, access_token

        # case 4: user propagation is of lower priority than propagation in URL
        if user_ppgn._ppgn_rank > ppgn._ppgn_rank + 1:
            user_ppgn._ppgn_parent_id = ppgn.ppgn_id
            user_ppgn._ppgn_rank = ppgn._ppgn_rank + 1
            user_ppgn.save()

            return 4, user_ppgn._ppgn_token

        # case 5: user propagation is of higher priority than propagation in URL
        if user_ppgn._ppgn_rank <= ppgn._ppgn_rank + 1:
            return 5, user_ppgn._ppgn_token

    @app.route("/tost/<access_token>", methods=["GET", "PUT"])
    @auth.login_required
    def view_tost(access_token):
        encoding = get_header_encoding(request)
        email, auth_token = get_header_auth(request)
        user = User.query.filter_by(_user_auth_token=auth_token).first()
        case, ppgn_token = review_access_token(access_token, user.user_id)

        if request.method == "GET":
            # case 1: propagation invalid
            if case == 1:
                response = compose_response(
                    {
                        "code": 40,
                        "msg": "tost not found"
                    }, encoding=encoding)
                response.status_code = 404
                return response

            # case 2: user visits resource for the first time
            # case 4: user propagation is of lower priority than propagation in URL
            # case 5: user propagation is of higher priority than propagation in URL
            if case in [2, 4, 5]:
                return redirect(url_for("view_tost", access_token=ppgn_token))

            # case 3: user is creator of tost that propagation points to
            tost = get_tost_by_token(ppgn_token)

            response = create_tost_summary(ppgn_token, tost, tost._tost_body,
                                           encoding)
            response.status_code = 200
            return response

        if request.method == "PUT":
            # case 1: propagation invalid
            if case == 1:
                response = compose_response(
                    {
                        "code": 40,
                        "msg": "tost not found"
                    }, encoding=encoding)
                response.status_code = 404
                return response

            # case 2: user visits resource for the first time
            # case 4: user propagation is of lower priority than propagation in URL
            # case 5: user propagation is of higher priority than propagation in URL
            if case in [2, 4, 5]:
                response = compose_response(
                    {
                        "code": 50,
                        "msg": "please use refreshed access token",
                        "access-token": str(ppgn_token)
                    },
                    encoding=encoding)
                response.status_code = 302
                return response

            # case 3: user is creator of tost that propagation points to
            tost = get_tost_by_token(ppgn_token)
            tost._tost_body = str(request.data.get("body", ""))
            tost._tost_updator_user_id = user.user_id
            tost._tost_update_timestamp = db.func.current_timestamp()
            tost.save()

            response = create_tost_summary(ppgn_token, tost, tost._tost_body,
                                           encoding)
            response.status_code = 200
            return response
コード例 #12
0
def create_app(config_name):
    app = FlaskAPI(__name__, instance_relative_config=True)
    app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)

    from app.models import Portfolio, Trades
    with app.app_context():
        db.create_all()

    @app.route('/')
    def main():
        return "Hello World\n Following are the list of routes for this API:\n1. '/trade'\n2. '/trade/[id]/delete'\n3. '/portfolio'\n4. '/returns'"

    @app.route('/trade', methods=['GET', 'PUT', 'POST'])
    def trading():
        if request.method == 'GET':
            if request.args.get('ticker') != None:
                tradelist = Trades.fetch_all()
                results = []

                for trade in tradelist:
                    if(trade.ticker_symbol == request.args.get('ticker')):
                        obj = {
                            'id': trade.id,
                            'ticker_symbol': trade.ticker_symbol,
                            'price': trade.price,
                            'shares': trade.shares,
                            'type': trade.type
                        }
                        results.append(obj)
                response = jsonify(results)
                response.status_code = 200
                return response
            else:
                tradelist = Trades.fetch_all()
                results = []

                for trade in tradelist:
                    obj = {
                        'id': trade.id,
                        'ticker_symbol': trade.ticker_symbol,
                        'price': trade.price,
                        'shares': trade.shares,
                        'type': trade.type
                    }
                    results.append(obj)
                response = jsonify(results)
                response.status_code = 200
                return response
        elif request.method == 'PUT':
            id = str(request.data.get('id', ''))
            if not id:
                response = jsonify({'ERROR': 'ID field is required'})
                response.status_code = 400
                return response
            tradelist = Trades.query.filter_by(id=id).first()
            flag=0
            if not tradelist:
                flag=1

            if request.data.get('price') <= 0: 
                response = jsonify({'ERROR': 'Zero or Negative price not valid'})
                response.status_code = 400
                return response
            if request.data.get('shares') <=0:
                response = jsonify({'ERROR': 'Zero or Negative shares not valid'})
                response.status_code = 400
                return response
            if request.data.get('type') == 'SELL':
                check_portfolio = Portfolio.query.filter_by(
                    ticker_symbol=request.data.get('ticker_symbol')).first()
                if not check_portfolio or (check_portfolio.shares < request.data.get('shares')):
                    response = jsonify(
                        {'ERROR': 'Cannot sell when low/no shares available'})
                    response.status_code = 400
                    return response
            prev_shares = tradelist.shares
            if flag==1:
                tradelist=Trades(id,str(request.data.get('ticker_symbol')),request.data.get('price'), request.data.get('shares')
                ,str(request.data.get('type')))
            else :
                tradelist.id = id
                tradelist.ticker_symbol = str(request.data.get('ticker_symbol'))
                tradelist.price = request.data.get('price')
                tradelist.shares = request.data.get('shares')
                tradelist.type = str(request.data.get('type'))

            if Portfolio.query.filter_by(ticker_symbol=request.data.get('ticker_symbol', '')).first():
                if tradelist.type == 'BUY':
                    current_portfolio = Portfolio.query.filter_by(
                        ticker_symbol=request.data.get('ticker_symbol', '')).first()
                    total = current_portfolio.shares * current_portfolio.avg_buy_price
                    total = total + (tradelist.price * tradelist.shares)
                    total = total / (tradelist.shares +
                                     current_portfolio.shares)
                    current_portfolio.avg_buy_price = total
                    current_portfolio.shares = tradelist.shares-prev_shares + current_portfolio.shares
                    
                else:
                    current_portfolio = Portfolio.query.filter_by(
                        ticker_symbol=request.data.get('ticker_symbol', '')).first()
                    current_portfolio.shares = current_portfolio.shares - tradelist.shares + prev_shares

                current_portfolio.add_trade()
            else:
                portfolio = Portfolio(
                    tradelist.ticker_symbol, tradelist.price, tradelist.shares)
                portfolio.add_trade()

            tradelist.add_trade()
            if flag==1:
                response = jsonify({
                    'NOTE' : 'The Id provided does not exist so creating a new record as below',
                    'id': tradelist.id,
                    'ticker_symbol': tradelist.ticker_symbol,
                    'price': tradelist.price,
                    'shares': tradelist.shares,
                    'type': tradelist.type
                })
            else :
                response = jsonify({
                    'id': tradelist.id,
                    'ticker_symbol': tradelist.ticker_symbol,
                    'price': tradelist.price,
                    'shares': tradelist.shares,
                    'type': tradelist.type
                })
            response.status_code = 202
            return response
        elif request.method == 'POST':
            if request.data.get('id'):
                if Trades.query.filter_by(id=request.data.get('id', '')).first() and Trades.query.filter_by(ticker_symbol=request.data.get('ticker_symbol')).first():
                    response = jsonify({'ERROR': 'Record already exists'})
                    response.status_code = 200
                    return response
            if request.data.get('price') <= 0: 
                response = jsonify({'ERROR': 'Zero or Negative price not valid'})
                response.status_code = 400
                return response
            if request.data.get('shares') <=0:
                response = jsonify({'ERROR': 'Zero or Negative shares not valid'})
                response.status_code = 400
                return response
            if request.data.get('type') == 'SELL':
                check_portfolio = Portfolio.query.filter_by(
                    ticker_symbol=request.data.get('ticker_symbol')).first()
                if not check_portfolio or (check_portfolio.shares < request.data.get('shares')):
                    response = jsonify(
                        {'ERROR': 'Cannot sell when low/no shares available'})
                    response.status_code = 400
                    return response
            if request.data.get('id'):
                tradelist = Trades(request.data.get('id'), str(request.data.get('ticker_symbol')), request.data.get(
                    'price'), request.data.get('shares'), str(request.data.get('type')))
            else:
                tradelist = Trades(-1,str(request.data.get('ticker_symbol')), request.data.get(
                    'price'), request.data.get('shares'), str(request.data.get('type')))

            if Portfolio.query.filter_by(ticker_symbol=request.data.get('ticker_symbol')).first():
                if tradelist.type == 'BUY':
                    current_portfolio = Portfolio.query.filter_by(
                        ticker_symbol=request.data.get('ticker_symbol', '')).first()
                    total = current_portfolio.shares * current_portfolio.avg_buy_price
                    total = total + (tradelist.price * tradelist.shares)
                    total = total / (tradelist.shares +
                                     current_portfolio.shares)
                    current_portfolio.avg_buy_price = total
                    current_portfolio.shares = tradelist.shares + current_portfolio.shares
                else:
                    current_portfolio = Portfolio.query.filter_by(
                        ticker_symbol=request.data.get('ticker_symbol', '')).first()
                    current_portfolio.shares = current_portfolio.shares - tradelist.shares
                current_portfolio.add_trade()
            else:
                portfolio = Portfolio(
                    tradelist.ticker_symbol, tradelist.price, tradelist.shares)
                portfolio.add_trade()
            tradelist.add_trade()
            response = jsonify({
                'id': tradelist.id,
                'ticker_symbol': tradelist.ticker_symbol,
                'price': tradelist.price,
                'shares': tradelist.shares,
                'type': tradelist.type
            })
            response.status_code = 201

            return response
        else:
            response = jsonify({'ERROR': 'Illegal Operation'})
            response.status_code = 400
            return response

    @app.route('/trade/<int:id>/delete', methods=['DELETE'])
    def delete_trade(id):
        if request.method == 'DELETE':
            del_trade = Trades.query.filter_by(id=id).first()
            if del_trade:
                curr_portfolio = Portfolio.query.filter_by(
                    ticker_symbol=del_trade.ticker_symbol).first()
                if del_trade.type == 'BUY':
                    del_share = del_trade.shares
                    del_price = del_trade.price
                    curr_avg_price = curr_portfolio.avg_buy_price
                    curr_shares = curr_portfolio.shares
                    new_avg_price = ((curr_avg_price*curr_shares) -
                                     (del_price*del_share))/(curr_shares-del_share)
                    curr_portfolio.avg_buy_price = new_avg_price
                    curr_portfolio.shares = curr_shares-del_share
                    curr_portfolio.add_trade()
                    del_trade.delete()
                    response = jsonify({
                        'ticker_symbol': curr_portfolio.ticker_symbol,
                        'avg_buy_price': curr_portfolio.avg_buy_price,
                        'shares': curr_portfolio.shares
                    })
                    response.status_code = 201
                    return response
                else:
                    curr_portfolio.shares = curr_portfolio.shares-del_trade.shares
                    curr_portfolio.add_trade()
                    del_trade.delete()
                    response = jsonify({
                        'ticker_symbol': curr_portfolio.ticker_symbol,
                        'avg_buy_price': curr_portfolio.avg_buy_price,
                        'shares': curr_portfolio.shares
                    })
                    response.status_code = 201
                    return response
            else:
                response = jsonify({'ERROR': 'No record found for this id'})
                response.status_code = 404
                return response
        else:
            response = jsonify({'ERROR': 'Illegal Operation'})
            response.status_code = 400
            return response

    @app.route('/portfolio', methods=['GET'])
    def return_portfolio():
        if request.method == 'GET':
            portfolio_list = Portfolio.fetch_all()
            results = []
            for portfolio in portfolio_list:
                obj = {
                    'ticker_symbol': portfolio.ticker_symbol,
                    'avg_buy_price': portfolio.avg_buy_price,
                    'shares': portfolio.shares
                }
                results.append(obj)
            response = jsonify(results)
            response.status_code = 200
            return response

    @app.route('/returns', methods=['GET'])
    def fetch_returns():
        if request.method == 'GET':
            portfolio_list = Portfolio.fetch_all()
            sum = 0
            for portfolio in portfolio_list:
                sum = sum + ((100-portfolio.avg_buy_price)*portfolio.shares)
            response = jsonify({'Cumulative Returns': sum})
            response.status_code = 200
            return response
    return app
コード例 #13
0
def create_app(config_name):
    from app.models.category import Category
    from app.models.recipe import Recipe
    app = FlaskAPI(__name__, instance_relative_config=True)
    app.config.from_object(app_config['development']
                           )  # app.config.from_object(app_config[config_name])
    app.config.from_pyfile('config.py')
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    db.init_app(app)
    with app.app_context():
        db.create_all()

    @app.route('/categories', methods=['POST', 'GET'])
    def categories():
        if request.method == "POST":
            category_name = str(request.data.get('category_name', ''))
            if category_name:
                category = Category(category_name=category_name)
                category.save()
                response = jsonify({
                    'category_id':
                    category.category_id,
                    'category_name':
                    category.category_name,
                    'date_created':
                    category.date_created,
                    'date_modified':
                    category.date_modified,
                    'recipes':
                    url_for('recipes',
                            category_id=category.category_id,
                            _external=True)
                })
                response.status_code = 201
                return response
        else:
            # GET
            categories = Category.get_all()
            results = []

            for category in categories:
                obj = {
                    'category_id':
                    category.category_id,
                    'category_name':
                    category.category_name,
                    'date_created':
                    category.date_created,
                    'date_modified':
                    category.date_modified,
                    'recipes':
                    url_for('recipes',
                            category_id=category.category_id,
                            _external=True)
                }
                results.append(obj)
            response = jsonify(results)
            response.status_code = 200
            return response

    @app.route('/categories/<int:category_id>',
               methods=['GET', 'PUT', 'DELETE'])
    def category_edit_and_delete(category_id, **kwargs):
        category = Category.query.filter_by(category_id=category_id).first()
        if not category:
            # Raise an HTTPException with a 404 not found status code
            return {
                "message": "Url doesn't exist. Please type existing url"
            }, 404

        if request.method == 'DELETE':
            category.delete()
            return {
                "message":
                "category {} deleted successfully".format(category.category_id)
            }, 200

        elif request.method == 'PUT':
            category_name = str(request.data.get('category_name', ''))
            category.category_name = category_name
            category.save()
            response = jsonify({
                'category_id':
                category.category_id,
                'category_name':
                category.category_name,
                'date_created':
                category.date_created,
                'date_modified':
                category.date_modified,
                'recipes':
                url_for('recipes',
                        category_id=category.category_id,
                        _external=True)
            })
            response.status_code = 200
            return response
        else:
            # GET
            response = jsonify({
                'category_id':
                category.category_id,
                'category_name':
                category.category_name,
                'date_created':
                category.date_created,
                'date_modified':
                category.date_modified,
                'recipes':
                url_for('recipes',
                        category_id=category.category_id,
                        _external=True)
            })
            response.status_code = 200
            return response

    @app.route('/categories/<int:category_id>/recipes',
               methods=['POST', 'GET'])
    def recipes(category_id, **kwargs):
        if request.method == "POST":
            recipe_name = str(request.data.get('recipe_name', ''))
            ingredients = str(request.data.get('ingredients', ''))
            directions = str(request.data.get('directions', ''))

            if recipe_name:
                recipe = Recipe(recipe_name=recipe_name)
                recipe.save()
                response = jsonify({
                    'recipe_id': recipe.recipe_id,
                    'recipe_name': recipe.recipe_name,
                    'ingredients': recipe.ingredients,
                    'directions': recipe.directions,
                    'date_created': recipe.date_created,
                    'date_modified': recipe.date_modified
                })
                response.status_code = 201
                return response
        else:
            # GET
            recipes = Recipe.query.filter_by(category_id=category_id).all()
            results = []

            for recipe in recipes:
                obj = {
                    'recipe_id': recipe.recipe_id,
                    'recipe_name': recipe.recipe_name,
                    'ingredients': recipe.ingredients,
                    'directions': recipe.directions,
                    'date_created': recipe.date_created,
                    'date_modified': recipe.date_modified
                }
                results.append(obj)
            response = jsonify(results)
            response.status_code = 200
            return response

    @app.route('/categories/<int:category_id>/recipes/<int:recipe_id>',
               methods=['GET', 'PUT', 'DELETE'])
    def recipe_edit_and_delete(category_id, recipe_id, **kwargs):
        recipe = Recipe.query.filter_by(recipe_id=recipe_id).first()
        if not recipe:
            # Raise an HTTPException with a 404 not found status code
            return {
                "message": "Url doesn't exist. Please type existing url"
            }, 404

        if request.method == 'DELETE':
            recipe.delete()
            return {
                "message":
                "recipe {} deleted successfully".format(recipe.recipe_id)
            }, 200

        elif request.method == 'PUT':
            recipe_name = str(request.data.get('recipe_name', ''))
            ingredients = str(request.data.get('ingredients', ''))
            directions = str(request.data.get('directions', ''))

            recipe.recipe_name = recipe_name
            recipe.ingredients = ingredients
            recipe.directions = directions

            recipe.save()
            response = jsonify({
                'recipe_id': recipe.recipe_id,
                'recipe_name': recipe.recipe_name,
                'ingredients': recipe.ingredients,
                'directions': recipe.directions,
                'date_created': recipe.date_created,
                'date_modified': recipe.date_modified
            })
            response.status_code = 200
            return response
        else:
            # GET
            response = jsonify({
                'recipe_id': recipe.recipe_id,
                'recipe_name': recipe.recipe_name,
                'ingredients': recipe.ingredients,
                'directions': recipe.directions,
                'date_created': recipe.date_created,
                'date_modified': recipe.date_modified
            })
            response.status_code = 200
            return response

    return app
コード例 #14
0
ファイル: index.py プロジェクト: klemmari1/ilmoitushaukka
from flask import redirect, render_template, request, session, url_for
from flask_api import FlaskAPI

import settings
from mail_service import subscribe_email, unsubscribe_email
from models.db import db
from post_service import delete_old_posts, drop_post_table, fetch_posts, get_posts

app = FlaskAPI(__name__)
app.secret_key = settings.SECRET_KEY

# DB Setup
conn_str = os.getenv("DATABASE_URL", "sqlite:///app.db")
app.config["SQLALCHEMY_DATABASE_URI"] = conn_str
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.app_context().push()

db.init_app(app)
db.create_all()


@app.route("/", methods=["GET"])
def home():
    unsubscribe = request.args.get("unsubscribe")
    if unsubscribe:
        is_unsubscribed = unsubscribe_email(unsubscribe)
        if is_unsubscribed:
            session["success"] = "Email unsubscribed from sale alerts!"
        else:
            session["warning"] = "Email is not subscribed to sale alerts!"
    return render_template(
コード例 #15
0
def runsched(model_id_list: List[int], app: FlaskAPI):
    """ Calculate the model score for the date range specified inside the scheduler """
    with app.app_context():
        for model_id in model_id_list:
            _run_sched_for_model_no_set_dates(model_id)