Postgresql 插入到postgres DB:无效的字符串格式(分析异常错误)
我正在创建一个日志数据库,在其中跟踪执行步骤并捕获它可能失败或不失败的地方。 我在插入抛出到DB的异常时遇到问题 我首先调用端点,然后查询django数据库。 在本例中,我希望捕获selection_查询中的一个错误,从而无法从数据库中获取数据。 我想记录这条消息 例如: 异常捕获Postgresql 插入到postgres DB:无效的字符串格式(分析异常错误),postgresql,exception,Postgresql,Exception,我正在创建一个日志数据库,在其中跟踪执行步骤并捕获它可能失败或不失败的地方。 我在插入抛出到DB的异常时遇到问题 我首先调用端点,然后查询django数据库。 在本例中,我希望捕获selection_查询中的一个错误,从而无法从数据库中获取数据。 我想记录这条消息 例如: 异常捕获 try: select_query = "SELECT columnn from row" cur.execute(select_query) selected_vals
try:
select_query = "SELECT columnn from row"
cur.execute(select_query)
selected_vals = cur.fetchall()
except Exception as e:
response = insert_into_logging(message = f"{e}", logging_id = 3)
错误
File "/usr/lib/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
这是因为消息参数中传递的值。
(message=f“{e}”
)
它不能插入数据库中
“e”的值为:
我试图通过
str(e)
repr(e.args[0])
'关系“行”不存在\n行1:从行中选择列\n^\n'
repr(e)
UndefinedTable('关系“行”不存在\n行1:从行中选择列\n^\n',)
还有其他多种方法,但都没有用。
它们都会导致相同的JSONDecodeError
基本上,关键问题是,这不是一种有效的字符串格式,无法在数据库中对其进行解析。
我所需要的只是这个异常的一个表示形式
错误,它才是可插入的
数据流:
插入功能
def insert_into_logging(message, logging_id, date_time):
url = f"""url/insert-into-logging/"""
data = {
"message": message,
"logging_id": logging_id,
}
response = r.post(url, data=json.dumps(data, indent=4, sort_keys=True, default=str))
print(response)
return response.json()
查询数据库
def insert_to_logging(request):
from datetime import datetime, timedelta
if request.method != 'POST':
print(request.method)
return JsonResponse({'status':'error', 'message':'Client insertion only accepts post requests.' + str(request.method)})
today = datetime.today()
body = json.loads(request.body)
message = body.get('message')
logging_id = body.get('logging_id')
Logging.objects.create(message = message, logging_id = logging_id, time_stamp = today)
return JsonResponse({'status':'OK', 'message':'Logging successful'})
Django车型
class Logging(models.Model):
objects = GetOrNoneManager()
message = models.CharField(max_length=64, blank=True, null=True)
logging_id = models.IntegerField(blank=True, null=True)
time_stamp = models.DateTimeField(blank=True, null=True)
class Meta:
db_table = 'logging'
嗯,也许没有叫做
行的表
?是的,我知道,但这不是问题所在。我希望能够在日志数据库中捕捉到这个错误,而不是查询特定的数据库表,而是在另一个数据库中捕捉到这个错误。那是哪种编程语言?编程语言是python
class Logging(models.Model):
objects = GetOrNoneManager()
message = models.CharField(max_length=64, blank=True, null=True)
logging_id = models.IntegerField(blank=True, null=True)
time_stamp = models.DateTimeField(blank=True, null=True)
class Meta:
db_table = 'logging'