Can anyone tell me how to pass array of object in graphql mutation from react js side.I tried passing the object in react but getting error of not same type.
[input type][1]
[from api side][2]
[declaring the object][3]
[passing object in mutation][4]
[error i'm facing][5]
[1]: https://i.stack.imgur.com/ufVtA.png
[2]: https://i.stack.imgur.com/kQt5m.png
[3]: https://i.stack.imgur.com/hnxLM.png
[4]: https://i.stack.imgur.com/5JCHf.png
[5]: https://i.stack.imgur.com/BonPE.png
What i understood from your problem is that, You want to pass array of objects as argument to the mutation. It can be done easily.
First define a input in the schema,as below. It has the value name as string. You can add whatever you want. This structure will be used for passing value as argument.
input Product {
name: String
}
The above created input will be passed as a array as given below.
type RootMutation{
createProduct(product: [Product]): String
}
You will get the data in the resolver
createProduct: (args)=>{
// You will get the value in this 'args'
// Do Whatever you want
}
The input is given as follow
createProduct(product:[{name:"has"}])
Related
Like I used to do with FastAPI routes, I want to make a function that is expecting a dict. I want to type hint like in FastAPI with a Pydantic model.
Note that I am just using FastAPI as a reference here and this app serves a total different purpose.
What I did:
models.py
from pydantic import BaseModel
class Mymodel(BaseModel):
name:str
age:int
main.py
def myfunc(m:Mymodel):
print(m)
print(m.name)
myfunc({"name":"abcd","age":3})
It prints m as a normal dict and not Mymodel and m.name just throws an AttributeError.
I don't understand why it is behaving like this because the same code would work in FastAPI. Am I missing something here? What should I do to make this work.
I am expecting a dict arg in the func, I want to type hint with a class inherited from pydantic BaseModel. Then I want to acccess the attributes of that class.
I don't want to do:
def myfunc(m):
m = Mymodel(**m)
Thank You.
from pydantic import BaseModel
from pydantic import validate_arguments
class Mymodel(BaseModel):
name:str
age:int
#validate_arguments
def myfunc(m:Mymodel):
print(m)
print(m.name)
myfunc({"name":"abcd","age":3})
This might be what you are looking for: https://pydantic-docs.helpmanual.io/usage/validation_decorator/
Since you pass a dict to your custom function, the attribute should be accessed in the following way:
print(m['name'])
# or
print(m.get('name'))
Otherwise, to use m.name instead, you need to parse the dict to the corresponding Pydantic model, before passing it to the function, as shwon below:
data = {"name":"abcd", "age":3}
myfunc(Mymodel(**data))
# or
myfunc(Mymodel.parse_obj(data))
The reason that passing {"name":"abcd", "age":3} in FastAPI and later accessing the attributes using the dot operator (e.g., m.name) works, is that FastAPI does the above parsing and validation internally, as soon as a request arrives. This is the reason that you can then convert it back to a dictionary in your endpoint, using m.dict(). Try, for example, passing an incorrect key, e.g., myfunc(Mymodel(**{"name":"abcd","MYage":3}))—you would get a field required (type=value_error.missing) error (as part of Pydantic's Error Handling), similar to what FastAPI would return (as shown below), if a similar request attempted to go through (you could also test that through Swagger UI autodocs at http://127.0.0.1:8000/docs). Otherwise, any dictionary passed by the user (in the way you show in the question) would go through without throwing an error, in case it didn't match the Pydantic model.
{
"detail": [
{
"loc": [
"body",
"age"
],
"msg": "field required",
"type": "value_error.missing"
}
]
}
You could alternatively use Pydantic's validation decorator (i.e., #validate_arguments) on your custom function. As per the documentation:
The validate_arguments decorator allows the arguments passed to a
function to be parsed and validated using the function's annotations
before the function is called. While under the hood this uses the same
approach of model creation and initialisation; it provides an
extremely easy way to apply validation to your code with minimal
boilerplate.
Example:
from pydantic import validate_arguments
from pydantic import BaseModel
class Model(BaseModel):
name: str
age: int
#validate_arguments
def myfunc(m: Model):
print(m)
print(m.name)
myfunc({"name":"abcd","age":3})
I want to use FastAPI without an ORM (using asyncpg) and map the returned values from a select query to a pydantic model. This way the returned values are validated with pydantic and the response that is returned is structured like the pydantic model/schema.
I’ve tried looking for documentation on this but it’s pretty hard to find/not clear. I’d appreciate any help!
Every pydantic model inherits a couple of utility helpers to create objects. One is parse_obj which takes a dict and creates the model object from that.
parse_obj: this is very similar to the __init__ method of the model, except it takes a dict rather than keyword arguments. If the object passed is not a dict a ValidationError will be raised.
From the example on the linked section above:
class User(BaseModel):
id: int
name = 'John Doe'
signup_ts: datetime = None
m = User.parse_obj({'id': 123, 'name': 'James'})
print(m)
#> id=123 signup_ts=None name='James'
You might be able to give parse_obj a Record directly since it implements dict-like accessors, so just try it and see if it works. If not you can use dict(<row record from asyncpg>) to convert the record to an actual dict.
Imagine I have a dict.
d = ['a': 1 , 'b':3]
I'm having a hard time to understand the difference between d.get and d.get().
I know that d.get() get the value from the key, like this:
print(d.get('a') )
output: 1
But when I write d.get, it shows this:
print(d.get)
output: <built-in method get of dict object at .........>
What is 'd.get' doing in my code?
I'm using python 3X
A method is literally just an attribute of an object that happens to be of type <class function>. The output you see is essentially what happens when you try to call print() on any function object, and is essentially a concise string representation that python creates for the function.
Actually calling a function is done with parentheses: d.get('a'), which means to execute the behavior the function refers to. It doesn't especially matter where the function is, though: I could do the following, and it would still work:
d = {'a': 1 , 'b':3}
freefunc = d.get
freefunc('a')
This is what the term "first class functions" refers to, when people compare python to something like Java. An entire function can be encapsulated in a variable and treated no differently than any other variable or attribute.
The short answer? There is no difference between the two methods. They are the same exact method.
The difference in your code is at when you write .get() you call the method, but when you write .get you just get a pointer (or location in the memory, to be exact) for that method, to call it later on if needed.
In the first scenario, you are calling print on the result of executing get('a'), which in this case is 1.
In your second scenario, you are calling print on the get function itself, instead of on an execution of it, which evaluates to its documentation, i.e. <built-in method get of dict object at... etc.
I am creating a class and setting some properties. And I am referencing dictionary as a class object. But not able to access the second element of the object.
I tried to google the problem but it does not specify the cause of my problem.
data = {
'a': {
'vsdf': 'asfas',
'nfgn': 'aser',
'aser': 'rtydf'
},
'b': ['ndfg', 'ndf', 'safd']
}
My class looks something like this:
def __init__(self, meta):
self.meta = meta
and when i create the object of this class like this:
request = Request(data)
and try to print the request['b'] it shows the error "'Request' object is not subscriptable"
Actual result should be like :
['', '', '']
but it shows:
'Request' object is not subscriptable
With the code you have given, the data dictionary will be stored in the meta instance variable. You'll need to access it by first accessing that variable, i.e. request.meta['b'].
In order to get it to act the way you want, you'll need to loop through the dict passed in to __init__ and set each variable individually. Take a look at this answer for how to do that: Set attributes from dictionary in python
Here is my method:
def mongo_find(collection_name, find_value):
list(MongoClient("localhost:27017").db[collection_name].find(find_value))
find_value = {'milestones.content': {'$regex': 'The idea'}}, {'milestones.content'}
print(list(mongo_find(collection_name, find_value)))
I'm getting this error:
TypeError: filter must be an instance of dict, bson.son.SON, or other type that inherits from collections.Mapping
but following works okay:
list(MongoClient("localhost:27017").db[collection_name].find({'milestones.content': {'$regex': 'The idea'}}, {'milestones.content'}))
So when running mongo_find method I tried printing:
print(find_value)
({'milestones.content': {'$regex': 'The idea'}}, {'milestones.content'})
Probably because round brackets are added on both ends. Is there a solution?
In your working example
list(MongoClient("localhost:27017").db[collection_name].find({'milestones.content': {'$regex': 'The idea'}}, {'milestones.content'}))
you are actually passing two parameters to the find function. The first one is of type dictionary and specifiies a filter
{'milestones.content': {'$regex': 'The idea'}}
while the second one is a python set which will be used for the projection
{'milestones.content'}
You non-working version passes but one parameter to the find() method which is a python tuple (that is where the round brackets in your output come from) and looks like that:
({'milestones.content': {'$regex': 'The idea'}}, {'milestones.content'})
So to fix that you would want to pass two parameters like in your working example:
def mongo_find(collection_name, filter. projection):
list(MongoClient("localhost:27017").db[collection_name].find(filter, projection))
filter = {'milestones.content': {'$regex': 'The idea'}}
projection = {'milestones.content'}
print(list(mongo_find(collection_name, filter, projection)))