Python%操作时的字符问题(转义字符问题)

发布于 2024-11-27 21:09:33 字数 839 浏览 1 评论 0原文

我尝试在 Django 中发送确认电子邮件,但 excape 字符出现问题。

我有一个用于邮件内容的辅助函数,

def getActivationMailBody():
    email_body = "<table width='100%'>
    email_body = email_body + '<p>' + '%(confirmLink)s' + '</p>'
    return email_body

并且嵌入了确认网址,例如

email_body = getActivationMailBody()
email_body = email_body % {'confirmLink': '%s/kullanici/onay/%s/%s'%(WEB_URL,md5.new(form.cleaned_data['email']).hexdigest()[:30], activation_key)}
msg = EmailMessage(email_subject, email_body, DEFAULT_FROM_EMAIL, [email_to]) 
msg.content_subtype="html"
res = msg.send(fail_silently=False)

但是,在嵌入 confirmLink 时,我收到错误,因为

unsupported format character ''' (0x27) at index 18

我发现问题是由 % 字符,但我不知道如何纠正它。

你能给我什么建议吗?谢谢

I try to send a confirmation email in Django but there is a problem with excape characters.

I have a helper function for content of mail as

def getActivationMailBody():
    email_body = "<table width='100%'>
    email_body = email_body + '<p>' + '%(confirmLink)s' + '</p>'
    return email_body

And the confirmation url is embedded like

email_body = getActivationMailBody()
email_body = email_body % {'confirmLink': '%s/kullanici/onay/%s/%s'%(WEB_URL,md5.new(form.cleaned_data['email']).hexdigest()[:30], activation_key)}
msg = EmailMessage(email_subject, email_body, DEFAULT_FROM_EMAIL, [email_to]) 
msg.content_subtype="html"
res = msg.send(fail_silently=False)

However, while the confirmLink embedding I get an error as

unsupported format character ''' (0x27) at index 18

I found that the problem is caused by % character but I couldn't figure out how can I correct that.

Could you give me any suggestion ? Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酒与心事 2024-12-04 21:09:33

在格式字符串中,% 可以通过加倍来转义:

email_body = "<table width='100%%'>"

您的构造方式有点奇怪,因为 getActivationEmailBody 不返回电子邮件的正文,而是返回用于创建正文的格式字符串。您可能想要重命名该函数。

In a format string, a % can be escaped by doubling:

email_body = "<table width='100%%'>"

It's a little odd how you've constructed this, since getActivationEmailBody isn't returning the body of the email, but instead a format string to create the body. You might want to rename the function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文