欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

flask 框架操作MySQL数据库简单示例

时间:2020-12-07 17:47:15|栏目:Python代码|点击:

本文实例讲述了flask 框架操作MySQL数据库。分享给大家供大家参考,具体如下:

一、创建数据库表格

"""
Created on 19-10-8
@requirement:Anaconda 4.3.0 (64-bit) Python3.6
@description:创建表格
"""
import pymysql
server = '127.0.0.1'
user = 'root'
password = 'password'
# 连接数据库
conn = pymysql.connect(server, user, password, database='information_collection') # 获取连接
cursor = conn.cursor() # 获取游标
# "**ENGINE=InnoDB DEFAULT CHARSET=utf8**"-创建表的过程中增加这条,中文就不是乱码
# 创建表
cursor.execute("""
CREATE TABLE if not exists user(
   user_id INT NOT NULL auto_increment primary key,
   user_name VARCHAR(100),
   user_password VARCHAR(100),
   user_nickname VARCHAR(100),
   user_email VARCHAR(100)
   )
   ENGINE=InnoDB DEFAULT CHARSET=utf8
 """)
# 查询数据库表user内容
cursor.execute('SELECT * FROM user')
# 查看一行 多行:cursor.fetchall()
row = cursor.fetchone()
print(row)
# if row[0] is None:
#   row0 = list(row)
#   row0[0] = 0
#   row = tuple(row0)
# # 插入数据,注:与sqlserver有些区别
cursor.execute("INSERT INTO user VALUES('%s','%s','%s','%s')" % ('xiaoming','qwe','ming','@163.com'))
# 提交数据,才会写入表格
conn.commit()
# 关闭游标关闭数据库
cursor.close()
conn.close()

二、flask操作mysql

"""
Created on 19-10-8
@requirement:Anaconda 4.3.0 (64-bit) Python3.6
@description:
"""
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, jsonify, request
import configparser
import os
app = Flask(__name__)
# 使用ConfigParser 首选需要初始化实例,并读取配置文件:
my_config = configparser.ConfigParser()
my_config.read('db.conf')
# 连接数据库information_collection
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DEV_DATABASE_URL') or \
               "mysql+pymysql://root:password@127.0.0.1:3306/information_collection"
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
mydb = SQLAlchemy()
mydb.init_app(app)
# 用户模型
class User(mydb.Model):
  user_id = mydb.Column(mydb.Integer, primary_key=True)
  user_name = mydb.Column(mydb.String(60), nullable=False)
  user_password = mydb.Column(mydb.String(30), nullable=False)
  user_nickname = mydb.Column(mydb.String(50))
  user_email = mydb.Column(mydb.String(30), nullable=False)
  def __repr__(self):
    return '<User %r>' % self.user_name
# 获取用户列表,所有数据
@app.route('/users', methods=['GET'])
def getUsers():
  data = User.query.all()
  datas = []
  for user in data:
    datas.append({'user_id': user.user_id, 'user_name': user.user_name, 'user_nickname': user.user_nickname, 'user_email': user.user_email})
  return jsonify(data=datas)
# 添加用户数据,一条一条添加
@app.route('/user', methods=['POST'])
def addUser():
  user_name = request.form.get('user_name')
  user_password = request.form.get('user_password')
  user_nickname = request.form.get('user_nickname')
  user_email = request.form.get('user_email')
  user = User(user_name=user_name, user_password=user_password, user_nickname=user_nickname, user_email=user_email)
  try:
    mydb.session.add(user)
    mydb.session.commit()
  except:
    mydb.session.rollback()
    mydb.session.flush()
  userId = user.user_id
  if (user.user_id is None):
    result = {'msg': '添加失败'}
    return jsonify(data=result)
  data = User.query.filter_by(user_id=userId).first()
  result = {'user_id': user.user_id, 'user_name': user.user_name, 'user_nickname': user.user_nickname, 'user_email': user.user_email}
  return jsonify(data=result)
# 获取单条数据
@app.route('/user/<int:userId>', methods=['GET'])
def getUser(userId):
  user = User.query.filter_by(user_id=userId).first()
  if (user is None):
    result = {'msg': '找不到数据'}
  else:
    result = {'user_id': user.user_id, 'user_name': user.user_name, 'user_nickname': user.user_nickname, 'user_email': user.user_email}
  return jsonify(data=result)
# 修改用户数据
@app.route('/user/<int:userId>', methods=['PATCH'])
def updateUser(userId):
  user_name = request.form.get('user_name')
  user_password = request.form.get('user_password')
  user_nickname = request.form.get('user_nickname')
  user_email = request.form.get('user_email')
  try:
    user = User.query.filter_by(user_id=userId).first()
    if (user is None):
      result = {'msg': '找不到要修改的记录'}
      return jsonify(data=result)
    else:
      user.user_name = user_name
      user.user_password = user_password
      user.user_nickname = user_nickname
      user.user_email = user_email
      mydb.session.commit()
  except:
    mydb.session.rollback() # 回滚
    mydb.session.flush() # 重置
  userId = user.user_id
  data = User.query.filter_by(user_id=userId).first()
  result = {'user_id': user.user_id, 'user_name': user.user_name, 'user_password': user.user_password, 'user_nickname': user.user_nickname, 'user_email': user.user_email}
  return jsonify(data=result)
# 删除用户数据
@app.route('/user/<int:userId>', methods=['DELETE'])
def deleteUser(userId):
  User.query.filter_by(user_id=userId).delete()
  mydb.session.commit()
  return getUsers()
if __name__ == '__main__':
  app.run()

三、返回数据的样式

{
  "data": {
    "user_email": "@126.com",
    "user_id": 6,
    "user_name": "xiaoli",
    "user_nickname": "lili"
  }
}

希望本文所述对大家基于flask框架的Python程序设计有所帮助。

上一篇:Python的Flask框架应用程序实现使用QQ账号登录的方法

栏    目:Python代码

下一篇:pandas 空的dataframe 插入列名的示例

本文标题:flask 框架操作MySQL数据库简单示例

本文地址:http://www.codeinn.net/misctech/30420.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有