如果没有从JSON响应中获取数据,如何制作用户数据?

时间:2019-10-29 14:33:17

标签: python json django

我正在创建一个应用程序,该应用程序从一些用户那里获取信息,例如姓名,电子邮件,ID号等。我想从POST获得响应,但是在某些情况下,我没有从用户那里获得电子邮件,所以我需要用这个空数据创建一个参数。

换句话说,我正在解析POST的参数,并检查所有数据是否正确且合法,如果我没有从API收到电子邮件,我想创建一个参数,或者可能是一个空的至少是字符串。

            try:
                if not email:
                    errors['email'] = _(u'This data is missing.')
                else:
                    validate_email(email)
                    if email != user_data['email']:
                        if user_data['email'] in ["", None]:
                            user_data['email'] = email
                        # If the email is modified, its no longer verified and I check if the user is registered with another email.
                        if 'email_verified' in user_data:
                            user_data['email_verified'] = False
                        users_same_mail = User.objects.filter(email=email)
                        if users_same_mail.exists():
                            # I check if the email is twice registered
                            # I give the user another email registered in the database
                            errors['email'] = _(
                                u'The email is already registered.')

            except ValidationError as e:
                errors['email'] = _(
                    u'Bad email, please enter another one.')```

What can i write to create a empty string or some value, all i want is to set email to something that is not Null because it will raise a KeyError later when i try to access that key. 

1 个答案:

答案 0 :(得分:0)

已经解决。

我通过创建一个if添加密钥。

If 'email' not in user_data.keys(): user_data['email'] = ''

通过添加此键(如果存在任何KeyError),它将添加空字符串。