gpt4 book ai didi

python - Django:如何在语法错误上向用户获取模板调试信息

转载 作者:行者123 更新时间:2023-11-28 19:25:24 26 4
gpt4 key购买 nike

我有一个页面,用户可以在其中将自己的模板提交到文本区域中,现在它需要这么简单。然而,由于它是用户生成的输入,我需要验证他们不会做破坏我应用程序其余部分的事情,同时如果他们做错了什么,就他们做错了什么提供有用的反馈。

为了提供有用的反馈,我想要一些类似于 django 为我提供的东西(使用 django 1.4):

enter image description here

特别是上面的一点。我将用户模板放在 django 模板中,这样我就不必自己验证语法错误和填充内容。看起来像这样:

try:
template = get_template_from_string(user_input)
template.render(context=Context())
except:
do something to ouptut the error

需要渲染调用,否则根本不会抛出异常。

我试过打印异常及其参数,但这只提供了非常有限的信息。我也尝试过使用 traceback,但它从不返回行号或模板中的任何内容,只返回到 python 代码中抛出异常的位置。我也无法使用 Google 找到任何东西,我通过 Django 源代码的搜索让我想知道实际错误页面是在哪里生成的......


所以基本上我的问题是;我如何获得图像中显示的信息位?

编辑澄清一下:我希望用户能够制作模板,以便在发送电子邮件时可以使用这些模板。由于 Django 模板引擎已经存在,我想我会使用那个而不是其他东西。

模板本身使用 this 变得安全片段和我自己对变量的一些解析。到目前为止,除了对用户有用的调试消息外,一切正常。到目前为止,我所知道的是:“解析您的模板时出现问题,意外的 block 标记扩展”(例如),我希望它更像上面显示的图像。

最佳答案

我刚遇到同样的问题。在我的例子中,不需要有这样的细节回溯。所以我这样做了,使用模型清理方法

from django.core.exceptions import ValidationError
from django.core.urlresolvers import NoReverseMatch
from django.db import models
from django.template.base import Template, TemplateSyntaxError
from django.template.context import Context

class MyTemplate(models.Model):
template = models.TextField()

def clean(self):
try:
Template(self.tempalte).render(Context({}))
except TemplateSyntaxError as tse:
raise ValidationError('TemplateSyntaxError: %s' % tse)
except NoReverseMatch as nrm:
raise ValidationError('NoReverseMatch: %s' % nrm)

关于python - Django:如何在语法错误上向用户获取模板调试信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14537097/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com