Translating nested query from GraphQL to Graphene not working - python-3.x

So I have a GraphQL API which I wrote a query to and it works and sent me back data in GraphiQL.
query dishes {
dishes {
name
recipeNote
description
}
}
This is my Graphene translation of what I have
class Dish(ObjectType):
name = String()
recipeNote = String()
description = String()
class Query(ObjectType):
first = Field(Dish)
def resolve_first(parent, info):
return parent
query_string = "{ first { dishes { name recipeNote description } } }"
result = schema.execute(
query_string)
print(result)
print(result.data)
However this gives me an error {'errors': [{'message': 'Cannot query field "dishes" on type "Dish".', 'locations': [{'line': 1, 'column': 11}]}]}

from graphene import List, ObjectType, String
class Dish(ObjectType):
name = String()
recipeNote = String()
description = String()
class Query(ObjectType):
dishes = List(Dish)
def resolve_dishes(parent, info):
return [Dish(name='', recipeNote='', description=''), ...]
query_string = "query dishes {
dishes {
name
recipeNote
description
}
}"
result = schema.execute(
query_string)
print(result)
print(result.data)

Related

Flutter access model attribute using dynamic key [duplicate]

I'm trying to access a class value by using a variable previously defined in dart, but I keep getting the error the operator [] isn't defined for the class
In Javascript I would access an object value using a variable like this:
let movie = {
movieTitle : 'Toy Story',
actor: 'Tom Hanks'
}
let actorName = 'actor';
console.log(movie[actorName]); // <- what I'm trying to replicate in dart
// expected output: Tom Hanks
Here is what I've tried and is throwing that error
class Movie {
String name;
String actor;
String producer;
}
void main() {
var movieTitle = new Movie();
movieTitle.name = 'Toy Story';
movieTitle.actor = 'Tom Hanks';
print(movieTitle.actor); <- prints out Tom Hanks as expected
var actorName = 'actor';
print(movieTitle[actorName]); <- throws error
}
I expect to be able to use a variable on the fly to access the value.
A trivial use case for me would be if I had a a list of Movie classes, where some actors and producers are null, I would like to filter on either non null actors or producer with a function like so:
List values = movieList.where((i) => i.actor != "null").toList(); // returns all Movies in movieList where the actor value isn't the string "null"
var actorIsNull = 'actor';
List values = movieList.where((i) => i[actorisNull] != "null").toList(); // throws error
You can createn a toMap() function in your Movie class and access properties using [] operator
class Movie {
String name;
String actor;
String producer;
Map<String, dynamic> toMap() {
return {
'name': name,
'actor' : actor,
'producer' : producer,
};
}
}
Now Movie class properties can be accessed as:
Movie movie = Movie();
movie.toMap()['name'];
You cannot access class members by a string containing their name. (Except with mirrors - outside the scope of this answer.)
You could remove the class altogether and just use a Map<String, String>.
Map<String, String> movie = {
'movieTitle': 'Toy Story',
'actor': 'Tom Hanks',
}
You could add some bool methods on the class.
bool hasNoActor() => actor == null;
...
List values = movieList.where((m) => !m.hasNoActor()).toList();
Or, you could pass a lambda to your mapper.
Movie movieTitle = Movie()
..name = 'Toy Story'
..actor = 'Tom Hanks';
Function hasActor = (Movie m) => m.actor != null;
List values = movieList.where(hasActor).toList();

Print the specific field from list

