XML 文件上传中的用户验证错误:Python/Django

User Validation Errors in XML File Uploading: Python/Django

提问人:ej719 提问时间:8/15/2023 最后编辑:ej719 更新时间:8/15/2023 访问量:21

问:

当尝试在允许用户上传(特别是 XML)文件的全栈 Django/React 项目中创建功能时,我在用户验证中遇到了一个问题,它抛出错误,即 userId 没有被抓取。任何反馈都是值得赞赏的,因为这是我第一次尝试XML解析。

以下是以下相关文件:


[
  {
    "model": "easapi.user",
    "pk": 1,
    "fields": {
      "uid": "123456",
      "name": "Hayley",
      "email": "[email protected]"
    }
  }
]


[
  {
    "model": "easapi.log",
    "pk": 1,
    "fields": {
      "user": 1,
      "dateStart": "2022-11-22",
      "dateEnd": "2022-11-22",
      "dateGenerated": "2022-11-22"
    }
  }
class User(models.Model):
    uid = models.CharField(max_length=50)
    name = models.CharField(max_length=50)
    email = models.EmailField(max_length=75)
    
    def __str__(self):
        return self.name


class Log(models.Model):
  
  user = models.ForeignKey(User, on_delete=models.CASCADE)
  dateStart = models.DateTimeField(max_length=20)
  dateEnd = models.DateTimeField(max_length=20)
  dateGenerated = models.DateTimeField(max_length=20)
  log_hash = models.CharField(max_length=255) 
  
  
  def __str__(self):
    return self.name

class LogView(ViewSet):
  
  def retrieve(self, request, pk):
    
    log = Log.objects.get(pk=pk)
    serializer = LogSerializer(log)
    return Response(serializer.data)
  
  def list(self, request):
    
    logs = Log.objects.all()
    
    uid_query = request.query_params.get('uid', None)
    if uid_query is not None:
      logs = logs.filter(user=uid_query)
    serializer = LogSerializer(logs, many = True)
    return Response(serializer.data)
  
  @staticmethod
  def generate_unique_log_hash(user_uid):
    while True:
            # Combine user UID, current timestamp, and random seed
            unique_string = f"{user_uid}_{int(time.time())}"
            
            # Generate a hash using SHA-256
            hash_object = hashlib.sha256(unique_string.encode())
            unique_hash = hash_object.hexdigest()
            
            try:
                # Attempt to retrieve a log with this hash
                Log.objects.get(log_hash=unique_hash)
            except Log.DoesNotExist:
                # If the log doesn't exist, this hash is unique
                return unique_hash
  
  def create(self, request):
        user = User.objects.get(uid=request.data['user'])
        # print("User UID:", user_uid)

        
        log_hash = self.generate_unique_log_hash(user.uid)
        print(log_hash)
        log = Log.objects.create(
            dateStart=request.data['dateStart'],
            dateEnd=request.data['dateEnd'],
            dateGenerated=request.data['dateGenerated'],
            user=user,
            log_hash=log_hash
        )
        
        serializer = LogSerializer(log)
        return Response(serializer.data)
  
class LogSerializer(serializers.ModelSerializer):
  
  class Meta:
    model = Log
    fields = ('id', 'user', 'dateStart', 'dateEnd', 'dateGenerated')
    depth = 1

最初,我尝试记录 User 对象以查看它返回的内容,并且在我开始重构代码时,我得到了一个具有未定义值的对象。

现在,我收到相同错误的变体,告诉我无法访问我的 userId (uid)。


File "/views/log.py", line 49, in create
    user = User.objects.get(uid=request.data['user'])
  File "/share/virtualenvs/eas_server-8WC6yVew/lib/python3.10/site-packages/django/db/models/manager.py", line 87, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/python3.10/site-packages/django/db/models/query.py", line 637, in get
    raise self.model.DoesNotExist(
easapi.models.user.User.DoesNotExist: User matching query does not exist.
[14/Aug/2023 20:19:32] "POST /log/ HTTP/1.1" 500 98488`


  File "/python3.10/site-packages/django/db/utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "/python3.10/site-packages/django/db/backends/utils.py", line 89, in _execute
    return self.cursor.execute(sql, params)
  File "/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 328, in execute
    return super().execute(query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: easapi_log.user_id

以下是我尝试为 create 方法实现的其他选项,这些方法收到了类似的响应:


   def create(self, request):
    
     user = User.objects.get(uid=request.data['user'])
     # user = User.objects.get(uid=request.data["user_id"])
     print(user.__dict__)
    
     log = Log.objects.create(
       dateStart = request.data['dateStart'],
       dateEnd = request.data['dateEnd'],
       dateGenerated = request.data['dateGenerated'],
       # user = user
       user = user.uid
     )
   while True:
      try:
        log = Log.objects.create(
            dateStart=request.data['dateStart'],
            dateEnd=request.data['dateEnd'],
            dateGenerated=request.data['dateGenerated'],
             user = user
             # user=user.uid,
        )
         break  # Break the loop if creation is successful
       except IntegrityError:
        # Handle the uniqueness constraint error, e.g., generate a new log_hash
         pass
     serializer = LogSerializer(log)
     return Response(serializer.data)



 def create(self, request):
     try:
         user = User.objects.get(uid=request.data["user"])
     except User.DoesNotExist:
         return Response({"error": "User not found"}, status=status.HTTP_404_NOT_FOUND)
    
     log = Log.objects.create(
         dateStart=request.data['dateStart'],
         dateEnd=request.data['dateEnd'],
         dateGenerated=request.data['dateGenerated'],
         user=user
     )
     serializer = LogSerializer(log)
     return Response(serializer.data)

Django 身份验证 文件上传 xml 解析

评论


答: 暂无答案