如何解决django-graphql-jwt 与 django-phone-field 类型的 PhoneNumber 对象不是 JSON 可序列化的
我目前正在使用 django-phone-field 的项目中使用 graphene-django 库。
这是我的自定义 User 模型,我在其中使用 PhoneField。
from aiohttp import web
@web.middleware
async def error_middleware(request,handler):
try:
response = await handler(request)
# this is needed to handle ``return web.HTTPNotFound()`` case
if response.status == 404:
return web.Response(text='First custom 404 message',status=404)
return response
except web.HTTPException as ex:
# this is needed to handle ``raise web.HTTPNotFound()`` case
if ex.status == 404:
return web.Response(text='Second custom 404 message',status=404)
raise
# this is needed to handle non-HTTPException
except Exception:
return web.Response(text='Oops,something went wrong',status=500)
app = web.Application(middlewares=[error_middleware])
我使用 django-graphql-jwt 处理身份验证。
这是我的 class User(AbstractBaseUser,PermissionsMixin):
"""
Custom User model to add the required phone number
"""
first_name = models.CharField(
max_length=100
)
last_name = models.CharField(
max_length=100
)
email = models.EmailField(
verbose_name='Email address',max_length=255,unique=True,# Because it's unique,blank is not an option because there Could be 2 with the same value ('')
blank=False,null=True
)
phone = CustomPhoneField(
# Please note this formatting only works for US phone numbers right Now
# https://github.com/VeryApt/django-phone-field#usage
# If international numbers are needed at some point,take a look at:
# https://github.com/stefanfoulis/django-phonenumber-field
E164_only=True,unique=True
)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'phone'
required_FIELDS = ['first_name','last_name',]
查询:
tokenAuth
mutation TokenAuth ($phone: String!,$password: String!) {
tokenAuth(phone: $phone,password: $password) {
token
payload
refreshExpiresIn
}
}
我通过覆盖 PhoneField 的 {
"errors": [
{
"message": "Object of type PhoneNumber is not JSON serializable","locations": [
{
"line": 2,"column": 5
}
],"path": [
"tokenAuth"
]
}
],"data": {
"tokenAuth": null
}
}
方法临时制作了一个猴子补丁,如下所示:
to_python
我想知道针对此问题的正确解决方案是什么,并且还想了解它的实际工作原理,以便我可以继续使用更优雅的解决方案。
解决方法
看着您的问题,我认为您正在尝试使用字符串而不是 Json 字段。如果电话号码是您可以尝试使用 JsonString 数据类型的 JSON 字段,则可以解决这个问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。