Please help to print the assetNumber. Need to search for specific assetname and print its associated assetNumber using list in groovy.
Currently, it does not print value. It struck once search criteria is entered.
class Main
{
public static void main(String[] args)
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in))
List list = new ArrayList()
Asset asset = new Asset()
def name
def assetNumber
def assigneeName
def assignedDate
def assetType
String userInput = "Yes"
while(userInput.equalsIgnoreCase("Yes"))
{
println "Enter the asset details:"
asset.name = br.readLine()
asset.assetNumber= Integer.parseInt(br.readLine())
asset.assigneeName = br.readLine()
asset.assignedDate = Date.parse('dd/MM/yyyy', br.readLine())
list.add(asset)
println "Do you want to continue(yes/no)"
userInput = br.readLine()
}
println "Enter the asset type:"
assetType = br.readLine()
println "Asserts with type "+assetType+":"
def items = list.findAll{p->p.name == assetType }
items.each { println it.assetNumber }
}
}
class Asset
{
def name
def assetNumber
def assigneeName
def assignedDate
}
You are overwriting the value in your Asset object, then adding the same object to the list every time
If you create a new asset inside the loop (rather than outside it), it should work...
Something like this:
import groovy.transform.*
class Main {
static main(args) {
def console = System.console()
def list = []
while (true) {
def name = console.readLine 'Enter the asset name:'
def number = console.readLine 'Enter the asset number:'
def assignee = console.readLine 'Assignee name:'
def date = console.readLine 'Date (dd/MM/yyyy):'
list << new Asset(
name: name,
assetNumber: Integer.parseInt(number),
assigneeName: assignee,
assignedDate: Date.parse('dd/MM/yyyy', date)
)
if ('Y' != console.readLine('Enter another (y/n):')?.take(1)?.toUpperCase()) {
break
}
}
def type = console.readLine 'Enter the asset type:'
println "Assets with type $type:"
list.findAll { p -> p.name == type }
.each { println it.assetNumber }
}
#Canonical
static class Asset {
def name
def assetNumber
def assigneeName
def assignedDate
}
}

Flask admin: add dynamic choices to SelectField inside embedded document

I have a string field inside an embedded document and override this field to be a selected field.
After overriding, I add an empty list of choices as an argument to the selcted field.
The issue is that on form access we try to add some dynamic choices to the selected field, but for some reason, this fails.
How can we add some dynamic choices?
I need to do this using some kind of preprocessor because the data is from DB that loads just after all the models.
class:
class BadgeDoc(EmbeddedDocument):
parent_id = ObjectIdField()
name = StringField()
display_text = StringField()
color = StringField()
extra_style = StringField()
service = ObjectIdField()
badge_type = StringField()
class PresentationCategory(Presentation):
product = ReferenceField('ProductType')
article = EmbeddedDocumentField(Article)
show_video_review = BooleanField()
show_video_reviews_count = IntField(default=0)
badge = ListField(EmbeddedDocumentField(BadgeDoc))
view:
class PresentationView(NewPresentationView):
form_subdocuments = {
'badge': {
'form_subdocuments': {
None:
{
'form_excluded_columns': ('name', 'display_text', 'color', 'extra_style', 'service',
'badge_type'),
'form_overrides': {
'parent_id': admin.form.fields.Select2Field,
},
'form_args': {
'parent_id': {'choices': []}
}
}
}
}
}

Groovy map constructor keys to different variable names

