I'm currently a bit stuck. I have to create a model of our dynamodb using pynamodb, and here's what I have (part of a bigger model, exported from a real user in DB)
packs = [
{
"exos": {
"4": {
"start": 1529411739,
"session": 1529411739,
"finish": 1529417144
},
"5": {
"start": 1529417192,
"session": 1529417192
}
},
"id": 10
},
{
"exos": {
"32": {
"start": 1529411706,
"session": 1529411706
}
},
"id": 17
}
]
Here's what I got so far:
class ExercisesMapAttribute(MapAttribute):
pass
class PackMapAttribute(MapAttribute):
exos = ExercisesMapAttribute()
id = NumberAttribute()
class TrainUser(Model):
class Meta:
table_name = 'TrainUser'
region = 'eu-west-1'
# [...] Other stuff removed for clarity
packs = ListAttribute(of=PackMapAttribute())
Currently I think I got correctly up until the "4":, "5": etc... As they are exercices name.
The idea is that this structure is supposed to represent a list of packs, then inside a list of exercises with their id and more info... I need a way to map that from the current db json to classes I can then use with PynamoDB. Is it even possible?
Thanks!
I've tried DynamicMapAttribute but I can't figure out if it will work with my configuration.
I also don't know how a custom attribute could be done to overcome this.
Related
I am trying to combine two SQLAlchemyConnectionField. The current error i face is graphql.error.base.GraphQLError: Expected value of type "PostsObject" but got: Tag
My current connections are defined like so posts = SQLAlchemyConnectionField(PostsObject.connection, /* input arguments like posts(name: "") */) Is there a way to add another type or allow to return something like
"data": {
"posts": {
"edges": [
{
"node": "Different table"
},
{
"node": "Other table"
}]}},
I am using graphene_sqlalchemy well anyway thats all thanks !
I am parsing a file and end up with a dictionary like this:
user_data = {
"title": "TestA",
"sects": [
{
"type": "cmd",
"cmd0": {
"moveX": 12,
"moveY": 34,
"action": "fire"
},
"session": 9999,
"cmd1": {
"moveX": 56,
"moveY": 78,
"action": "stop"
},
"endType": 0,
},
{
"type": "addUsers",
"user1": {
"name": "John",
"city": "London"
},
"user2": {
"name": "Mary",
"city": "New York"
},
post = "yes"
}
]
}
I am attempting to validate it using marshmallow but not sure how to handle these two things:
With sects the content of each nested dict is dependent on the type (cmd, addUser, etc). Is there a way to pick a schema based on the value of a field?
Is there such a thing as field 'startsWith' to handle the fact that I may have cmd0, cmd1...cmdN?
So, something like the following:
class CmdSchema(schema):
type = fields.Str()
cmdN = fields.Dict(...) # Allow cmd1, cmd2, etc
session = fields.Int()
endType = fields.Int()
class AddUsersSchema(schema):
type = fields.Str()
userN = fields.Dict(...) # Allow user1, user2, etc
post = fields.Str()
class ParsedFileSchema(schema):
title = fields.Str()
sects = fields.Nested(...) # Choose nested schema based on sects[i]['type']?
Note: I cannot change the format/content of the file I'm parsing and order matters (so I need to retain the order of cmd1, cmd2, etc so they can be processed in the correct order).
1/ What you want to achieve is polymorphism. You may want to check out marshmallow-oneofschema.
2/ This does not exist to my knowledge. It shouldn't be too hard to create as a custom validator, though. It might even make it to the core.
I am working with a JSON request.get that returns a list. I will like to save each individual object in the response to my models so I did this:
in views.py:
def save_ram_api(request):
r = requests.get('https://ramb.com/ciss-api/v1/')
# data = json.loads(r)
data = r.json()
for x in data:
title = x["title"]
ramyo_donotuse = x["ramyo"]
date = x["date"]
thumbnail = x["thumbnail"]
home_team_name = x["side1"]["name"]
away_team_name = x["side2"]["name"]
competition_name = x["tournament"]["name"]
ramAdd = ramSample.objects.create(title=title, ramyo_donotuse=ramyo_donotuse, date=date, thumbnail=thumbnail, home_team_name=home_team_name, away_team_name=away_team_name, competition_name=competition_name)
ramAdd.save()
return HttpResponse("Successfully submitted!")
This works fine except that it would only save the last objects on the list.
the JSON response list (as a random 60 objects at any time) would look something like:
[
{
"title": "AY - BasketMouth",
"ramyo": "AY de comedian"
"side1": {
"name": "Comedy Central",
"url": "https:\/\/www.rabithole.com\/laugh\/dave-chappel\/"
},
"side2": {
"name": "Basket Mouth",
"url": "https:\/\/www.rabithole.com\/laugh\/chris-rockie\/"
},
"tournament": {
"name": "Night of a thousand laugh",
"id": 15,
"url": "https:\/\/www.rabithole.com\/laugh\/chris-rockie\/"
},
"points": [
{
"nature": "Gentle",
"phrase": "Just stay"
},
{
"nature": "Sarcastic",
"phrase": "Help me"
}
]
},
{
"title": "Dave - Chris",
"ramyo": "Dave Chapelle"
"side1": {
"name": "Comedy Central",
"url": "https:\/\/www.rabithole.com\/laugh\/dave-chappel\/"
},
"side2": {
"name": "Chris Rockie",
"url": "https:\/\/www.rabithole.com\/laugh\/chris-rockie\/"
},
"tournament": {
"name": "Tickle me",
"id": 15,
"url": "https:\/\/www.rabithole.com\/laugh\/chris-rockie\/"
},
"points": [
{
"nature": "Rogue",
"phrase": "Just stay"
}
]
}
]
In this case my views.py will only save the last dictionary on the list, ignoring the other 59.
My question would be:
How do I get the views.py to save the entire objects on the list?
Notice that the "points" is also a list that contains one or more dictionaries, any help how to save this as well?
Your code is saving only the last object in the list because you are creating and saving the object outside of the loop. Try this,
def save_ram_api(request):
r = requests.get('https://ramb.com/ciss-api/v1/')
# data = json.loads(r)
data = r.json()
for x in data:
title = x["title"]
ramyo_donotuse = x["ramyo"]
date = x["date"]
thumbnail = x["thumbnail"]
home_team_name = x["side1"]["name"]
away_team_name = x["side2"]["name"]
competition_name = x["tournament"]["name"]
ramAdd = ramSample.objects.create(title=title, ramyo_donotuse=ramyo_donotuse, date=date, thumbnail=thumbnail, home_team_name=home_team_name, away_team_name=away_team_name, competition_name=competition_name)
ramAdd.save()
return HttpResponse("Successfully submitted!")
How do I get the views.py to save the entire objects on the list?
Notice that the "points" is also a list that contains one or more
dictionaries, any help how to save this as well?
Regarding your those questions
If you are using PostgreSQL as a database then you can use Django's built is JSONField and ArrayField for PostgreSQL database.
And if your database is not PostgreSQL you can use jsonfield library.
My slot for a custom intent is always being recognised as None.
I have an intents schema which looks like this:
{
"interactionModel": {
"languageModel": {
"invocationName": "name_of_app",
"intents": [
{
"name": "AMAZON.CancelIntent",
"samples": []
},
{
"name": "AMAZON.HelpIntent",
"samples": []
},
{
"name": "AMAZON.StopIntent",
"samples": []
},
{
"name": "EventsIntent",
"slots": [
{
"name": "eventCity",
"type": "AMAZON.GB_CITY"
}
],
"samples": [
"whats on in {eventCity}",
"whats going on in {eventCity} ",
"tell me what events are in {eventCity}"
]
}
],
"types": []
}
}
}
My code is in python, using the flask-ask framework. My main entrypoint looks something like this:
#ask.launch
def start_skill():
welcome_message = 'Welcome to name_of_app, what do you want?'
return question(welcome_message)
#ask.intent('EventsIntent', mapping={'city': 'eventCity'})
def weather(city):
return statement('you have selected {}'.format(city))
Even this simple example however, does not work when the input is:
"whats on in London?"
I have tried with lowercase and with/without punctuation in the testing panel on the amazon developer console, however the return is always:
"you have selected None"
indicating that None is passed as 'eventCity'. Am I passing this slot incorrectly in either the intent schema or in the code?
Thanks
hey buddy following is the solution of your problem:
#ask.launch
def start_skill():
welcome_message = 'Welcome to name_of_app, what do you want?'
return question(welcome_message)
#ask.intent('EventsIntent', convert={'eventCity': str})
def weather(eventCity):
return statement('you have selected {}'.format(eventCity))
I was also facing similar issue this thing resolved my issue.
I use django and django graphene for make a graphql API.
In the view of my application, I use reactJS and react-bootstrap-table. React-bootstrap-table expects that I pass it an object array but does not support nested objects.
I created query in my schema.py:
class ApplicationNode(DjangoObjectType):
class Meta:
model = Application
filter_fields = ['name', 'sonarQube_URL']
interfaces = (relay.Node,)
class Query(ObjectType):
application = relay.Node.Field(ApplicationNode)
all_applications = DjangoFilterConnectionField(ApplicationNode)
The answers to these queries are JSON nested objects like this:
{
"data": {
"allApplications": {
"edges": [
{
"node": {
"id": "QXBwbGljYXRpb25Ob2RlOjE=",
"name": "foo",
"sonarQubeUrl": "foo.com",
"flow":{
"id": "QYBwbGljYXRpb45Ob2RlOjE=",
"name": "flow_foo"
}
}
},
{
"node": {
"id": "QXBwbGljYXRpb25Ob2RlOjI=",
"name": "bar",
"sonarQubeUrl": "bar.com"
"flow":{
"id": "QXBwbGljYXRpb26Ob2RlOjA=",
"name": "flow_bar"
}
}
}
]
}
}
}
I have to put them flat before giving them to React-bootstrap-table.
What is the better way, intercept the results of graphene-django queries to put them flat or make this job in ReactJS view?
If the first way is better, how to intercept the results of graphene-django queries to put them flat?
The best thing to do is to wrap react-bootstrap-table in a new component. In the component massage the relay props into a flat structure as needed for react bootstrap table.
For example:
MyReactTable = ({allApplications}) => {
let flatApplications = allApplications.edges.map(({node: app}) => {
return {
name: app.name,
sonarQubeUrl: app.sonarQubeUrl,
flowName: app.flow.name
};
});
return (
<BootstrapTable data={flatApplications} striped={true} hover={true}>
<TableHeaderColumn dataField="name" isKey={true} dataAlign="center" dataSort={true}>Name</TableHeaderColumn>
<TableHeaderColumn dataField="sonarQubeUrl" dataSort={true}>Sonar Qube Url</TableHeaderColumn>
<TableHeaderColumn dataField="flowName" dataFormat={priceFormatter}>Flow Name</TableHeaderColumn>
</BootstrapTable>
);
};