In Flask server
# request.form
@app.route('/create', methods=['POST'])
def create():
value1 = request.form.get('field1')
value2 = request.form['file2']
# ... do something with the user data ...
# INSERT INTO mytable (field1, field2) VALUES (value1, value2)
return render_template('index.html')
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Todo app</title>
</head>
<body>
<form method="post" action="/todos/create">
<input type="text" name="description" />
<input type="submit" value="Create" />
</form>
<ul>
{% for d in data %}
<li>
{
{ d.description }}
</li>
{% endfor %}
</ul>
</body>
</html>
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://username@localhost:5432/todoapp'
db = SQLAlchemy(app)
class Todo(db.Model):
__tablename__ = 'todos'
id = db.Column(db.Integer, primary_key=True)
description = db.Column(db.String(), nullable=False)
def __repr__(self):
return f'<Todo {
self.id} {
self.description}>'
# Ensure the tables are created for all the models that we've created and they haven't been created.
db.create_all()
@app.route('/todos/create', methods=['POST'])
def create_todo():
description = request.form.get('description', '')
todo = Todo(description=description)
db.session.add(todo)
db.session.commit()
# index is the name of our route handler that listens to changes on index route.
return redirect(url_for('index'))
@app.route('/')
def index():
return render_template('index.html', data=Todo.query.all())
# 运行命令
FLASK_APP=app.py FLASK_DEBUG=true flask run
结果如下:
当在输入框里输入内容,点击create按钮,就会将输入内容显示在页面上