I have JSON looking like:
{
"days": [
{
"mintemp": "21.8"
}
]
}
With Groovy, I parse it like this:
class WeatherRow {
String mintemp
}
def file = new File("data.json")
def slurper = new JsonSlurper().parse(file)
def days = slurper.days
def firstRow = days[0] as WeatherRow
println firstRow.mintemp
But actually, I would like to name my instance variable something like minTemp (or even something completely random, like numberOfPonies). Is there a way in Groovy to map a member of a map passed to a constructor to something else?
To clarify, I was looking for something along the lines of #XmlElement(name="mintemp"), but could not easily find it:
class WeatherRow {
#Element(name="mintemp")
String minTemp
}
Create a constructor that takes a map.
Runnable example:
import groovy.json.JsonSlurper
def testJsonStr = '''
{"days": [
{ "mintemp": "21.8" }
]}'''
class WeatherRow {
String minTemp
WeatherRow(map) {
println "Got called with constructor that takes a map: $map"
minTemp = map.mintemp
}
}
def slurper = new JsonSlurper().parseText(testJsonStr)
def days = slurper.days
def firstRow = days[0] as WeatherRow
println firstRow.minTemp
Result:
Got called with constructor that takes a map: [mintemp:21.8]
21.8
(of course you'd remove the println line, it's just there for the demo)
You can achieve this using annotation and simple custom annotation processor like this:
1. Create a Custom Annotation Class
#Retention(RetentionPolicy.RUNTIME)
#interface JsonDeserializer {
String[] names() default []
}
2. Annotate your instance fields with the custom annotation
class WeatherRow{
#JsonDeserializer(names = ["mintemp"])
String mintemp;
#JsonDeserializer(names = ["mintemp"])
String minTemp;
#JsonDeserializer(names = ["mintemp"])
String numberOfPonies;
}
3. Add custom json deserializer method using annotation processing:
static WeatherRow fromJson(def jsonObject){
WeatherRow weatherRow = new WeatherRow();
try{
weatherRow = new WeatherRow(jsonObject);
}catch(MissingPropertyException ex){
//swallow missing property exception.
}
WeatherRow.class.getDeclaredFields().each{
def jsonDeserializer = it.getDeclaredAnnotations()?.find{it.annotationType() == JsonDeserializer}
def fieldNames = [];
fieldNames << it.name;
if(jsonDeserializer){
fieldNames.addAll(jsonDeserializer.names());
fieldNames.each{i ->
if(jsonObject."$i")//TODO: if field type is not String type custom parsing here.
weatherRow."${it.name}" = jsonObject."$i";
}
}
};
return weatherRow;
}
Example:
def testJsonStr = '''
{
"days": [
{
"mintemp": "21.8"
}
]
}'''
def parsedWeatherRows = new JsonSlurper().parseText(testJsonStr);
assert WeatherRow.fromJson(parsedWeatherRows.days[0]).mintemp == "21.8"
assert WeatherRow.fromJson(parsedWeatherRows.days[0]).minTemp == "21.8"
assert WeatherRow.fromJson(parsedWeatherRows.days[0]).numberOfPonies == "21.8"
Check the full working code at groovyConsole.

Dynamic object graph navigation in Groovy

folks!
I want to be able to navigate Groovy object graph dynamically, having the path in string:
def person = new Person("john", new Address("main", new Zipcode("10001", "1234")))
def path = 'address.zip.basic'
I know that I can access a property in map notation, but it's only one level deep:
def path = 'address'
assert person[path] == address
Is there any way to evaluate deeper path?
Thanks!
This can be achieved by overriding the getAt operator and traversing the property graph. The following code uses Groovy Category but inheritance or mixins could also be used.
class ZipCode {
String basic
String segment
ZipCode(basic, segment) {
this.basic = basic
this.segment = segment
}
}
class Address {
String name
ZipCode zip
Address(String name, ZipCode zip) {
this.name = name
this.zip = zip
}
}
class Person {
String name
Address address
Person(String name, Address address) {
this.name = name
this.address = address
}
}
#Category(Object)
class PropertyPath {
static String SEPARATOR = '.'
def getAt(String path) {
if (!path.contains(SEPARATOR)) {
return this."${path}"
}
def firstPropName = path[0..path.indexOf(SEPARATOR) - 1]
def remainingPath = path[path.indexOf(SEPARATOR) + 1 .. -1]
def firstProperty = this."${firstPropName}"
firstProperty[remainingPath]
}
}
def person = new Person('john', new Address('main', new ZipCode('10001', '1234')))
use(PropertyPath) {
assert person['name'] == 'john'
assert person['address.name'] == 'main'
assert person['address.zip.basic'] == '10001'
}
PropertyPath.SEPARATOR = '/'
use(PropertyPath) {
assert person['address/zip/basic'] == '10001'
}

Resources