在python web.py中使用百度富文本编辑器 UEditor

6 篇文章 0 订阅

UEditor官方没有支持python的版本,有人改了个python的django版本,但是没找到web.py的。

于是参考php版本,实现了一下web.py集成UEditor,包含了文件上传,图片上传,视频上传,图片远程抓取,涂鸦等。

可能会有一些session之类的没有处理。

Demo代码可以在https://github.com/meizhitu/100programhomework/tree/master/100-25-literal-10-todo 查看

首先改ueditor.config.js,把原来指向php的链接改成web.py的

 //图片上传配置区
        ,imageUrl:"/ue_imageUp"             //图片上传提交地址
        ,imagePath:""                     //图片修正地址,引用了fixedImagePath,如有特殊需求,可自行配置
        //,imageFieldName:"upfile"                  //图片数据的key,若此处修改,需要在后台对应文件修改对应参数
        //,compressSide:0                           //等比压缩的基准,确定maxImageSideLength参数的参照对象。0为按照最长边,1为按照宽度,2为按照高度
        //,maxImageSideLength:900                   //上传图片最大允许的边长,超过会自动等比缩放,不缩放就设置一个比较大的值,更多设置在image.html中
        //,savePath: [ 'upload1', 'upload2', 'upload3' ]    //图片保存在服务器端的目录, 默认为空, 此时在上传图片时会向服务器请求保存图片的目录列表,
                                                            // 如果用户不希望发送请求, 则可以在这里设置与服务器端能够对应上的目录名称列表
                                                            //比如: savePath: [ 'upload1', 'upload2' ]

        //涂鸦图片配置区
        ,scrawlUrl:"/ue_scrawlUp"           //涂鸦上传地址
        ,scrawlPath:""                            //图片修正地址,同imagePath

        //附件上传配置区
        ,fileUrl:"/ue_fileUp"               //附件上传提交地址
        ,filePath:""                   //附件修正地址,同imagePath
        //,fileFieldName:"upfile"                    //附件提交的表单名,若此处修改,需要在后台对应文件修改对应参数

        //远程抓取配置区
        //,catchRemoteImageEnable:true               //是否开启远程图片抓取,默认开启
        ,catcherUrl:"/ue_getRemoteImage"   //处理远程图片抓取的地址
        ,catcherPath:""                  //图片修正地址,同imagePath
        //,catchFieldName:"upfile"                   //提交到后台远程图片uri合集,若此处修改,需要在后台对应文件修改对应参数
        //,separater:'ue_separate_ue'               //提交至后台的远程图片地址字符串分隔符
        //,localDomain:[]                            //本地顶级域名,当开启远程图片抓取时,除此之外的所有其它域名下的图片都将被抓取到本地,默认不抓取127.0.0.1和localhost

        //图片在线管理配置区
        ,imageManagerUrl:"/ue_imageManager"       //图片在线管理的处理地址
        ,imageManagerPath:""                                    //图片修正地址,同imagePath

        //屏幕截图配置区
        ,snapscreenHost: location.hostname                                 //屏幕截图的server端文件所在的网站地址或者ip,请不要加http://
        ,snapscreenServerUrl: "/ue_imageUp" //屏幕截图的server端保存程序,UEditor的范例代码为“URL +"server/upload/php/snapImgUp.php"”
        ,snapscreenPath: ""
        ,snapscreenServerPort: location.port                                   //屏幕截图的server端端口
        //,snapscreenImgAlign: ''                                //截图的图片默认的排版方式

        //word转存配置区
        ,wordImageUrl:"/ue_imageUp"             //word转存提交地址
        ,wordImagePath:""                       //
        //,wordImageFieldName:"upfile"                     //word转存表单名若此处修改,需要在后台对应文件修改对应参数

        //视频上传配置区
        ,getMovieUrl:"/ue_getMovie"                   //视频数据获取地址
        ,videoUrl:"/ue_fileUp"               //附件上传提交地址
        ,videoPath:""                   //附件修正地址,同imagePath
        //,videoFieldName:"upfile"                    //附件提交的表单名,若此处修改,需要在后台对应文件修改对应参数
然后配置web.py的urls映射

urls = (
    '/', 'Index',
    '/ue_imageUp', Ue_ImageUp,
    '/ue_fileUp', Ue_FileUp,
    '/ue_scrawlUp', Ue_ScrawlUp,
    '/ue_getRemoteImage', Ue_GetRemoteImage,
    '/ue_getMovie', Ue_GetMovie,
    '/ue_imageManager', Ue_ImageManager,
)
最后实现这些web.py的class。

#coding=utf-8
import base64
import uuid
import urllib2
import os

import web

ueconfig_dir = 'static/upload'
ueconfig_url = '/' + ueconfig_dir


