Beispiel #1
0
def add_resource():
    """Add a new resource."""
    test_jsonapi_header()
    resources = get_resources()
    try:
        data = touni(request.body.read())
        #pprint(data)
        add_request = json.loads(data)
    except (ValueError):
        abort(400, "The expected content should be json, encoded in utf8.")
    if not "data" in add_request:
        abort(422, "The data property must be present.")
    if "errors" in add_request:
        abort(422, "The errors property must not be present.")
    if add_request["data"].get("type") != "resource":
        abort(422, "There must be a \"type\" property set to \"resource\" in the data field.")
    if not isinstance(add_request["data"].get("attributes"), dict):
        abort(422, "There must be a \"attributes\" property set to an object in the data field.")
    resource = add_request["data"]["attributes"]
    try:
        validate_resource(resource)
    except ValidationFailed as error:
        abort(422, str(error))
    _id = add_request["data"].get("id", get_id())
    if not isinstance(_id, STR_TYPE) or not re.match("^([!*\"'(),+a-zA-Z0-9$_@.&+-])+$", _id):
        abort(403, "The id {} is invalid, can not be part of a url.".format(repr(_id)))
    if _id in resources or _id == "ids":
        abort(403, "The id \"{}\" already exists.".format(_id))
    resources[_id] = resource
    response.status = 201
    link = get_location_url(_id)
    response.headers["Location"] = link
    return response_object({"data": {"attributes": resource, "type":"resource", "id": _id},
            "links": {"self":link}})
Beispiel #2
0
 def test_all_invalid_examples_fail(self):
     for i in get_invalid_examples():
         self.assertFalse(is_valid_resource(i))
         self.assertRaises(ValidationFailed, lambda: validate_resource(i))
Beispiel #3
0
 def test_all_valid_examples_succeed(self):
     for v in get_valid_examples():
         self.assertTrue(is_valid_resource(v))
         validate_resource(v)