将字典数据作为输入传递给FastAPI Strawberry Mutation应该如何操作?

huangapple go评论70阅读模式
英文:

How Can I pass dictionary data as a input to the fast api strawberry mutation?

问题

My input data: {"Nepal": "Kathmandu", "Italy": "Rome", "England": "London"}

Goal: 我想将上述数据作为输入传递给草莓变异。

It seems currently, strawberry is not supporting dict type. I found JSON type but if i want to use JSON as a type i need to pass the data like this "{\"Nepal\": \"Kathmandu\", \"Italy\": \"Rome\", \"England\": \"London\"}"

I dont want to escape the quotes by using \. Is there any alternative to handle this issue?

英文:

My input data: {"Nepal": "Kathmandu", "Italy": "Rome", "England": "London"}

Goal: I want to pass above data as a input to the strawberry mutation.

It seems currently, strawberry is not supporting dict type. I found JSON type but if i want to use JSON as a type i need to pass the data like this "{\"Nepal\": \"Kathmandu\", \"Italy\": \"Rome\", \"England\": \"London\"}"

I dont want to escape the quotes by using \. Is there any alternative to handle this issue?

答案1

得分: 1

我前两天做了类似的事情,不过不确定是否完全符合你的需求,我的数据库有一个 JSON 字段,所以我的 GraphQL 也需要 JSON 类型。

import ast

@strawberry.type(description="blogs 的 mutation")
class BlogMutation:

    @strawberry.mutation(description="创建新博客")
    async def create_blog(self, id: int, blog: BlogCreate) -> int:

        parse_blog_body = ast.literal_eval(blog.body)
        parse_blog_body = dict(parse_blog_body)

        new_blog = BlogTable(title=blog.title, body=parse_blog_body, user_id=id)
        session.add(new_blog)
        session.commit()
        session.refresh(new_blog)

        return new_blog.id

我的 serializers.py


from strawberry.scalars import JSON
import strawberry


class BlogSerializer:
    id: int
    title: str
    body: JSON


class BlogCreateSerializer:
    title: str
    body: JSON


BlogCreate = strawberry.input(BlogCreateSerializer)
Blog = strawberry.type(BlogSerializer)

model.py


from sqlalchemy import Column, Integer, String, ForeignKey, JSON
from sqlalchemy.orm import relationship
from connection.connection import Base

class Blog(Base):
    __tablename__ = 'blog'

    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String)
    body = Column(JSON, default={})
    user_id = Column(Integer, ForeignKey('user.id'))
    user = relationship('User', back_populates='blog')

    class Config:
        arbitrary_types_allowed = True

请注意,你可能遇到的问题可能与 GraphQL 的引号有关。注意查询使用了双引号,然后 JSON 使用了单引号,找不到解决这个问题的方法。


mutation {
  createBlog(id: 1, blog: {
    title: "hello",
    body: "{'hello': 'world'}"
  })
}

英文:

I did something similar the other day, however not sure if it is exactly what you want, my database had a json field so my graphql also required the Json type

import ast

@strawberry.type(description="mutation for blogs")
class BlogMutation:

    @strawberry.mutation(description="Create a new blog")
    async def create_blog(self, id: int, blog: BlogCreate) -> int:

        parse_blog_body = ast.literal_eval(blog.body)
        parse_blog_body = dict(parse_blog_body)

        new_blog = BlogTable(title=blog.title, body=parse_blog_body, user_id=id)
        session.add(new_blog)
        session.commit()
        session.refresh(new_blog)

        return new_blog.id

my serializers.py


from strawberry.scalars import JSON
import strawberry


class BlogSerializer:
    id: int
    title: str
    body: JSON


class BlogCreateSerializer:
    title: str
    body: JSON


BlogCreate = strawberry.input(BlogCreateSerializer)
Blog = strawberry.type(BlogSerializer)

model.py


from sqlalchemy import Column, Integer, String, ForeignKey, JSON
from sqlalchemy.orm import relationship
from connection.connection import Base

class Blog(Base):
    __tablename__ = 'blog'

    id = Column(Integer, primary_key=True, autoincrement=True)
    title = Column(String)
    body = Column(JSON, default={})
    user_id = Column(Integer, ForeignKey('user.id'))
    user = relationship('User', back_populates='blog')

    class Config:
        arbitrary_types_allowed = True


do note that your issue might be to do with graphql quotes
notice the query is using double quotes and then the json is using single, could not find a way around this


mutation {
  createBlog(id: 1, blog: {
    title: "hello",
    body: "{'hello': 'world'}"
  })
}

答案2

得分: 0

Python支持单引号和双引号来包围字符串文字,因此您可以将所述JSON字符串用单引号引起来,而不必转义双引号:

{'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}

如果您的输入数据以字典形式提供,您还可以使用json.dumps方法将对象输出为JSON字符串:

import json
json.dumps({'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'})
'{"Nepal": "Kathmandu", "Italy": "Rome", "England": "London"}'
英文:

Python supports both single quotes and double quotes for enclosing a string literal, so you can write the said JSON string quoted in single quotes instead to avoid having to escape double quotes:

'{"Nepal": "Kathmandu", "Italy": "Rome", "England": "London"}'

If you have the input data given to you as a dict, you can also use the json.dumps method instead to output the object as a JSON string:

>>> import json
>>> json.dumps({"Nepal": "Kathmandu", "Italy": "Rome", "England": "London"})
'{"Nepal": "Kathmandu", "Italy": "Rome", "England": "London"}'
>>>

huangapple
  • 本文由 发表于 2023年6月6日 09:09:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76410848.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定