英文:
How do I pass data from my html flask to my sqlite3 database(python)
问题
我正在尝试制作一个应用程序,用户输入一些信息,我需要将这些信息发送到我的数据库和另一个页面(结果页面),它将显示已发送的信息。我已经不知道它发送到哪个页面,我在尝试将数据发送到我的数据库时遇到了问题,我希望只发送手机名称和序列号到数据库。
以下是我的HTML代码:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="/static/css/main.css">
<link rel="stylesheet" href="{{ url_for('static',filename='css/main.css') }}">
<script type="text/javascript" src="{{url_for('static', filename='script/result.js')}}"></script>
<title>Fen</title>
</head>
<body>
<section>
<div class="form-box">
<div class="form-value">
<form method="GET" action="result.html">
<h2>Add Phone</h2>
<div class="inputbox">
<ion-icon name="mail-outline"></ion-icon>
<input name="Person Name" id="Name" type="text">
<label for="">Name</label>
</div>
<div class="inputbox">
<ion-icon name="mail-outline"></ion-icon>
<input name="Phone Name" id="phone_name" type="text">
<label for="">Phone Name</label>
</div>
<div class="inputbox">
<ion-icon name="lock-closed-outline"></ion-icon>
<input name="Serial Number" type="text" id="sr" required>
<label for="">serial number</label>
</div>
<div class="inputbox">
<ion-icon name="lock-closed-outline"></ion-icon>
<input name="E-Mail" type="email" id="em" required>
<label for="">E-mail</label>
</div>
<div class="inputbox">
<ion-icon name="lock-closed-outline"></ion-icon>
<input name="Phone Number" type="text" id="pn" required>
<label for="">Phone Number</label>
</div>
<button id="log" type="submit">Add Phone</button>
</form>
</div>
</div>
</section>
<script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script>
<script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script>
<script>
window.addEventListener('load', () => {
const parms = (new URL(document.location)).searchParams;
const username = parms.get('Person Name')
const PhoneName = parms.get('Phone Name')
const SerialNumber = parms.get('Serial Number')
const Email = parms.get('E-Mail')
const PhoneNumber = parms.get('Phone Number')
document.getElementById('name').innerHTML = username
document.getElementById('result-name').innerHTML = PhoneName
document.getElementById('result-surname').innerHTML = SerialNumber
document.getElementById('result-Email').innerHTML = Email
document.getElementById('result-number').innerHTML = PhoneNumber
})
console.log('welcome')
</script>
</body>
</html>
这是我的Python/Flask代码:
from flask import *
import sqlite3
app = Flask(__name__)
@app.route('/')
def main() :
return render_template('/Phonebook.html')
@app.route('/', methods = ['POST'])
def phonebook() :
name = request.form['name']
phonenumber = request.form['number']
connection = sqlite3.connect('phonebook2.db')
cursor = connection.cursor()
query1 = "INSERT INTO phonebook2 VALUES ('{n}','{sn}')".format(n=name,sn=phonenumber)
cursor.execute(query1)
connection.commit()
@app.route('/result',methods = ['GET'])
def result ():
try:
if request.method == "GET":
name = request.args.get('name')
connection = sqlite3.connect('phonebook2.db')
cursor = connection.cursor()
query2 = "SELECT number from phonebook2 WHERE Name = '{n}'".format(n=name)
result = cursor.execute(query2)
result = result.fetchall()[0][0]
return render_template('result.html', phonenumber = result)
except:
return render_template('result.html', phonenumber = "")
if __name__ == '__main__':
app.run(debug=True)
我尝试了一些方法,但没有成功,而且这是我第一次使用Flask和SQLite3,我只了解一些基础知识。感谢您花时间查看我的代码。
英文:
I am trying to make an app where the user put's in a couple of inputs and i need the inputs to go to my database and my other page which is results which will show it i already don't where it sends to the other page i am having a problem trying to send the data to my database and i want it to send the Phone Name and serial number to the database only.
Here Is My HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="/static/css/main.css">
<link rel="stylesheet" href="{{ url_for('static',filename='css/main.css') }}">
<script type="text/javascript" src="{{url_for('static', filename='script/result.js')}}"></script>
<title>Fen</title>
</head>
<body>
<section>
<div class="form-box">
<div class="form-value">
<form method="GET" action="result.html">
<h2>Add Phone</h2>
<div class="inputbox">
<ion-icon name="mail-outline"></ion-icon>
<input name="Person Name" id="Name" type="text">
<label for="">Name</label>
</div>
<div class="inputbox">
<ion-icon name="mail-outline"></ion-icon>
<input name="Phone Name" id="phone_name" type="text">
<label for="">Phone Name</label>
</div>
<div class="inputbox">
<ion-icon name="lock-closed-outline"></ion-icon>
<input name="Serial Number" type="text" id="sr" required>
<label for="">serial number</label>
</div>
<div class="inputbox">
<ion-icon name="lock-closed-outline"></ion-icon>
<input name="E-Mail" type="email" id="em" required>
<label for="">E-mail</label>
</div>
<div class="inputbox">
<ion-icon name="lock-closed-outline"></ion-icon>
<input name="Phone Number" type="text" id="pn" required>
<label for="">Phone Number</label>
</div>
<button id="log" type="submit">Add Phone</button>
</form>
</div>
</div>
</section>
<script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script>
<script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script>
<script>
window.addEventListener('load', () => {
const parms = (new URL(document.location)).searchParams;
const username = parms.get('Person Name')
const PhoneName = parms.get('Phone Name')
const SerialNumber = parms.get('Serial Number')
const Email = parms.get('E-Mail')
const PhoneNumber = parms.get('Phone Number')
document.getElementById('name').innerHTML = username
document.getElementById('result-name').innerHTML = PhoneName
document.getElementById('result-surname').innerHTML = SerialNumber
document.getElementById('result-Email').innerHTML = Email
document.getElementById('result-number').innerHTML = PhoneNumber
})
console.log('welcome')
</script>
</body>
</html>
and here is my python/flask code:
from flask import *
import sqlite3
app = Flask(__name__)
@app.route('/')
def main() :
return render_template('/Phonebook.html')
@app.route('/', methods = ['POST'])
def phonebook() :
name = request.form['name']
phonenumber = request.form['number']
connection = sqlite3.connect('phonebook2.db')
cursor = connection.cursor()
query1 = "INSERT INTO phonebook2 VALUES ({n},{sn})".format(n=name,sn=phonenumber)
cursor.execute(query1)
connection.commit()
@app.route('/result',methods = ['GET'])
def result ():
try:
if request.method == "GET":
name = request.args.get('name')
connection = sqlite3.connect('phonebook2.db')
cursor = connection.cursor()
query2 = "SELECT number from phonebook2 WHERE Name = {n}".format(n=name)
result = cursor.execute(query2)
result = result.fetchall()[0][0]
return render_template('result.html', phonenumber = result)
except:
return render_template('result.html', phonenumber = "")
if __name__ == '__main__':
app.run(debug=True)
I Tried some things but it didn't work and also it's my first time using flask and sqlite3 i know bit of the basics about them
thank you for taking the time to look at my code
答案1
得分: 0
我感谢您为学习这个并尝试的解决方案所付出的努力。它仍然需要一些改进。
需要更改的事项
- 您必须在
phonebook2.db
中创建一个新表来存储信息。 - 在HTML中,应该定义
POST
而不是GET
以达到在所需路由上提交表单。 - 如果您想要读取提交的表单数据,应该使用
request.form['name']
,输入元素应该像这样:<input name="name" id="name" type="text">
。输入标签字段名称应该与您尝试获取的键匹配。
查看更新后的代码
HTML
....
<section>
<div class="form-box">
<div class="form-value">
<!-- 这应该是POST方法,动作应该是所需的路由 -->
<form method="POST" action="/">
<h2>Add Phone</h2>
<div class="inputbox">
<ion-icon name="mail-outline"></ion-icon>
<input name="name" id="Name" type="text">
<label for=""></label>
</div>
<div class="inputbox">
<ion-icon name="mail-outline"></ion-icon>
<input name="phone_name" id="phone_name" type="text">
<label for=""></label>
</div>
<div class="inputbox">
<ion-icon name="lock-closed-outline"></ion-icon>
<input name="serial_number" type="text" id="sr" required>
<label for=""></label>
</div>
<div class="inputbox">
<ion-icon name="lock-closed-outline"></ion-icon>
<input name="email" type="email" id="em" required>
<label for=""></label>
</div>
<div class="inputbox">
<ion-icon name="lock-closed-outline"></ion-icon>
<input name="number" type="text" id="pn" required>
<label for=""></label>
</div>
<button id="log" type="submit">Add Phone</button>
</form>
</div>
</div>
</section>
....
app.py
from flask import *
import sqlite3
app = Flask(__name__)
@app.route('/')
def main():
# 如果不存在表,则创建一个表
connection = sqlite3.connect('phonebook2.db')
cursor = connection.cursor()
create_table_query = '''
CREATE TABLE IF NOT EXISTS phonebook2 (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
number TEXT
)
'''
cursor.execute(create_table_query)
connection.commit()
connection.close()
return render_template('/Phonebook.html')
@app.route('/', methods=['POST'])
def phonebook():
name = request.form['name']
phonenumber = request.form['number']
connection = sqlite3.connect('phonebook2.db')
cursor = connection.cursor()
query1 = "INSERT INTO phonebook2 (name, number) VALUES ('{n}', '{sn}')".format(n=name, sn=phonenumber)
cursor.execute(query1)
connection.commit()
# 提交后,重定向到结果页面
return redirect("/result?name=" + name)
@app.route('/result', methods=['GET'])
def result():
try:
if request.method == "GET":
name = request.args.get('name')
connection = sqlite3.connect('phonebook2.db')
cursor = connection.cursor()
query2 = "SELECT number from phonebook2 WHERE name = '{n}'".format(n=name)
result = cursor.execute(query2)
result = result.fetchall()[0][0]
return render_template('result.html', phonenumber=result)
except:
return render_template('result.html', phonenumber="")
if __name__ == '__main__':
app.run(debug=True)
参考资料
愿您学有所成!
英文:
I appreciate the effort you took for learning this and solutions you tried.It still needs some refinements.
Things to change
- You have to create a new table in
phonebook2.db
to store the information. - You should define
POST
instead ofGET
in the html to reach the form submission at the desired route. request.form['name']
if you would like to read the submitted form data as this, the input element should be like<input name="name" id="name" type="text">
. The input tag field name should match as the key you are trying to get.
See the updated codes
HTML
....
<section>
<div class="form-box">
<div class="form-value">
<!-- This should be post method and the action should be the desired route -->
<form method="POST" action="/">
<h2>Add Phone</h2>
<div class="inputbox">
<ion-icon name="mail-outline"></ion-icon>
<input name="name" id="Name" type="text">
<label for="">Name</label>
</div>
<div class="inputbox">
<ion-icon name="mail-outline"></ion-icon>
<input name="phone_name" id="phone_name" type="text">
<label for="">Phone Name</label>
</div>
<div class="inputbox">
<ion-icon name="lock-closed-outline"></ion-icon>
<input name="serial_number" type="text" id="sr" required>
<label for="">serial number</label>
</div>
<div class="inputbox">
<ion-icon name="lock-closed-outline"></ion-icon>
<input name="email" type="email" id="em" required>
<label for="">E-mail</label>
</div>
<div class="inputbox">
<ion-icon name="lock-closed-outline"></ion-icon>
<input name="number" type="text" id="pn" required>
<label for="">Phone Number</label>
</div>
<button id="log" type="submit">Add Phone</button>
</form>
</div>
</div>
</section>
....
app.py
from flask import *
import sqlite3
app = Flask(__name__)
@app.route('/')
def main() :
# This is to create a table if it is not exists
connection = sqlite3.connect('phonebook2.db')
cursor = connection.cursor()
create_table_query = '''
CREATE TABLE IF NOT EXISTS phonebook2 (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
number TEXT
)
'''
cursor.execute(create_table_query)
connection.commit()
connection.close()
return render_template('/Phonebook.html')
@app.route('/', methods = ['POST'])
def phonebook() :
name = request.form['name']
phonenumber = request.form['number']
connection = sqlite3.connect('phonebook2.db')
cursor = connection.cursor()
query1 = "INSERT INTO phonebook2 (name,number) VALUES ('{n}','{sn}')".format(n=name,sn=phonenumber)
cursor.execute(query1)
connection.commit()
# After submit, redirecting to the result page
return redirect("/result?name=" + name)
@app.route('/result',methods = ['GET'])
def result ():
try:
if request.method == "GET":
name = request.args.get('name')
connection = sqlite3.connect('phonebook2.db')
cursor = connection.cursor()
query2 = "SELECT number from phonebook2 WHERE name = '{n}'".format(n=name)
result = cursor.execute(query2)
result = result.fetchall()[0][0]
return render_template('result.html', phonenumber = result)
except:
return render_template('result.html', phonenumber = "")
if __name__ == '__main__':
app.run(debug=True)
References
Happy learning..
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论