我正在使用Django Rest Framework在现有数据库上执行get()post()。在这些模型中,我没有定义任何主键或外键关系,因为这些约束是在数据库级别处理的。当我在settings.py文件中有debug = True
时,将显示带有追溯的数据库级错误。但是,当debug = False时,我希望在响应中显示错误。
例如:错误消息:
IntegrityError at /dqf_api/ReceiptLog/
(1062, "Duplicate entry 'ede pivot-dummy-ede_case_76-ede pivot command 76' for key 'PRIMARY'")
当debug = True时,将显示此内容。当debug = False时,如何捕捉并显示此错误?
编辑:包括代码模块
models.py
class TestCaseCommandRun(models.Model):
# fields ..Doesn't have id field as the database doesn't have it
class Meta:
managed = False
db_table = 'test_case_command_run'
unique_together = (('team_name', 'suite_name', 'suite_run_id', 'case_name', 'command_name'),)
class TestCaseCommandRunResults(models.Model):
# fields ..Doesn't have id field as the database doesn't have it
class Meta:
managed = False
db_table = 'test_case_command_run_results'
unique_together = (('suite_run_id', 'command_run_id', 'rule_name', 'result_id'),)
views.py
class TestCaseCommandRunViewSet(viewsets.ModelViewSet):
queryset = models.TestCaseCommandRunViewSet.objects.values('team_name','suite_name','suite_run_id', 'case_name','command_name','command_run_id','run_start','run_end','result','run_status')
serializer_class = serializers.TestCaseCommandRunViewSet
class TestCaseCommandRunResultsViewSet(viewsets.ModelViewSet):
queryset = models.TestCaseCommandRunResultsViewSet.objects.values('suite_run_id','command_run_id','rule_name', 'result_id',
'result','expected_values','actual_values','report_values','extended_values')
serializer_class = serializers.TestCaseCommandRunResultsViewSet
class ReceiptLogViewSet(CreateAPIView):
serializer_class = serializers.ReceiptLogSerializer.ReceiptLogSerializerClass
serializers.py
class TestCaseCommandRunResultsViewSet(serializers.ModelSerializer):
class Meta:
model = models.TestCaseCommandRunResultsViewSet
fields = ['suite_run_id','command_run_id','rule_name', 'result_id','result','expected_values','actual_values','report_values','extended_values']
class TestCaseCommandRunSerializer(serializers.ModelSerializer):
class Meta:
model = models.TestCaseCommandRunSerializer
fields = ['team_name','suite_name','suite_run_id', 'case_name','command_name','command_run_id','run_start','run_end','result','run_status']
class ReceiptLogSerializerClass(serializers.Serializer):
team_name = serializers.CharField(max_length=30)
suite_name = serializers.CharField(max_length=100)
suite_run_id = serializers.CharField(max_length=50,required=False, allow_blank=True, default=datetime.now().strftime('%Y%m%d%H%M%S'))
case_name = serializers.CharField(max_length=50)
command_name = serializers.CharField(max_length=50)
command_run_id = serializers.CharField(max_length=50,required=False, allow_blank=True, default='Not Applicable')
run_start = serializers.DateTimeField(default=datetime.now, required=False)
run_end = serializers.DateTimeField(default=datetime.now, required=False)
result = serializers.CharField(max_length=10, default='Not Applicable')
run_status = serializers.CharField(max_length=10)
rule_name = serializers.CharField( max_length=50, required=False, allow_blank=True, default='Not Applicable')
expected_values = serializers.CharField(max_length=200, allow_blank=True)
actual_values = serializers.CharField(max_length=200, allow_blank=True)
report_values = serializers.CharField(max_length=200, allow_blank=True)
extended_values = serializers.CharField(max_length=200, allow_blank=True)
def create(self, validated_data):
team_name = validated_data.get('team_name', None)
suite_name = validated_data.get('suite_name', None)
suite_run_id = validated_data.get('suite_run_id', None)
case_name = validated_data.get('case_name', None)
command_name = validated_data.get('command_name', None)
command_run_id = validated_data.get('command_run_id', None)
run_start = validated_data.get('run_start', None)
run_end = validated_data.get('run_end', None)
result = validated_data.get('result', None)
run_status = validated_data.get('run_status', None)
rule_name = validated_data.get('rule_name', None)
expected_values = validated_data.get('expected_values', None)
actual_values = validated_data.get('actual_values', None)
report_values = validated_data.get('report_values', None)
extended_values = validated_data.get('extended_values', None)
test_case_command_run_data = {
'team_name': team_name,
'suite_name': suite_name,
'suite_run_id': suite_run_id,
'case_name': case_name,
'command_name': command_name,
'command_run_id': command_run_id,
'run_start': run_start,
'run_end': run_end,
'result': result,
'run_status': run_status
}
TestCaseCommandRunSerializer.create(TestCaseCommandRunSerializer(), validated_data=test_case_command_run_data)
test_case_command_run_result_data = {
'suite_run_id': suite_run_id,
'command_run_id': command_run_id,
'rule_name': rule_name,
'result_id': self.result_id,
'result': result,
'expected_values': expected_values,
'actual_values': actual_values,
'report_values': report_values,
'extended_values': extended_values,
}
TestCaseCommandRunResultsSerializer.create(TestCaseCommandRunResultsSerializer(), validated_data=test_case_command_run_result_data)
self.result_id += 1
return validated_data
urls.py
router = routers.DefaultRouter()
router.register(r'test_case_command_runs', views.TestCaseCommandRunViewSet)
router.register(r'test_case_command_run_results', views.TestCaseCommandRunResultsViewSet)
urlpatterns = [
url(r'^dqf_api/', include(router.urls)),
url(r'^dqf_api/ReceiptLog/', views.ReceiptLogView.ReceiptLogViewSet.as_view(), name='ReceiptLog')]
编辑:代码修复
将此添加到serializers.py
def create(self, validated_data):
try:
return super().create(validated_data)
except IntegrityError as e:
error_msg = "IntegrityError occurred while creating entry in test_case_command_run_result model. Detailed Error: %s" %e
raise serializers.ValidationError(error_msg)
答案 0 :(得分:0)
使用try catch语句
在views.py
class TestCaseCommandRunViewSet(viewsets.ModelViewSet):
try:
queryset = models.TestCaseCommandRunViewSet.objects.values('team_name','suite_name','suite_run_id', 'case_name','command_name','command_run_id','run_start','run_end','result','run_status')
serializer_class = serializers.TestCaseCommandRunViewSet
return Response("working")
except Exception as e:
return Response(e)
class TestCaseCommandRunResultsViewSet(viewsets.ModelViewSet):
try:
queryset = models.TestCaseCommandRunResultsViewSet.objects.values('suite_run_id','command_run_id','rule_name','result_id','result','expected_values','actual_values','report_values','extended_values')
serializer_class = serializers.TestCaseCommandRunResultsViewSet
retutn Response("Working")
except Exception as e:
return Response(e)
class ReceiptLogViewSet(CreateAPIView):
try:
serializer_class = serializers.ReceiptLogSerializer.ReceiptLogSerializerClass
return Response("working")
except Exception as e:
return Response(e)
答案 1 :(得分:0)
也许尝试这样的事情:
if serializer.is_valid():
serializer.save()
return Response("success")
else:
return Response(serialzier.errors)