创建一个空文件pycharm打开,并创建虚拟环境
一次性安装以下所有:pip install -r r.txt
Flask==1.1.4
Flask-Caching==1.10.1
Flask-Cors==3.0.10
Flask-Migrate==2.7.0
Flask-RESTful==0.3.9
Flask-Script==2.0.6
Flask-SQLAlchemy==2.5.1
MarkupSafe==2.0.1
PyJWT==2.3.0
PyMySQL==1.0.2
qiniu==7.6.0
redis==4.2.2
# 可以放置在**.txt文件 一次性安装
挂载项? ?create_app.py
from flask import Flask
from flask_cors import CORS
from model.model import db
from views.views import goods_dp
def create_app(config):
flask_app = Flask(__name__)
flask_app.config.from_object(config) # 挂在配置项
cors = CORS(flask_app) # 跨域
flask_app.register_blueprint(goods_dp) # 注册蓝图
db.init_app(flask_app) # 绑定数据库连接对象
return flask_app
程序入口????????app.py?
from config.settings import Config
from create_app import create_app
app = create_app(Config)
# if __name__ == '__main__':
# app.run('127.0.0.1',port=18888)
配置项? ?config >> settings.py
?current_app.config.get('SECRET_KEY')? ? ? ? # 配置项取值语法
class Config():
SECRET_KEY = 'dasezytxrdtf'
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:123456@127.0.0.1:3306/20220919db'
SQLALCHEMY_TRACK_MODIFICATIONS = False # 是否追踪数据库发生的变化
SQLALCHEMY_ECHO = True # 是否在控制台打印输出sql语句
JSON_AS_ASCII = False # 返回JSON的时候不转义中文
?迁移项? ? ? ? manage.py
from flask_migrate import Migrate, MigrateCommand
from flask_script import Manager # script第三方扩展
from app import app
from model.model import db
# 1.创建命令行对象
manage = Manager(app)
# 2.创建迁移对象
migrate = Migrate(app, db)
# 3.添加迁移命令到命令行对象
manage.add_command('db', MigrateCommand)
# 4.运行
if __name__ == '__main__':
manage.run()
?模型类? ? ? ? models >> model.py
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class GoodsModel(db.Model):
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
title = db.Column(db.String(128), comment='商品名')
desc = db.Column(db.Text, comment='商品简介')
price = db.Column(db.DECIMAL(10, 2), comment='价格')
img = db.Column(db.String(128), comment='图片')
创建数据库?settings.py中指定的?20220919db库名
python manage.py db init? ? ? ? # 初始化
python manage.py db migrate? ? ? ? # 迁移数据库
python manage.py db? ? ? ? # 查看所有命令
python manage.py db upgrade? ? ? ? # 执行迁移
??视图? ? ? ? views >> views.py
import random
from datetime import datetime
from flask import Blueprint, request, jsonify
from flask_restful import Api, Resource
from model.model import GoodsModel, db
goods_dp = Blueprint('goods_dp', __name__, url_prefix='/v1')
api = Api(goods_dp)
class GoodsView(Resource):
def get(self):
# 查看所有商品
goods_list = GoodsModel.query.all() # 获取所有对象
goods_all = []
for goods in goods_list:
d = {
'id': goods.id,
'title': goods.title,
'price': str(goods.price), # DECIMAL类型 不能被JSON序列化
'desc': goods.desc,
# 'img': request.scheme + '://' + request.host + '/' + goods.img,
# 协议 + :// + 主机地址 + / + 图片名
# 'img': '%s://%s/%s' % (request.scheme, request.host, goods.img)
'img': 'http://127.0.0.1:5000/' + goods.img
}
goods_all.append(d)
return jsonify({'code': 200, 'msg': '商品列表获取成功',
'data': goods_all})
def post(self):
# 添加商品
args = request.json
title = args.get('title')
desc = args.get('desc')
price = args.get('price')
img = args.get('img')
if not all([title, desc, price, img]):
return jsonify({'code': 400, 'msg': '参数不完整'})
goods = GoodsModel(title=title, price=price, desc=desc, img=img)
db.session.add(goods)
db.session.commit()
return jsonify({'code': 200, 'msg': '添加成功'})
class GoodsInfoView(Resource):
def get(self, id):
# 获取一条商品
goods_info = GoodsModel.query.get(id) # 获取一条对象
if not goods_info:
return jsonify({'code': 400, 'msg': '商品不存在'})
return jsonify({
'code': 200,
'msg': '商品获取成功',
'data': {
'id': goods_info.id,
'title': goods_info.title,
'desc': goods_info.desc,
'price': str(goods_info.price),
'img': '%s://%s/%s' % (request.scheme, request.host, goods_info.img),
}
})
def put(self, id):
# 修改一条商品
args = request.json
title = args.get('title')
desc = args.get('desc')
price = args.get('price')
img = args.get('img')
goods_info = GoodsModel.query.get(id)
if not goods_info:
return jsonify({'code': 400, 'msg': '商品不存在'})
if title and title != goods_info.title: # title不为空 并且修改后的值发生改变 才进行修改
goods_info.title = title
if desc and desc != goods_info.desc:
goods_info.desc = desc
if price and price != goods_info.price:
goods_info.price = price
if img and img != goods_info.img:
goods_info.img = img
db.session.commit()
return jsonify({'code': 200, 'msg': '修改成功'})
def delete(self, id):
# 删除一条商品
goods_info = GoodsModel.query.get(id)
if not goods_info:
return jsonify({'code': 400, 'msg': '商品不存在'})
GoodsModel.query.filter(GoodsModel.id == id).delete()
db.session.commit()
return jsonify({'code': 200, 'msg': '删除成功'})
# 上传图片
class UploadView(Resource):
def post(self):
img = request.files.get('img')
filename = datetime.strftime(datetime.now(), '%Y%m%d%H%M%S')
filename += str(random.randint(100000, 999999))
filename += '.'
filename += img.filename.split('.')[-1]
img.save('./static/%s' % filename)
return jsonify({'code': 200, 'msg': '文件上传成功',
'data': {'filename': 'static/%s' % filename}})
api.add_resource(GoodsView, '/goods')
api.add_resource(GoodsInfoView, '/goods/<int:id>')
api.add_resource(UploadView, '/upload')
|