How can this Django Rest Framework Serializer (used to validate a json) be simplified? - serialization

So I have the following "json":
a = {
"ranks": {
"top_list": [5, 224, 232, 234],
"top_dict": {
"start": 696,
"end": 704
},
"top_id": 8
}
}
and the following serializers (which works):
from rest_framework import serializers
class TopDictSchema(serializers.Serializer):
start = serializers.IntegerField()
end = serializers.IntegerField()
class RanksSchema(serializers.Serializer):
top_list = serializers.ListField()
top_dict = TopDictSchema()
top_id = serializers.IntegerField()
class MySerializer(serializers.Serializer):
ranks = RanksSchema()
Combining them like this:
MySerializer(data=a).is_valid() == True
> True
Can the serializers be simplified?

Related

Looping over map variable using for_each expression in terraform

I have variable that I want to iterate over using for_each in terraform to create multiple instances of submodule - node_groups, which is part of eks module. This is my variable:
variable "frame_platform_eks_node_groups" {
type = map
default = {
eks_kube_system = {
desired_capacity = 1,
max_capacity = 5,
min_capacity = 1,
instance_type = ["m5.large"],
k8s_label = "eks_kube_system",
additional_tags = "eks_kube_system_node"
},
eks_jenkins_build = {
desired_capacity = 1,
max_capacity = 10,
min_capacity = 1,
instance_type = ["m5.large"],
k8s_label = "eks_jenkins_build",
additional_tags = "eks_jenkins_build_node"
}
}
}
And this is my node_groups submodule, which is part of module eks.
module "eks" {
...
node_groups = {
for_each = var.frame_platform_eks_node_groups
each.key = {
desired_capacity = each.value.desired_capacity
max_capacity = each.value.max_capacity
min_capacity = each.value.min_capacity
instance_types = each.value.instance_type
k8s_labels = {
Name = each.value.k8s_label
}
additional_tags = {
ExtraTag = each.value.additional_tags
}
}
When I run terraform plan I am getting following error:
15: each.key = {
If this expression is intended to be a reference, wrap it in parentheses. If
it’s instead intended as a literal name containing periods, wrap it in quotes
to create a string literal.
My intention obviously is to get eks_kube_system and eks_jenkins_build values from the map variable with each.key reference. But something is wrong. Do you have advice what I am doing wrong?
Thank you!
Its not exactly clear what node_groups is as it is not defined in your question, but assuming that it is a list of maps, then the code should be:
module "eks" {
...
node_groups = [
for k,v in var.frame_platform_eks_node_groups:
{
desired_capacity = v.desired_capacity
max_capacity = v.max_capacity
min_capacity = v.min_capacity
instance_types = v.instance_type
k8s_labels = {
Name = v.k8s_label
}
additional_tags = {
ExtraTag = v.additional_tags
}
}
]

read data from Map<String, Object>

I get these type of data from some api. I want to read data from "FK_User" which seems an object, when
I read data like this i get this error:
The method '[]' isn't defined for the class 'Object'.
- 'Object' is from 'dart:core'.
print(a["FK_User"]["username"]);
and the data is like this:
var a = {
"ID": "dummyID",
"FK_User": {
"username": "dummyID",
},
"Somefield": "dymmy",
}
var b = a["FK_User"]["username"];
how can I read this type of data?
Map<String, dynamic> a = {
"ID": "dummyID",
"FK_User": {
"username": "dummyID",
},
"Somefield": "dymmy",
};
var b = a["FK_User"]["username"]; // dummyID
Map<String,dynamic> a_map = Map.castFrom(a);
Map<String,dynamic> fk_user_map = Map.castFrom(a_map["FK_user"]);

How to make post with data class

I have this endpoint with this structure:
uri = http://127.0.0.1:9090/tables/mask
and this payload:
{
"_id" : "5d66c9b6d5ccf30bd5b6b541",
"connectionId" : "1967c072-b5cf-4e9e-1c92-c2b49eb771c4",
"name" : "Customer",
"columns" : [
{
"name" : "FirstName",
"mask" : true
},
{
"name" : "LastName",
"mask" : false
},
{
"name" : "City",
"mask" : false
},
{
"name" : "Phone",
"mask" : false
}
],
"parentId" : null
}
in my Kotlin code I have this structure to deserialize:
data class ColumnsMaskModel (val name:String, val mask:Boolean )
data class TablesMaskModel (val _id:String, val name:String, val connectionId:String, val columns:MutableList<ColumnsMaskModel?> )
and how can I use TablesMaskModel to make a HTTP post in Kotlin
You'll need an HTTP client to do that. Data classes themselves has nothing to do with HTTP, they are just data structures. There are a lot of HTTP clients available on Kotlin for JVM:
java.net.HttpURLConnection
Java 9's HttpClient
Apache HttpComponents
OkHttp
Ktor
Let's see how to make HTTP requests in Ktor:
data class ColumnsMaskModel(val name: String, val mask: Boolean)
data class TablesMaskModel(val _id: String, val name: String, val connectionId: String, val columns: MutableList<ColumnsMaskModel?>)
fun main() = runBlocking {
val client = HttpClient {
install(JsonFeature) {
serializer = JacksonSerializer()
}
}
val result = client.post<String> {
url("http://httpbin.org/post")
contentType(ContentType.Application.Json)
body = TablesMaskModel(
_id = "5d66c9b6d5ccf30bd5b6b541",
connectionId = "1967c072-b5cf-4e9e-1c92-c2b49eb771c4",
name = "Customer",
columns = mutableListOf(
ColumnsMaskModel(name = "FirstName", mask = true),
ColumnsMaskModel(name = "LastName", mask = false),
ColumnsMaskModel(name = "City", mask = false),
ColumnsMaskModel(name = "Phone", mask = false)
)
)
}
println(result)
client.close()
}
Note that Ktor uses suspending functions for HTTP requests, so you'll need a coroutine scope, runBlocking in this example.
Ktor supports various "backends" for HTTP clients – Apache, Coroutines IO, curl. It also has different "features" to enable on-the-flight payloads serializations and de-serializations, like in the example above.

karate: finding index of the particular element value from API response

my code for finding index as below
* def list = nestActual #this is API response value which is given at the end
* def searchFor = { category_name: 'books3'}
* def foundAt = []
* def fun = function(x, i){ if (karate.match(x, searchFor).pass) foundAt.add(i) }
* eval karate.forEach(list, fun)
* print "==========foundAt=======" +foundAt
i have tried the above code for finding index where im getting foundAt index as null.
Below is my response where i want to find index of "category_name":"books3"
[
{
"category_id":1, "parent_cat_id":0, "category_name":"books", "slug_name":"books_1", "popular":true,
}, {
"category_id":2, "parent_cat_id":1, "category_name":"books2", "slug_name":"books_2", "popular":false,
}, {
"category_id":3, "parent_cat_id":1, "category_name":"books3", "slug_name":"books3_2", "popular":false,
}, {
"category_id":4, "parent_cat_id":3, "category_name":"mp3", "slug_name":"mp_3", "popular":false, }, {
"category_id":5, "parent_cat_id":3, "category_name":"mp4", "slug_name":"humoristiska_deckare_mysi_deck_3", "popular":false, }, {
"category_id":6, "parent_cat_id":3, "category_name":"video", "slug_name":"video3", "popular":false,
} ]
Please let me know how to find index of "category_name":"books3" using karate
Guess what, there is a far simpler way, the trick is to convert your search target into an array of primitives. Then you can use the List.indexOf() Java method:
Scenario: using the java indexOf api (will change with graal)
* def response = [{ name: 'a' }, { name: 'b' }, { name: 'c' }]
* def names = $[*].name
* def index = names.indexOf('b')
* match index == 1

Karate API : Converting two arrays into an object

How to merge to below arrays into an object in Karate API. I tried below code it is not working.
keys = ['foo', 'bar', 'qux']
values = ['1', '2', '3']
Feature: ArrayToObject
Scenario: ArrayToObject Coversion JS script
* def keys = ['foo', 'bar', 'qux']
* def values = ['1', '2', '3']
* def Arr2object =
"""
function (keys, vals) {
return keys.reduce(
function(prev, val, i) {
prev[val] = vals[i];
return prev;
}, {}
);
}
"""
* string text = Arr2object(keys, values)
* print text
Expected something like this
{
"foo": "1",
"bar": "2",
"qux": "3"
}
This might work,
* def Arr2object =
"""
function(keys,values){
var newObj = {};
if(keys.length == values.length){
for (var i = 0; i <= keys.length - 1; i++) {
newObj [keys[i]] = values[i];
}
return newObj;
}
return newObj;
}