write flask app, input and output to browser, html input to sqlite, python retrieve data to html, include all file names, and where to store those files, write simple sample codes
Here's a simple Flask app that takes an input from an HTML form, stores it in a SQLite database, retrieves the data from the database and displays it in the browser.
File names and locations:
- app.py: the Python file containing the Flask app
- index.html: the HTML file containing the input form
- database.db: the SQLite database file
app.py:
from flask import Flask, render_template, request
import sqlite3
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/submit', methods=['POST'])
def submit():
name = request.form['name']
email = request.form['email']
conn = sqlite3.connect('database.db')
c = conn.cursor()
c.execute("INSERT INTO users (name, email) VALUES (?, ?)", (name, email))
conn.commit()
conn.close()
return 'Data stored successfully'
@app.route('/users')
def users():
conn = sqlite3.connect('database.db')
c = conn.cursor()
c.execute("SELECT * FROM users")
data = c.fetchall()
conn.close()
return render_template('users.html', data=data)
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Flask App</title>
</head>
<body>
<form action="/submit" method="POST">
<label>Name:</label>
<input type="text" name="name"><br>
<label>Email:</label>
<input type="email" name="email"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
users.html:
<!DOCTYPE html>
<html>
<head>
<title>Flask App</title>
</head>
<body>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
{% for row in data %}
<tr>
<td>{{ row[1] }}</td>
<td>{{ row[2] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
To run the app, save the above code in separate files with the specified names and locations. Then run the following command in the terminal:
export FLASK_APP=app.py
flask run
This will start the Flask development server running on http://localhost:5000. Open that URL in a web browser to see the homepage with the input form. Submit some data and then go to http://localhost:5000/users to see the data displayed in a table.
原文地址: https://www.cveoy.top/t/topic/qFu 著作权归作者所有。请勿转载和采集!