Flask_SQLite_HTML_Form_Notes
Flask_SQLite_HTML_Form_Notes
---------------------------------
import sqlite3
conn = sqlite3.connect("mydatabase.db")
cursor = conn.cursor()
# Create a table
cursor.execute('''
''')
conn.commit()
conn.close()
-----------------------------------
import sqlite3
app = Flask(__name__)
conn = sqlite3.connect('mydatabase.db')
conn.row_factory = sqlite3.Row
return conn
--------------------------------------------------------------
<html>
<body>
<h2>Add User</h2>
</form>
<br>
</body>
</html>
----------------------------
@app.route('/')
def form():
return render_template('form.html')
@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()
------------------------------------
@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
7. Running the Flask App
------------------------
if __name__ == '__main__':
app.run(debug=True)
Explanation:
------------
- You can view the stored data in an HTML table using another Flask route.
Make sure you have a 'templates' folder in the same directory as your Python file. Inside it, save the
form.html file.