Flask_SQLite_HTML_Explained_Notes
Flask_SQLite_HTML_Explained_Notes
This guide will help you build a simple web app where:
- You can view all submitted records in a table on another web page.
---------------------------------
import sqlite3
conn = sqlite3.connect("mydatabase.db")
cursor = conn.cursor()
cursor.execute('''
''')
conn.commit()
conn.close()
2. Creating a Flask Application
-------------------------------
Flask is a web framework that allows you to create web apps using Python.
import sqlite3
app = Flask(__name__)
def get_db_connection():
conn = sqlite3.connect('mydatabase.db')
return conn
----------------------------------------------------
You need a folder named "templates" in the same location as your Python file.
Inside it, create a file called form.html with the following code:
<html>
<body>
<h2>Add User</h2>
</form>
<br>
</body>
</html>
-------------------------------------
@app.route('/')
def form():
return render_template('form.html')
Explanation:
When you visit http://127.0.0.1:5000/, this function runs and displays the HTML form.
----------------------------------
@app.route('/add_user', methods=['POST'])
def add_user():
name = request.form['name']
age = request.form['age']
conn = get_db_connection()
conn.execute("INSERT INTO users (name, age) VALUES (?, ?)", (name, age))
conn.commit()
conn.close()
return "User added successfully! <a href='/'>Add Another</a>"
Explanation:
- Data is inserted into the database with parameterized SQL to prevent injection.
-------------------------------
@app.route('/users')
def users():
conn = get_db_connection()
conn.close()
html += f"<tr><td>{row['id']}</td><td>{row['name']}</td><td>{row['age']}</td></tr>"
return html
Explanation:
if __name__ == '__main__':
app.run(debug=True)
Conclusion:
-----------
- You now have a working web app that uses HTML + Python to input and store data.
- You can expand this with update/delete functions and even user login.