python flask实战订餐系统微信小程序-45ueditor图片列表在线管理功能

B站配套视频教程观看ueditor图片列表在线管理功能

本地上传按钮不能展示的原因解决

应该传递正确图片展示url,他的zurl是这个,只需将它评出来就可以

http://127.0.0.1:8999/static/upload/20210825/efb27551c196435f89a0ecf47d2bedb3.png

UrlManager.py添加静态方法

    @staticmethod
    def buildImageUrl( path ):
        app_config = app.config['APP']
        url = app_config['domain'] + app.config['UPLOAD']['prefix_url'] + path
        return url

base_setting.py添加domain配置

APP = {
    'domain':'http://127.0.0.1:8999'
}

Upload.py添加服务的调用

from common.libs.UrlManager import UrlManager

def uploadImage():
	resp = { 'state':'SUCCESS','url':'','title':'','original':'' }
	file_target = request.files
	upfile = file_target['upfile'] if 'upfile' in file_target else None
	if upfile is None:
		resp['state'] = "上传失败"
		return jsonify(resp)

	ret = UploadService.uploadByFile( upfile )
	if ret['code'] != 200:
		resp['state'] = "上传失败:" + ret['msg']
		return jsonify(resp)

	resp['url'] = UrlManager.buildImageUrl( ret['data']['file_key'] )
	return jsonify( resp )

可以看到成功上傳了

在綫管理功能的添加

创建图片数据库

show databases;
use food_db
CREATE TABLE `images` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `file_key` varchar(60) NOT NULL DEFAULT '' COMMENT '文件名',
  `created_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '插入时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
flask-sqlacodegen "mysql://root:123456@127.0.0.1/food_db" --tables images --outfile "order/common/models/Images.py" --flask

images.pu

# coding: utf-8

from application import db

class Image(db.Model):
    __tablename__ = 'images'

    id = db.Column(db.Integer, primary_key=True)
    file_key = db.Column(db.String(60), nullable=False, server_default=db.FetchedValue(), info='???')
    created_time = db.Column(db.DateTime, nullable=False, server_default=db.FetchedValue(), info='????')

UploadService.py上传成功后需要存储起来:

from common.models.Image import Image

class UploadService():
	@staticmethod
	def uploadByFile( file ):
		config_upload = app.config['UPLOAD']
		resp = { 'code':200,'msg':'操作成功~~','data':{} }
		filename = secure_filename( file.filename )
		ext = filename.rsplit(".",1)[1]
		if ext not in config_upload['ext']:
			resp['code'] = -1
			resp['msg'] = "不允许的扩展类型文件"
			return resp


		root_path = app.root_path + config_upload['prefix_path']
		#不使用getCurrentDate创建目录,为了保证其他写的可以用,这里改掉,服务器上好像对时间不兼容
		file_dir = datetime.datetime.now().strftime("%Y%m%d")
		save_dir = root_path + file_dir
		if not os.path.exists( save_dir ):
			os.mkdir( save_dir )
			os.chmod( save_dir,stat.S_IRWXU | stat.S_IRGRP |  stat.S_IRWXO )

		file_name = str( uuid.uuid4() ).replace("-","") + "." + ext
		file.save( "{0}/{1}".format( save_dir,file_name ) )

		model_image = Image()
		model_image.file_key = file_dir + "/" + file_name
		model_image.created_time = getCurrentDate()
		db.session.add( model_image)
		db.session.commit()

		resp['data'] = {
			'file_key': model_image.file_key
		}
		return resp

上传测试可以看到成功上传

返回上传的所有图片用于管理

if action == "listimage":
return listImage()

@route_upload.route("/ueditor",methods = [ "GET","POST" ])
def ueditor():

   req = request.values
   action = req['action'] if 'action' in req else ''

   if action == "config":
      root_path = app.root_path
      config_path = "{0}/web/static/plugins/ueditor/upload_config.json".format( root_path )
      with open( config_path,encoding="utf-8" ) as fp:
         try:
            config_data =  json.loads( re.sub( r'\/\*.*\*/' ,'',fp.read() ) )
         except:
            config_data = {}
      return  jsonify( config_data )

   if action == "uploadimage":
      return uploadImage()

   if action == "listimage":
      return listImage()

   return "upload"
from common.models.Images import Image

def listImage():
	resp = { 'state':'SUCCESS','list':[],'start':0 ,'total':0 }

	req = request.values

	start = int( req['start']) if 'start' in req else 0
	page_size = int( req['size']) if 'size' in req else 20

	query = Image.query
	if start > 0:
		query = query.filter( Image.id < start )

	list = query.order_by( Image.id.desc() ).limit( page_size ).all()
	images = []

	if list:
		for item in list:
			images.append( { 'url': UrlManager.buildImageUrl( item.file_key ) } )
			start = item.id
	resp['list'] = images
	resp['start'] = start
	resp['total'] = len( images )
	return jsonify( resp )

运行就可以看到在线管理成功配置了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

虚坏叔叔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值