[英]Link Python script to HTML form
好的,我已經檢查了一些相關的問題,但似乎找不到確切的問題。
基本上,我已經對網站進行了硬編碼,很少使用bootstrap。
我想編寫一個聯系表格,我開始學習Python,因此使用Flask編寫了一個。
現在,由於我編碼了一個單獨的項目,因此該表格與所有html文件都是分開的。
我知道我可以創建一個完整的Flask項目,並通過該應用程序重新定義我的所有html文件,並讓該應用程序為其生成URL,但是就聯系表單而言,這將是很多工作的地獄。
有什么方法可以在HTML中定義表單並使其引用Python Flask腳本?
我真的不知道該怎么做,而且我在Google的任何地方都找不到答案,但那時我可能正在搜索錯誤的內容。
所以,這是我的HTML:
<form action="routes.py" method="post" class="basic-grey">
<label>
<span>Your Name :</span>
<input id="name" type="text" name="name" placeholder="Your Full Name" />
</label>
<label>
<span>Your Email :</span>
<input id="email" type="email" name="email" placeholder="Valid Email Address" />
</label>
<label>
<span>Message :</span>
<textarea id="message" name="message" placeholder="Your Message to Us"></textarea>
</label>
<label>
<span> </span>
<input type="button" class="button" value="Send" />
</label>
</form>
這是Python Flask腳本:
# Imported the Flask class and a function render_template
from flask import Flask, render_template, request, flash
from forms import ContactForm
from flask.ext.mail import Message, Mail
import os
mail = Mail()
# Created an instance/object of the Flask class
app = Flask(__name__)
app.secret_key = os.urandom(24)
# Mapped the URL '/' to the function home().
# Now when someone visits this URL, the function home() will execute.
# This uses a decorator to tell Flask which URL will cause the function below it to execute.
app.config['MAIL_SERVER']='smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USERNAME'] = 'fernindustrials@gmail.com'
app.config['MAIL_PASSWORD'] = 'l3d23pp3l1n'
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
mail.init_app(app)
@app.route('/contact', methods=['GET','POST'])
def contact():
form = ContactForm()
if request.method == 'POST':
if form.validate() == False:
flash('All fields are required.')
return render_template('contact.html', form=form)
else:
msg = Message(form.subject.data, sender='contact@example.com')
msg.recipients = ["fernindustrials@gmail.com"]
msg.body="""
From: %s <%s>
%s
""" % (form.name.data, form.email.data, form.message.data)
mail.send(msg)
return render_template('posted.html')
elif request.method == 'GET':
return render_template('contact.html', form=form)
# Use run() to run our app on a local server.
if __name__ == '__main__':
app.run(debug = True)
為了不違反規則,除非有人需要,否則我不會發布Forms.py文件。
我有什么需要改變或做不同的事情嗎? 可能嗎
另外,腳本在哪里引用index.html文件,即項目結構是什么?
表單標簽中的操作字段應設置為端點,而不是腳本。 這與PHP不同,在PHP中您確實指定了腳本。
因此,您的表單標簽可能如下所示:
<form action="/contact" method="POST" class="basic-grey">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.