One many reference flask_restx Dto - flask-restful

I have a problem in Dto. I want have in two model reference between each but I have an error due to declaration order. : NameError: name 'b' is not defined
class AADto:
api = Namespace('aa', description='aa related operations')
a = api.model('a', {
'id': fields.Integer(required=True, description='a id'),
'b': fields.Nested(b),
}),
b = api.model('b', {
'id': fields.Integer(required=True, description='b id'),
'aArray': fields.List(fields.Nested(a)),
}),
Someone have documentation for this case or an answer for how have reference between each ?
Thanks.

So I use Integer for b attribute of a. So attribute b became an b_id.
class AADto:
api = Namespace('aa', description='aa related operations')
a = api.model('a', {
'id': fields.Integer(required=True, description='a id'),
'b_id': fields.Integer(required=False, description='b id'),
}),
b = api.model('b', {
'id': fields.Integer(required=True, description='b id'),
'aArray': fields.List(fields.Nested(a)),
}),

Related

Update or create nested element in dynamoDB

I want to update or create DynamoDB item to get next element:
{
"id": 156,
"date": 12323233.000,
"countries": {
"ua": 1,
"ru": 2}
}
I use python and boto3. So I can check if field countries exist and if not add it. But that will mean 2 DB requests.
table.update_item(
Key={
'id': 156,
'date': date,
},
UpdateExpression='SET countries = if_not_exists(countries, :countries)',
ExpressionAttributeValues={
':countries': {},
},
)
table.update_item(
Key={
'id': 156,
'date': date,
},
UpdateExpression='ADD countries.#country :inc',
ExpressionAttributeNames={"#country": country},
ExpressionAttributeValues={
':inc': 1
},
)
Is there any way to merge this 2 requests in one?
I had to do something like this recently, and took a while to figure out. I've got a count I want to increment if a page doesn't already exist in my set of "done" pages. If not, it increments and adds the page number to the set. Took a while to realize you can 'append' to a list, but have to 'add' to a set.
try:
res = dbt.update_item(
Key={'pk': 'doc3', 'sk': 'na'},
ReturnConsumedCapacity='INDEXES', ReturnValues='ALL_NEW',
ExpressionAttributeNames={
'#count': 'count',
'#done': 'done',
},
ExpressionAttributeValues={
':1': 1,
':page': page,
':pagelist': set([page]),
},
ConditionExpression="(NOT contains(done, :page))",
UpdateExpression="ADD #done :pagelist, #count :1",
)
print(f'rand int page={page} count={res["Attributes"]["count"]}'
f' CU={res["ConsumedCapacity"]["Table"]}')
except ClientError as err:
if err.response['Error']['Code'] == 'ConditionalCheckFailedException':
print('Already got page=%s (%s)' % (page, err))
else:
raise

Immutable remove item from array from all elements in Map | Redux state

