总共写了4个文件:
一个主程序demo.py
一写测试数据脚本(直接在终端执行添加测试数据)
一个用来添加数据html文件,login.html
一个用来展示数据的html文件,index.html
写的很low的,临时写的,还有很多不用要的,比如manager,已开始写上去准备命令执行已有数据库的迁移,但是从新创建了一个模型类做简单的操作所以用不到,可以删掉的。而且什么验证都没做,添加数据最好添加有效的数据呀(如 zhangsan 28),用的是form表单提交数据
主程序:
from flask import Flask, render_template from flask import request from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate,MigrateCommand from flask_script import Shell,Manager app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://root:mysql@127.0.0.1:3306/xx" app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True app.config['WTF_CSRF_ENABLED'] = False db = SQLAlchemy(app) migrate = Migrate(app,db) manager = Manager(app) manager.add_command('db',MigrateCommand) class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(64), unique=True, index=True) age = db.Column(db.Integer, default=18) def __repr__(self): return 'User:%s'%self.name @app.route('/') def demo(): user = User.query.first() name = user.name age = user.age data = { "name": name, "age": age } return render_template("index.html", data=data) @app.route('/login', methods=["GET", "POST"]) def login(): if request.method == "POST": username = request.form.get("username") userage = request.form.get("userage") user = User(name=username, age=userage) db.session.add(user) db.session.commit() return render_template("login.html") if __name__ == '__main__': db.create_all() app.run(debug=True) manager.run()
测试数据:
- from .demo import *
- user_a = User(name='mayun', age=23)
- user_b = User(name='laoma', age=40)
- db.session.add_all([user_a, user_b])
- db.session.commit()
测试数据是在主程序所在虚拟环境目录下的中终端启用ipython执行即可
然后就是和主程序同目录下创建的templates模板文件下的两个html文件
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <table border="1"> <tr> <th>姓名</th> <th>年龄</th> </tr> <tr> <td>{{ data.name }}</td> <td>{{ data.age }}</td> </tr> </table> </body> </html>
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Xiaotaotao</title> </head> <body> <form method="post"> <label>姓名:</label><input type="text" name="username" placeholder="请输入姓名"><br/> <label>年纪:</label><input type="password" name="userage" placeholder="请输入年纪"><br/> <input type="submit" value="提交"> </form> </body> </html>
效果图:查询和数据库渲染到页面和从页面添加数据到数据库都OK
联系客服