如何在Sphinx构建的网站中添加在线表单?
可用的Sphinx扩展与实现方案
1. sphinxcontrib-forms
这是专门为Sphinx设计的表单扩展,支持在文档中嵌入可自定义的HTML表单:
- 能定义必填字段(比如电子邮箱)、文本输入框等,还可配置表单的提交动作。
- 在
conf.py中启用扩展:extensions = [ # 其他已启用的扩展 'sphinxcontrib.forms', ] - 在rst文档中编写表单:
.. form:: user_feedback :action: /handle_feedback :method: post .. field:: email :type: email :required: yes :label: 电子邮箱 .. field:: question1 :type: text :label: 问题1 .. field:: question2 :type: text :label: 问题2 .. button:: submit_btn :type: submit :value: 提交验证 - 表单提交后的邮件发送需要你自己编写后端逻辑,比如用Flask写一个视图函数接收数据,通过
smtplib格式化并发送邮件。
2. 自定义HTML嵌入 + 后端脚本
如果扩展满足不了需求,直接在rst中嵌入原生HTML表单也是可行的:
.. raw:: html <form action="/send_feedback.py" method="post" id="feedback-form"> <div> <label for="email">电子邮箱(必填):</label> <input type="email" id="email" name="email" required> </div> <div> <label for="q1">问题1:</label> <input type="text" id="q1" name="question1"> </div> <div> <label for="q2">问题2:</label> <input type="text" id="q2" name="question2"> </div> <button type="submit">提交验证</button> </form>
然后编写Python后端脚本send_feedback.py处理提交:
#!/usr/bin/env python3 import cgi import smtplib from email.mime.text import MIMEText # 获取表单数据 form_data = cgi.FieldStorage() user_email = form_data.getvalue('email', '') q1 = form_data.getvalue('question1', '') q2 = form_data.getvalue('question2', '') # 格式化邮件内容 email_content = f"用户反馈信息:\n电子邮箱: {user_email}\n问题1: {q1}\n问题2: {q2}" # 配置邮件发送参数 msg = MIMEText(email_content, 'plain', 'utf-8') msg['Subject'] = 'Sphinx网站用户反馈' msg['From'] = 'your-sender-email@example.com' msg['To'] = 'your-recipient-email@example.com' # 发送邮件 try: with smtplib.SMTP('smtp.example.com', 587) as smtp_server: smtp_server.starttls() smtp_server.login('your-sender-email@example.com', 'your-email-password') smtp_server.send_message(msg) # 返回成功响应 print("Content-Type: text/html; charset=utf-8") print() print("<html><body><h3>提交成功!感谢你的反馈。</h3></body></html>") except Exception as e: print("Content-Type: text/html; charset=utf-8") print() print(f"<html><body><h3>提交失败,请稍后重试。错误信息: {str(e)}</h3></body></html>")
注意要将脚本部署到网站的可执行目录,并确保服务器支持CGI或WSGI运行环境。
3. 第三方表单服务嵌入(备选方案)
如果不想自己开发后端,可以用第三方表单服务创建表单,然后在Sphinx页面中嵌入iframe:
.. raw:: html <iframe src="https://your-third-party-form-url" width="100%" height="600" frameborder="0" marginheight="0" marginwidth="0">加载中...</iframe>
这类服务会自动处理表单验证和邮件发送,无需自己编写代码,但样式自定义程度有限,且依赖第三方平台。
内容的提问来源于stack exchange,提问作者Mathieu
相关产品推荐
相关产品推荐