I am facing some problems removing an items from an array from every element within a map in my Redux state.
Using the following structure
entities: {
brands: (Map) {
first: {
...props,
strategists: [
'1', '2'
]
},
second: {
...props,
strategists: [
'1', '2'
]
}, ..
}
}
This is the best I could do:
const newBrands = state
.get('brands')
.map(brand => brand.updateIn(['strategists'], strategists => strategists.filter(s => s !== id)))
return state.set(['brands'], newBrands)
I doesn't add up tho and I coudn't really find it online either.
Thanks
I had not used Immutable.js before, but I played around with your code example and everything seems to work as expected up until the last line, where you're setting state using state.set(['brands'], newBrands) instead of state.set('brands', newBrands); Could that have been the issue? Otherwise the only change is that I assumed that the first and second should also be Maps, so if you got an error before then maybe that was also part of the problem.
I included the code just in case:
const state = Immutable.Map({});
const original = Immutable.Map({
first: Immutable.Map({
someProp: 'someValue1',
strategists: [
'1', '2', '3'
]
}),
second: Immutable.Map({
someProp: 'someValue2',
strategists: [
'1', '2', '3'
]
})
});
const id ='2';
const brands = original
.map(brand =>
brand.updateIn(['strategists'], strategists =>
strategists.filter(s => s !== id)
)
);
const newState = state.set('brands', brands);
console.log(
newState.get('brands')
.toString()
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.1/immutable.js"></script>

Omit utility function, $Omit? Or short for $PropertyType?

Lots of times I find myself using omit, which requires heavy use of $PropertyType
for instnace:
type EntityBase = {
id: EntityId,
created_at: DateStr
}
type Profile = {
...($Diff<EntityBase, {created_at:$PropertyType<EntityBase, 'created_at'>}>), // omit(created_at)
}
That's a lot of un-readable-ness for just trying to omit one key. Type of Profile is just an object of one key of id.
Is there a $Omit and/or shortform for $PropertyType?
Here is how $PropertyType can turn into tons of typing:
type Props = {
authorAvatar: $PropertyType<Profile, 'avatar'>,
authorName: $PropertyType<Profile, 'name'>,
commentsCnt: number,
created_at: $PropertyType<StoryType, 'created_at'>,
socialBoxId: $PropertyType<StoryType, 'socialBoxId'>,
story_line: $PropertyType<StoryType, 'story_line'>,
story_text: $PropertyType<StoryType, 'story_text'>
}
It would be awesome if can just do:
type Props = {
authorAvatar: Profile.avatar,
authorName: Profile.name,
commentsCnt: number,
created_at: StoryType.created_at,
socialBoxId: StoryType.socialBoxId,
story_line: StoryType.story_line,
story_text: StoryType.story_text
}

Filtering / Querying by the Contents of a List in DynamoDB

I am attempting to filter a DynamoDB query by the contents of a Map contained within a List. Here's an example of the structure I'm dealing with.
{
'EventType': 'git/push'
'EventTime': 1416251010,
'Commits': [
{
'id': '29d02aff...',
'subject': 'Add the thing to the place'
},
{
'id': '9d888fec...',
'subject': 'Spelling errors'
},
...
]
}
The hash key is EventType and range key EventTime. I am trying to write a filter that filters the result of a query to a specific id. Is is possible to create a DynamoDB filter expression that correctly filters the query like this? (My first thought was to use contains (a, a), but I don't think that will work on a List of Maps.)
This isn't currently supported by DynamoDB's API's expression language (as of November 2014) but there are some workarounds mentioned here.
I found a solution and I tested it, and it is working fine.
Here's what I did,
// created a schema like that:
var Movie = dynamo.define('example-nested-attribute', {
hashKey : 'title',
timestamps : true,
schema : {
title : Joi.string(),
releaseYear : Joi.number(),
tags : dynamo.types.stringSet(),
director : Joi.object().keys({
firstName : Joi.string(),
lastName : Joi.string(),
titles : Joi.array()
}),
actors : Joi.array().items(Joi.object().keys({
firstName : Joi.string(),
lastName : Joi.string(),
titles : Joi.array()
}))
}
});
and then you can query of a nested array of objects:
var params = {};
params.UpdateExpression = 'SET #year = #year + :inc, #dir.titles = list_append(#dir.titles, :title), #act[0].firstName = :firstName ADD tags :tag';
params.ConditionExpression = '#year = :current';
params.ExpressionAttributeNames = {
'#year' : 'releaseYear',
'#dir' : 'director',
'#act' : 'actors'
};
params.ExpressionAttributeValues = {
':inc' : 1,
':current' : 2001,
':title' : ['The Man'],
':firstName' : 'Rob',
':tag' : dynamo.Set(['Sports', 'Horror'], 'S')
};

Displaying key-value-pairs out of an array by using a template

I want to display key-value pairs stored in an array (derived from a Session-JSON variable) by using the #each template directive. How can I get access (if possible) to the fields of objects in an array.
Sorry, if this is a question that has been already answered, but I didn't find an appropriate answer here.
Here is some sample code (part of a template helper):
attributes: function () {
var attributes = [];
attributes = [{key: test1, value: 1}, {key: test3, value: 2}, {key: test3, value: 3}];
return attributes;
},
In the template, I used "this" or "this.key". Both didn't work the way as expected.
Thanks for any tipps!
Have you defined variables test1, test3 ? It looks like you put test1 and test3 without ", so it means js is trying to find variables with such names. That's why you couldn't see this.key working.
var attributes = [];
attributes = [{key: "test1", value: 1}, {key: "test2", value: 2}, {key: "test3", value: 3}];
return attributes;
In template:
{{#each attributes}}
{{this.key}} : {{this.value}}<br>
{{/each}}
Output:
test1 : 1<br>
test2 : 2<br>
test3 : 3<br>
Check here

Resources