Cla*_*ros 7 django graphql graphene-django
我想知道是否可以翻译石墨烯提供的验证错误消息?例如:“未提供身份验证凭据”,如下面的代码示例所示。
{
"errors": [
{
"message": "Authentication credentials were not provided",
"locations": [
{
"line": 2,
"column": 3
}
]
}
],
"data": {
"viewer": null
}
}
Run Code Online (Sandbox Code Playgroud)
import graphene\nfrom graphene_django.utils import camelize\n\nclass ErrorType(graphene.Scalar):\n @staticmethod\n def serialize(errors):\n if isinstance(errors, dict):\n if errors.get("__all__", False):\n errors["non_field_errors"] = errors.pop("__all__")\n return camelize(errors)\n raise Exception("`errors` should be dict!")\nRun Code Online (Sandbox Code Playgroud)\n\nclass MyMutation(graphene.Mutation):\n\n # add the custom error type\n errors = graphene.Field(ErrorType)\n\n form = SomeForm\n\n @classmethod\n def mutate(cls, root, info, **kwargs):\n f = cls.form(kwargs)\n if f.is_valid():\n pass\n else:\n # pass the form error to your custom error type\n return cls(errors=f.errors.get_json_data())\nRun Code Online (Sandbox Code Playgroud)\n\ndjango-graphql-auth使用类似的错误类型,它的工作原理如下,例如注册:
\n\nmutation {\n register(\n email:"skywalker@email.com",\n username:"skywalker",\n password1: "123456",\n password2:"123"\n ) {\n success,\n errors,\n token,\n refreshToken\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\n应该返回:
\n\n{\n "data": {\n "register": {\n "success": false,\n "errors": {\n "password2": [\n {\n "message": "The two password fields didn\xe2\x80\x99t match.",\n "code": "password_mismatch"\n }\n ]\n },\n "token": null,\n "refreshToken": null\n }\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
5179 次 |
| 最近记录: |