1.实验效果
如果插入的数据已经存在于数据库中,则出现以下提示:
查看数据库表中的数据,发现已经将数据存入了数据库表中:
2.主main.py文件
import os from flask_sqlalchemy import SQLAlchemy from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import String,Integer,create_engine,Column from flask import Flask,render_template,redirect,request,url_for,abort,jsonify app=Flask(__name__) class Config: ? ? """相关配置""" ? ? # cmd: ? ? # 创建数据库:create database flaskdb(数据库名) default charset(类型) utf8; ? ? # 使用数据:use flaskdb ? ? # 查看数据库表:show tables; ? ? SQLALCHEMY_DATABASE_URI='mysql+pymysql://root:root@127.0.0.1:3306/flaskdb' ? ? SQLALCHEMY_TRACK_MODIFICATIONS=True app.config.from_object(Config) #创建数据库 mysql=SQLAlchemy(app) #创建表 class Moster(mysql.Model): ? ? """管理员表名""" ? ? __tablename__='moster' ? ? username=Column(String(128),primary_key=True) ? ? password=Column(String(128),unique=True) @app.route('/<string:username>/<string:password>',methods=['POST','GET']) def Insert_User(username,password): ? ? #判断数据库表中是否已经存在了此用户,如果存在,则不进行插入数据 ? ? data=Moster.query.filter(Moster.username==username).all() ? ? if data==[]: ? ? ? ? # 创建对象,进行数据的插入 ? ? ? ? mos = Moster(username=username, password=password) ? ? ? ? # 创建session ? ? ? ? mysql.session.add(mos) ? ? ? ? mysql.session测试数据mit() ? ? ? ? # 关闭数据库 ? ? ? ? mysql.session.close() ? ? ? ? return jsonify('Add the data Successed!') ? ? else: ? ? ? ? return jsonify('The data have been existed!') @app.route('/index',methods=['POST','GET']) def index(): ? ? if request.method=='POST': ? ? ? ? username=request.form.get('username') ? ? ? ? password=request.form.get('password') ? ? ? ? return redirect(url_for('Insert_User',username=username,password=password)) ? ? return render_template('mysql.html') if __name__ == '__main__': ? ? print('Pycharm') ? ? # 对数据库进行清除,让数据库是“干净的” ? ? # mysql.drop_all() ? ? # 创建表 ? ? mysql.create_all() ? ? app.run(debug=True)
3.前端mysql.html文件
<!DOCTYPE html> <html lang="en"> <head> ? ? <meta charset="UTF-8"> ? ? <title>MySQL</title> ? ? <style> ? ? ? ? div { ? ? ? ? ? ? width:250px; ? ? ? ? ? ? height:100px; ? ? ? ? ? ? margin:auto; ? ? ? ? ? ? margin-top:200px; ? ? ? ? ? ? font-size:15px; ? ? ? ? ? ? font-weight:700; ? ? ? ? ? ? border:2px solid #000000; ? ? ? ? ? ? background:#FFFFFF; ? ? ? ? } ? ? ? ? div form input { ? ? ? ? ? ? margin-top:10px; ? ? ? ? } ? ? ? ? .btn{ ? ? ? ? ? ? margin-left:100px; ? ? ? ? ? ? cursor:pointer; ? ? ? ? } ? ? </style> </head> <body> ? ? <div> ? ? ? ? <form action="http://127.0.0.1:5000/index" method="POST"> ? ? ? ? ? ? <label>账号: </label> ? ? ? ? ? ? <input type="text" name="username"><br> ? ? ? ? ? ? <label>密码: </label> ? ? ? ? ? ? <input type="password" name="password"><br> ? ? ? ? ? ? <input class="btn" type="submit" name="submit" value="提交"><br> ? ? ? ? </form> ? ? </div> </body> </html>
到此这篇关于SQLAlchemy使用前端页面实现插入数据的文章就介绍到这了,更多相关SQLAlchemy插入数据内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
查看更多关于python中SQLAlchemy使用前端页面实现插入数据的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did99216