当前位置:   article > 正文

python flask 项目实践_pyhton flask 的 实践

pyhton flask 的 实践

架构:python+ flask +marshmallow+itsdangerous+pymysql

数据库:mysql

实现功能:登录、验证码、鉴权、用户、上传、下载、错误统一处理

api格式: restful + json

项目目录

web->controller ->uploads.py

  1. import datetime
  2. import os
  3. import time
  4. from flask import Blueprint, jsonify, request
  5. from web import db
  6. from web.setting import UPLOAD_URL
  7. from web.token_auth import login_required
  8. from web.model.uploads import Upload
  9. # 创建蓝图
  10. uploads = Blueprint('upload', __name__)
  11. # 单文件上传
  12. @uploads.route('/file', methods=["POST"])
  13. @login_required()
  14. def file():
  15. if request.files.to_dict() == {}:
  16. return jsonify(data={}, msg='file为空', code=500)
  17. year_time = datetime.datetime.now().strftime('%Y')
  18. month_time = datetime.datetime.now().strftime('%m')
  19. day_time = datetime.datetime.now().strftime('%d')
  20. pwd = UPLOAD_URL+'\\'+year_time+'\\'+month_time+'\\'+day_time
  21. save_pwd = 'static\\uploads' + '\\' + year_time + '\\' + month_time + '\\' + day_time
  22. word_name = os.path.exists(pwd)
  23. f = request.files['file']
  24. az = os.path.splitext(f.filename)[1]
  25. if not word_name:
  26. os.makedirs(pwd)
  27. filename = int(round(time.time() * 1000))
  28. upload_path = os.path.join(pwd, str(filename)+az)
  29. save_upload_path = os.path.join(save_pwd, str(filename) + az)
  30. f.save(upload_path)
  31. data = Upload(name=str(filename)+az, path=save_upload_path)
  32. db.session.add(data)
  33. db.session.commit()
  34. return jsonify(data={}, msg='上传成功', code=200)
  35. # 多文件上传
  36. @uploads.route('/files', methods=["POST"])
  37. @login_required()
  38. def files():
  39. if len(request.files.getlist('files')) == 0:
  40. return jsonify(data={}, msg='files为空', code=500)
  41. year_time = datetime.datetime.now().strftime('%Y')
  42. month_time = datetime.datetime.now().strftime('%m')
  43. day_time = datetime.datetime.now().strftime('%d')
  44. pwd = UPLOAD_URL + '\\' + year_time + '\\' + month_time + '\\' + day_time
  45. save_pwd = 'static\\uploads' + '\\' + year_time + '\\' + month_time + '\\' + day_time
  46. for f in request.files.getlist('files'):
  47. az = os.path.splitext(f.filename)[1]
  48. word_name = os.path.exists(pwd)
  49. if not word_name:
  50. os.makedirs(pwd)
  51. filename = str(round(time.time() * 1000))
  52. upload_path = os.path.join(pwd, filename+az)
  53. save_upload_path = os.path.join(save_pwd, str(filename) + az)
  54. f.save(upload_path)
  55. data = Upload(name=str(filename) + az, path=save_upload_path)
  56. db.session.add(data)
  57. db.session.commit()
  58. return jsonify(data={}, msg='上传成功', code=200)

web->controller ->user.py

  1. import hashlib
  2. from flask import jsonify, request, Blueprint, session
  3. from marshmallow import ValidationError
  4. from web.model.user import User
  5. from web import db
  6. from web.token_auth import create_token, login_required, verify_token
  7. from web.validator.user import UserSchema, RegisterSchema, LoginSchema
  8. from web.token_auth import check_token as check_token_auth
  9. # 创建蓝图
  10. user = Blueprint('user', __name__)
  11. # 用户列表
  12. @user.route('/index')
  13. @login_required()
  14. def index():
  15. total_page = 1
  16. if request.json is None:
  17. items = User.query.all()
  18. else:
  19. page = request.json.get('page')
  20. page_size = request.json.get('pageSize')
  21. if page_size is None:
  22. page_size = 10
  23. if page is None:
  24. items = User.query.all()
  25. else:
  26. data = User.query.paginate(page=page, per_page=page_size)
  27. items = data.items
  28. total_page = data.pages
  29. datas = []
  30. for user in items:
  31. datas.append({'id': user.id, 'username': user.username, 'password': user.password, 'roleid': user.roleid})
  32. return jsonify(data={'data': datas, 'total_page': total_page}, msg='成功', code=200)
  33. # 添加用户
  34. @user.route('/add', methods=["POST"])
  35. @login_required()
  36. def add():
  37. # 校验字段
  38. try:
  39. result = UserSchema().load(request.json)
  40. except ValidationError as e:
  41. return jsonify(data=e.messages, msg='', code=500)
  42. username = request.json.get('username')
  43. password = request.json.get('password')
  44. roleid = request.json.get('roleid')
  45. # 判断用户名是否重复
  46. filterData = User.query.filter(User.username == username).all()
  47. if len(filterData) >= 1:
  48. return jsonify(data={}, msg='用户名已存在', code=500)
  49. data = User(username=username, password=hashlib.md5(password.encode()).hexdigest(), roleid=roleid)
  50. db.session.add(data)
  51. db.session.commit()
  52. return jsonify(data={}, msg='成功', code=200)
  53. # 修改用户
  54. @user.route('/edit/<id>', methods=["PUT"])
  55. @login_required()
  56. def edit(id):
  57. # 校验字段
  58. try:
  59. result = UserSchema().load(request.json)
  60. except ValidationError as e:
  61. return jsonify(data=e.messages, msg='', code=500)
  62. username = request.json.get('username')
  63. password = request.json.get('password')
  64. roleid = request.json.get('roleid')
  65. # 判断是否有此用户
  66. filterData = User.query.filter(User.id == id).all()
  67. if len(filterData) == 0:
  68. return jsonify(data={}, msg='没有此用户', code=500)
  69. oneData = User.query.filter(User.id == id).first()
  70. oneData.username = username
  71. oneData.password = hashlib.md5(password.encode()).hexdigest()
  72. oneData.roleid = roleid
  73. db.session.commit()
  74. return jsonify(data={}, msg='成功', code=200)
  75. # 删除用户
  76. @user.route('/delete/<id>', methods=["DELETE"])
  77. @login_required()
  78. def delete(id):
  79. # 判断是否有此用户
  80. filterData = User.query.filter(User.id =
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号