今天完成了一个帮助系统的部分功能,将md格式的文件中自己定义@@@xxx@@@代表一个文件使用helper_resource/xxx替代,然后通过fileresponse的方式来把图片呈现出来,遇到困难就是替换之后html被重写不存在<img src="/show/">,第一次通过这种方式访问show方法,所以造成了图片无法显示,并且html自动转义会将< >转为&lt;&gt;所以语法不成立也造成了图片无法显示,解决方式当使用mistune把md转为html有意跳过<img src="/show/">并且当做一般文字直接写入就不会被自动转移了,网上解决自动转义的方法试了但是没用,待后期查明原因

def demo(request):
    return render(request, "show.html")


def md2html(md):
    with open(r"E:\untitled\untitled\{}".format(md)) as f1, open(r"E:\untitled\templates\show.html", 'w') as f2:
        for line in f1:
            if line.startswith("helper_resource"):
                f2.write("<img src=/show/>")
                continue
            html = mistune.markdown(line)
            f2.write(html)


def replace():
    md5 = ''
    with open(r'E:\untitled\untitled\im') as f1, open(r"E:\untitled\untitled\im_bak.md", "w") as f2:
        for line in f1:
            r = re.match(r'@@@([0-9a-z]+)@@@', line)
            if r:
                md5 = r.group(1)
                line = line.replace(r.group(), "helper_resource/{}".format(r.group(1)))
                f2.write(line)
            else:
                f2.write(line)
                continue
        return md5


def show(request):
    V = 'C:\\Users\\jackie\\Pictures\\xxx.jpg'
    m = hashlib.md5()
    m.update(V.encode())
    K = m.hexdigest()
    d = {K: V}
    md5 = replace()
    file = open(d[md5], 'rb')
    response = FileResponse(file)
    response['Content-Type'] = 'application/octet-stream'
    response['Content-Disposition'] = 'attachment;filename={}'.format(d[md5].split('\\')[-1])
    md2html("im_bak.md")
    return response
<li>Blue</li>
</ul>
<ul>
<li>Red</li>
</ul>
<ul>
<li>Green</li>
</ul>
<img src=/show/><ul>