API 端点返回 TypeError: 'type' object is not iterable
Posted
技术标签:
【中文标题】API 端点返回 TypeError: \'type\' object is not iterable【英文标题】:API endpoint returns TypeError: 'type' object is not iterableAPI 端点返回 TypeError: 'type' object is not iterable 【发布时间】:2020-06-20 14:12:57 【问题描述】:我正在通过使用AbstractBaseUser
类扩展users
类来编写创建用户API。该 API 对常规 model fields
工作正常,例如 EmailField
、CharField
、BooleanField
。但后来我决定也存储用户的profile_picture
。所以我创建了一个新字段profile_picture
为ImageField
来将用户头像的路径存储在相同的扩展users
模型中。
models.py
class Users(AbstractBaseUser, PermissionsMixin):
"""
This model is used to store user login credential and profile information.
It's a custome user model but used for Django's default authentication.
"""
email = models.EmailField(max_length=255, unique=True)
first_name = models.CharField(max_length=255, blank=False, null=False)
last_name = models.CharField(max_length=255, blank=False, null=False)
profile_picture = models.ImageField(upload_to='Images/', max_length=None, blank=True)
is_active = models.BooleanField(default=True)
# defing a custome user manager class for the custome user model.
objects = managers.UserManager()
# using email a unique identity for the user and it will also allow user to use email while logging in.
USERNAME_FIELD = 'email'
然后我更新了UserAPIView
类以添加parser_classes = (FileUploadParser)
view.py
from django.shortcuts import render
from . import views
from rest_framework.views import APIView
from django.db import IntegrityError
from rest_framework import status
from . import models, serializers
from rest_framework.response import Response
from django.core.mail import send_mail
from rest_framework.parsers import FileUploadParser
class UserAPIViews(APIView):
"""
"""
parser_classes = (FileUploadParser)
def post(self, request, format=None):
"""
"""
print(request.data)
serialized_data = serializers.UserSerializer(data=request.data)
if serialized_data.is_valid():
try:
user_id = serialized_data.save()
except IntegrityError as error:
message = f"Email already exist."
return Response (
'error_message' : message,
'status' : status.HTTP_226_IM_USED
)
subject = 'Eitan - Case Manager Account Credentials'
body = f"Hi serialized_data.validated_data.get('first_name') Your case manager account is ready. Please use following credentials to login. Email - serialized_data.validated_data.get('email'), Password - serialized_data.validated_data.get('password') Thank You! Team Eitan."
sender = "steinnlabs@gmail.com"
to = serialized_data.validated_data.get('email')
send_mail(subject, body, sender, [to], fail_silently=False)
success_message = f"User has been created."
return Response(
'success_message' : success_message,
'status' : status.HTTP_201_CREATED
)
else:
return Response (serialized_data.error_messages)
更新settings.py
以添加MEDIA_ROOT
和MEDIA_URL
settings.py
# Image upload configurations
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
MEDIA_URL = '/media/
现在,当我尝试到达http://127.0.0.1:8000/user/create/
的终点时,它会返回 -
TypeError at /user/create/
'type' object is not iterable
【问题讨论】:
【参考方案1】:parser_classes = (FileUploadParser)
应该是
parser_classes = (FileUploadParser,)
或者使用列表[]
代替元组。
如果不添加逗号,Python 会以与 x = something
相同的方式解释 x = (something)
。
【讨论】:
现在返回 "detail": "Missing filename. Request should include a Content-Disposition header with a filename parameter."
这是一个不同的错误。你问的那个已经解决了!请查看***.com/questions/46806335/…
你能告诉我如何将请求传递给 URL http://127.0.0.1:8000/user/create/
。我以前从未创建过图像上传 API。我的 JSON 对象中没有t know how to send the JSON request to upload files. Do I have to mention the path of image file as a value to key
profile_picture`?
您可以使用表单并通过request.FILES
获取内容。见:***.com/questions/20822823/…【参考方案2】:
我只需要添加解析器类来解析request.data
。
parser_classes = (FormParser, MultiPartParser)
【讨论】:
以上是关于API 端点返回 TypeError: 'type' object is not iterable的主要内容,如果未能解决你的问题,请参考以下文章
在谷歌云视觉 API 中调用 client.text_detection() 获取 TypeError: type object got multiple values for keyword arg
在使用json.dumps()格式化响应数据时报错TypeError: Object of type Response is not JSON serializable
Chrome iOS 58 中 fetch API 返回的 TypeError
Discord.js/ROBLOX API Endpoint 问题返回“Typeerror: json.data is not iterable”