Example #1
0
 def test_router_dispatch_post(db_session):
     """Test that auto router dispatch to post works."""
     router = ModelResourceRouter(session=db_session)
     data = {
         "track_id": "4000",
         "name": "Test Track Seven",
         "media_type": {
             "media_type_id": "2"
         },
         "genre": {
             "genre_id": "10"
         },
         "composer": "Nick Repole",
         "milliseconds": "206009",
         "bytes": "3305166",
         "unit_price": "0.99",
     }
     result = router.dispatcher(method="post", path="/tracks", data=data)
     assert result["track_id"] == 4000
Example #2
0
 def test_router_dispatch_put(db_session):
     """Test that auto router dispatch to put works."""
     router = ModelResourceRouter(session=db_session)
     data = {
         "album": "/tracks/1/album",
         "bytes": 11170334,
         "composer": "Angus Young, Malcolm Young, Brian Johnson",
         "genre": {
             "genre_id": 1
         },
         "media_type": {
             "media_type_id": 1
         },
         "milliseconds": 4000000,
         "name": "For Those About To Rock (We Salute You)",
         "playlists": "/tracks/1/playlists",
         "self": "/tracks/1",
         "track_id": 1,
         "unit_price": 0.99
     }
     result = router.dispatcher(method="put", path="/tracks/1", data=data)
     assert result["milliseconds"] == 4000000
Example #3
0
def api_router(path):
    """Generic API router.

    You'll probably want to be more specific with your routing.

    We're using the ModelResourceRouter, which automatically routes
    based on the class name of each Resource, and handles nested
    routing, querying, and updating automatically.

    """
    # get your SQLAlchemy db session however you normally would
    db_session = get_scoped_db_session("video")
    # This should be some context related to the current request.
    # Note that context can be used by resources/schemas to help
    # handle things like permissions/access, and would typically
    # contain any user related info for this request.
    context = {}
    router = ModelResourceRouter(session=db_session, context=context)
    # query params are used to parse fields to include, embeds,
    # sorts, and filters.
    query_params = request.values.to_dict()
    status = 200
    response_headers = {}
    if request.method.upper() == "POST":
        status = 201
    result = router.dispatcher(request.method,
                               path,
                               query_params=query_params,
                               data=request.json)
    if request.method.upper() == "OPTIONS":
        response_headers["Allow"] = ",".join(result)
        result = None
    if isinstance(result, ResourceCollection):
        # Handle providing prev, next, first, last page links header
        links = []
        if result.current_page is not None:
            link_template = '<{link}>; rel="{rel}"'
            if result.first_page:
                links.append(
                    link_template.format(link=url_for_other_page(
                        result.first_page),
                                         rel="first"))
            if result.previous_page:
                links.append(
                    link_template.format(link=url_for_other_page(
                        result.previous_page),
                                         rel="prev"))
            if result.next_page:
                links.append(
                    link_template.format(link=url_for_other_page(
                        result.next_page),
                                         rel="next"))
            if result.last_page:
                links.append(
                    link_template.format(link=url_for_other_page(
                        result.last_page),
                                         rel="last"))
        links_str = ",".join(links)
        if links_str:
            response_headers["Link"] = links_str
        # Handle successful HEAD requests
        if request.method.upper() == "HEAD":
            result = None
    if result is not None:
        result = json.dumps(result)
    return Response(result,
                    headers=response_headers,
                    mimetype="application/json",
                    status=status)
Example #4
0
File: api.py Project: repole/drowsy
def api_router(path):
    """Generic API router.

    You'll probably want to be more specific with your routing.

    We're using the ModelResourceRouter, which automatically routes
    based on the class name of each Resource, and handles nested
    routing, querying, and updating automatically.

    """
    # This should be some context related to the current request.
    # Note that context can be used by resources/schemas to help
    # handle things like permissions/access, and would typically
    # contain any user related info for this request.
    context = {}
    router = ModelResourceRouter(session=g.db_session, context=context)
    # query params are used to parse fields to include, embeds,
    # sorts, and filters.
    query_params = request.values.to_dict()
    errors = None
    status = 200
    response_headers = {}
    try:
        if request.method.upper() == "POST":
            status = 201
        result = router.dispatcher(
            request.method,
            path,
            query_params=query_params,
            data=request.json)
        if result is None:
            status = 204
        if request.method.upper() == "OPTIONS":
            response_headers["Allow"] = ",".join(result)
            result = None
        if isinstance(result, ResourceCollection):
            # Handle providing prev, next, first, last page links header
            links = []
            if result.current_page is not None:
                link_template = '<{link}>; rel="{rel}"'
                if result.first_page:
                    links.append(link_template.format(
                        link=url_for_other_page(result.first_page),
                        rel="first"))
                if result.previous_page:
                    links.append(link_template.format(
                        link=url_for_other_page(result.previous_page),
                        rel="prev"))
                if result.next_page:
                    links.append(link_template.format(
                        link=url_for_other_page(result.next_page),
                        rel="next"))
                if result.last_page:
                    links.append(link_template.format(
                        link=url_for_other_page(result.last_page),
                        rel="last"))
            links_str = ",".join(links)
            if links_str:
                response_headers["Link"] = links_str
            # Handle successful HEAD requests
            if request.method.upper() == "HEAD":
                result = None
        if result is not None:
            result = json.dumps(result)
        return Response(
            result,
            headers=response_headers,
            mimetype="application/json",
            status=status
        )
    except UnprocessableEntityError as exc:
        status = 433
        errors = exc.errors
        message = exc.message
        code = exc.code
    except MethodNotAllowedError as exc:
        status = 405
        message = exc.message
        code = exc.code
    except BadRequestError as exc:
        status = 400
        message = exc.message
        code = exc.code
    except ResourceNotFoundError as exc:
        status = 404
        message = exc.message
        code = exc.code
    if code is not None or message:
        if request.method.upper() == "HEAD":
            result = None
        else:
            result = {"message": message, "code": code}
            if errors:
                result["errors"] = errors
        return Response(
            json.dumps(result),
            mimetype="application/json",
            status=status)
Example #5
0
 def test_router_dispatch_get(db_session):
     """Test that auto router dispatch to get works."""
     router = ModelResourceRouter(session=db_session)
     result = router.dispatcher(method="get", path="/albums/1")
     assert result["album_id"] == 1
Example #6
0
 def test_router_dispatch_bad_path(db_session):
     """Test that auto router dispatch to a bad path fails."""
     router = ModelResourceRouter(session=db_session)
     with raises(ResourceNotFoundError):
         router.dispatcher(method="get", path="/1")
Example #7
0
 def test_router_dispatch_bad_method(db_session):
     """Test that auto router dispatch to a bad method fails."""
     router = ModelResourceRouter(session=db_session)
     with raises(MethodNotAllowedError):
         router.dispatcher(method="bad", path="/albums/1")
Example #8
0
 def test_router_dispatch_options(db_session):
     """Test that auto router dispatch to options works."""
     router = ModelResourceRouter(session=db_session)
     result = router.dispatcher(method="options", path="/albums/1")
     assert "GET" in result
Example #9
0
 def test_router_dispatch_delete(db_session):
     """Test that auto router dispatch to delete works."""
     router = ModelResourceRouter(session=db_session)
     result = router.dispatcher(method="delete", path="/tracks/1")
     assert result is None
Example #10
0
 def test_router_dispatch_patch(db_session):
     """Test that auto router dispatch to patch works."""
     router = ModelResourceRouter(session=db_session)
     data = {"milliseconds": 4000000}
     result = router.dispatcher(method="patch", path="/tracks/1", data=data)
     assert result["milliseconds"] == 4000000