如何将数据从我的HTML Flask传递到我的SQLite3数据库(Python)?

huangapple go评论72阅读模式
英文:

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:

&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;link rel=&quot;stylesheet&quot; href=&quot;/static/css/main.css&quot;&gt;
&lt;link rel=&quot;stylesheet&quot;  href=&quot;{{   url_for(&#39;static&#39;,filename=&#39;css/main.css&#39;)   }}&quot;&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;{{url_for(&#39;static&#39;, filename=&#39;script/result.js&#39;)}}&quot;&gt;&lt;/script&gt;
&lt;title&gt;Fen&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;section&gt;
&lt;div class=&quot;form-box&quot;&gt;
&lt;div class=&quot;form-value&quot;&gt;
&lt;form method=&quot;GET&quot; action=&quot;result.html&quot;&gt;
&lt;h2&gt;Add Phone&lt;/h2&gt;
&lt;div class=&quot;inputbox&quot;&gt;
&lt;ion-icon name=&quot;mail-outline&quot;&gt;&lt;/ion-icon&gt;
&lt;input name=&quot;Person Name&quot; id=&quot;Name&quot; type=&quot;text&quot;&gt;
&lt;label for=&quot;&quot;&gt;Name&lt;/label&gt;
&lt;/div&gt;
&lt;div class=&quot;inputbox&quot;&gt;
&lt;ion-icon name=&quot;mail-outline&quot;&gt;&lt;/ion-icon&gt;
&lt;input name=&quot;Phone Name&quot; id=&quot;phone_name&quot; type=&quot;text&quot;&gt;
&lt;label for=&quot;&quot;&gt;Phone Name&lt;/label&gt;
&lt;/div&gt;
&lt;div class=&quot;inputbox&quot;&gt;
&lt;ion-icon name=&quot;lock-closed-outline&quot;&gt;&lt;/ion-icon&gt;
&lt;input name=&quot;Serial Number&quot; type=&quot;text&quot; id=&quot;sr&quot; required&gt;
&lt;label for=&quot;&quot;&gt;serial number&lt;/label&gt;
&lt;/div&gt;   
&lt;div class=&quot;inputbox&quot;&gt;
&lt;ion-icon name=&quot;lock-closed-outline&quot;&gt;&lt;/ion-icon&gt;
&lt;input name=&quot;E-Mail&quot; type=&quot;email&quot; id=&quot;em&quot; required&gt;
&lt;label for=&quot;&quot;&gt;E-mail&lt;/label&gt;
&lt;/div&gt;   
&lt;div class=&quot;inputbox&quot;&gt;
&lt;ion-icon name=&quot;lock-closed-outline&quot;&gt;&lt;/ion-icon&gt;
&lt;input name=&quot;Phone Number&quot; type=&quot;text&quot; id=&quot;pn&quot; required&gt;
&lt;label for=&quot;&quot;&gt;Phone Number&lt;/label&gt;
&lt;/div&gt;
&lt;button id=&quot;log&quot; type=&quot;submit&quot;&gt;Add Phone&lt;/button&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/section&gt;
&lt;script type=&quot;module&quot; src=&quot;https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js&quot;&gt;&lt;/script&gt;
&lt;script nomodule src=&quot;https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
window.addEventListener(&#39;load&#39;, () =&gt; {  
const parms = (new URL(document.location)).searchParams;
const username = parms.get(&#39;Person Name&#39;)
const PhoneName = parms.get(&#39;Phone Name&#39;)
const SerialNumber = parms.get(&#39;Serial Number&#39;)
const Email = parms.get(&#39;E-Mail&#39;)
const PhoneNumber = parms.get(&#39;Phone Number&#39;)
document.getElementById(&#39;name&#39;).innerHTML = username
document.getElementById(&#39;result-name&#39;).innerHTML = PhoneName
document.getElementById(&#39;result-surname&#39;).innerHTML = SerialNumber
document.getElementById(&#39;result-Email&#39;).innerHTML = Email
document.getElementById(&#39;result-number&#39;).innerHTML = PhoneNumber
})
console.log(&#39;welcome&#39;)
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;

and here is my python/flask code:

from flask import *
import sqlite3
app = Flask(__name__)
@app.route(&#39;/&#39;)
def main() :
return render_template(&#39;/Phonebook.html&#39;)
@app.route(&#39;/&#39;, methods = [&#39;POST&#39;])
def phonebook() :
name = request.form[&#39;name&#39;]
phonenumber = request.form[&#39;number&#39;]
connection = sqlite3.connect(&#39;phonebook2.db&#39;)
cursor = connection.cursor()
query1 = &quot;INSERT INTO phonebook2 VALUES ({n},{sn})&quot;.format(n=name,sn=phonenumber)    
cursor.execute(query1)
connection.commit()
@app.route(&#39;/result&#39;,methods = [&#39;GET&#39;])
def result ():
try:
if request.method == &quot;GET&quot;:
name = request.args.get(&#39;name&#39;)
connection = sqlite3.connect(&#39;phonebook2.db&#39;)
cursor = connection.cursor()
query2 = &quot;SELECT number from phonebook2 WHERE Name = {n}&quot;.format(n=name)
result = cursor.execute(query2)
result =  result.fetchall()[0][0]
return render_template(&#39;result.html&#39;, phonenumber = result)
except:
return render_template(&#39;result.html&#39;, phonenumber = &quot;&quot;)
if __name__ == &#39;__main__&#39;:
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)

参考资料

愿您学有所成! 如何将数据从我的HTML Flask传递到我的SQLite3数据库(Python)?

英文:

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 of GET in the html to reach the form submission at the desired route.
  • request.form[&#39;name&#39;] if you would like to read the submitted form data as this, the input element should be like &lt;input name=&quot;name&quot; id=&quot;name&quot; type=&quot;text&quot;&gt;. The input tag field name should match as the key you are trying to get.

See the updated codes

HTML

....
&lt;section&gt;
&lt;div class=&quot;form-box&quot;&gt;
&lt;div class=&quot;form-value&quot;&gt;
&lt;!-- This should be post method and the action should be the desired route --&gt;
&lt;form method=&quot;POST&quot; action=&quot;/&quot;&gt;
&lt;h2&gt;Add Phone&lt;/h2&gt;
&lt;div class=&quot;inputbox&quot;&gt;
&lt;ion-icon name=&quot;mail-outline&quot;&gt;&lt;/ion-icon&gt;
&lt;input name=&quot;name&quot; id=&quot;Name&quot; type=&quot;text&quot;&gt;
&lt;label for=&quot;&quot;&gt;Name&lt;/label&gt;
&lt;/div&gt;
&lt;div class=&quot;inputbox&quot;&gt;
&lt;ion-icon name=&quot;mail-outline&quot;&gt;&lt;/ion-icon&gt;
&lt;input name=&quot;phone_name&quot; id=&quot;phone_name&quot; type=&quot;text&quot;&gt;
&lt;label for=&quot;&quot;&gt;Phone Name&lt;/label&gt;
&lt;/div&gt;
&lt;div class=&quot;inputbox&quot;&gt;
&lt;ion-icon name=&quot;lock-closed-outline&quot;&gt;&lt;/ion-icon&gt;
&lt;input name=&quot;serial_number&quot; type=&quot;text&quot; id=&quot;sr&quot; required&gt;
&lt;label for=&quot;&quot;&gt;serial number&lt;/label&gt;
&lt;/div&gt;   
&lt;div class=&quot;inputbox&quot;&gt;
&lt;ion-icon name=&quot;lock-closed-outline&quot;&gt;&lt;/ion-icon&gt;
&lt;input name=&quot;email&quot; type=&quot;email&quot; id=&quot;em&quot; required&gt;
&lt;label for=&quot;&quot;&gt;E-mail&lt;/label&gt;
&lt;/div&gt;   
&lt;div class=&quot;inputbox&quot;&gt;
&lt;ion-icon name=&quot;lock-closed-outline&quot;&gt;&lt;/ion-icon&gt;
&lt;input name=&quot;number&quot; type=&quot;text&quot; id=&quot;pn&quot; required&gt;
&lt;label for=&quot;&quot;&gt;Phone Number&lt;/label&gt;
&lt;/div&gt;
&lt;button id=&quot;log&quot; type=&quot;submit&quot;&gt;Add Phone&lt;/button&gt;
&lt;/form&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/section&gt;
....

app.py

from flask import *
import sqlite3
app = Flask(__name__)
@app.route(&#39;/&#39;)
def main() :
# This is to create a table if it is not exists
connection = sqlite3.connect(&#39;phonebook2.db&#39;)
cursor = connection.cursor()
create_table_query = &#39;&#39;&#39;
CREATE TABLE IF NOT EXISTS phonebook2 (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
number TEXT
)
&#39;&#39;&#39;
cursor.execute(create_table_query)
connection.commit()
connection.close()
return render_template(&#39;/Phonebook.html&#39;)
@app.route(&#39;/&#39;, methods = [&#39;POST&#39;])
def phonebook() :
name = request.form[&#39;name&#39;]
phonenumber = request.form[&#39;number&#39;]
connection = sqlite3.connect(&#39;phonebook2.db&#39;)
cursor = connection.cursor()
query1 = &quot;INSERT INTO phonebook2 (name,number) VALUES (&#39;{n}&#39;,&#39;{sn}&#39;)&quot;.format(n=name,sn=phonenumber)    
cursor.execute(query1)
connection.commit()
# After submit, redirecting to the result page
return redirect(&quot;/result?name=&quot; + name)
@app.route(&#39;/result&#39;,methods = [&#39;GET&#39;])
def result ():
try:
if request.method == &quot;GET&quot;:
name = request.args.get(&#39;name&#39;)
connection = sqlite3.connect(&#39;phonebook2.db&#39;)
cursor = connection.cursor()
query2 = &quot;SELECT number from phonebook2 WHERE name = &#39;{n}&#39;&quot;.format(n=name)
result = cursor.execute(query2)
result =  result.fetchall()[0][0]
return render_template(&#39;result.html&#39;, phonenumber = result)
except:
return render_template(&#39;result.html&#39;, phonenumber = &quot;&quot;)
if __name__ == &#39;__main__&#39;:
app.run(debug=True)

References

Happy learning.. 如何将数据从我的HTML Flask传递到我的SQLite3数据库(Python)?

huangapple
  • 本文由 发表于 2023年6月22日 12:01:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76528524.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定