from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///my_database.db'
db = SQLAlchemy(app)
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80), nullable=False)
@app.route('/form')
def form():
return render_template('form.html')
# 只接受post方法 不接受直接访问
# Method Not Allowed The method is not allowed for the requested URL.
@app.route('/submit', methods=['POST'])
def submit():
name = request.form['name']
user = User(name=name)
db.session.add(user)
db.session.commit()
return f'你好,{name}!已将你的姓名存入数据库。'
if __name__ == '__main__':
# 在 Flask 的应用上下文 app_context() 调用 db.create_all()
with app.app_context():
db.create_all()
app.run()
https://zhuanlan.zhihu.com/p/624750458
标签:__,初体验,name,form,Flask,app,db,context From: https://blog.51cto.com/u_16055028/9028251