def listImage(rootDir, retlist):
    for cfile in os.listdir(rootDir):
        path = os.path.join(rootDir, cfile)
        if os.path.isdir(path):
            listImage(path, retlist)
        else:
            if cfile.endswith('.gif') or cfile.endswith('.png') or cfile.endswith('.jpg') or cfile.endswith('.bmp'):
                retlist.append('/static/upload/' + cfile)


def saveUploadFile(fileName, content):
    fileName = fileName.replace('\\', '/') # replaces the windows-style slashes with linux ones.
    fout = open(ueconfig_dir + '/' + fileName, 'wb') # creates the file where the uploaded file should be stored
    fout.write(content) # writes the uploaded file to the newly created file.
    fout.close() # closes the file, upload complete.


class Ue_ImageUp:
    def GET(self):
        reqData = web.input()
        if 'fetch' in reqData:
            web.header('Content-Type', 'text/javascript')
            return 'updateSavePath(["upload"]);'
        web.header("Content-Type", "text/html; charset=utf-8")
        return ""

    def POST(self):
        postData = web.input(upfile={}, pictitle="")
        web.debug(postData)
        fileObj = postData.upfile
        picTitle = postData.pictitle
        fileName = fileObj.filename
        newFileName = str(uuid.uuid1()) + ".png"
        saveUploadFile(newFileName, fileObj.file.read())
        return "{'url':'" + ueconfig_url + '/' + newFileName + "','title':'" + picTitle + "','original':'" + fileName + "','state':'" + "SUCCESS" + "'}"


class Ue_FileUp:
    def GET(self):
        web.header("Content-Type", "text/html; charset=utf-8")
        return ""

    def POST(self):
        postData = web.input(upfile={})
        fileObj = postData.upfile
        fileName = postData.Filename
        ext = '.' + fileName.split('.')[-1]
        #web.py的static目录对中文文件名不支持,会404
        newFileName = str(uuid.uuid1()) + ext
        #fileNameFormat = postData.fileNameFormat
        saveUploadFile(newFileName, fileObj.file.read())
        return "{'url':'" + ueconfig_url + '/' + newFileName + "','fileType':'" + ext + "','original':'" + fileName + "','state':'" + "SUCCESS" + "'}"


class Ue_ScrawlUp:
    def GET(self):
        web.header("Content-Type", "text/html; charset=utf-8")
        return ""

    def POST(self):
        reqData = web.input(upfile={})
        if 'action' in reqData:
            if reqData.action == 'tmpImg':
                #上传背景
                fileObj = reqData.upfile
                fileName = fileObj.filename
                saveUploadFile(fileName, fileObj.file.read())
                return "<script>parent.ue_callback(" + ueconfig_url + '/' + fileName + "','" + "SUCCESS" + "')</script>"
        else:
            base64Content = reqData.content
            fileName = str(uuid.uuid1()) + '.png'
            saveUploadFile(fileName, base64.decodestring(base64Content))
            return "{'url':'" + ueconfig_url + '/' + fileName + "',state:'" + "SUCCESS" + "'}"


class Ue_GetRemoteImage:
    def GET(self):
        web.header("Content-Type", "text/html; charset=utf-8")
        return ""

    def POST(self):
        postData = web.input()
        urls = postData.upfile
        #urls = urls.replace('&','&')
        urllist = urls.split("ue_separate_ue")
        fileType = [".gif", ".png", ".jpg", ".jpeg", ".bmp"]
        outlist = []
        for fileurl in urllist:
            if not fileurl.startswith('http'):
                continue
            ext = "." + fileurl.split('.')[-1]
            web.debug(ext + "|" + fileurl)
            if ext in fileType:
                fileName = str(uuid.uuid1()) + ext
                saveUploadFile(fileName, urllib2.urlopen(fileurl).read())
                outlist.append(ueconfig_url + "/" + fileName)
        outlist = "ue_separate_ue".join(outlist)
        return "{'url':'" + outlist + "','tip':'远程图片抓取成功!','srcUrl':'" + urls + "'}"


class Ue_GetMovie:
    def POST(self):
        reqData = web.input()
        skey = reqData.searchKey
        vtype = reqData.videoType
        surl = 'http://api.tudou.com/v3/gw?method=item.search&appKey=myKey&format=json&kw=' + skey + '&pageNo=1&pageSize=20&channelId=' + vtype + '&inDays=7&media=v&sort=s'
        htmlContent = urllib2.urlopen(surl).read()
        web.debug(htmlContent)
        return htmlContent


class Ue_ImageManager:
    def POST(self):
        reqData = web.input()
        if 'action' in reqData:
            if reqData.action == 'get':
                retfiles = []
                listImage(ueconfig_dir, retfiles)
                htmlContent = "ue_separate_ue".join(retfiles)
                return htmlContent




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值