功能
归档
380
2017 年 02 月 02 日
用Python写一个Markdown编辑器

Python版本:3.5.2
Django版本:1.11+



一、Markdown编辑器


1.国内开源

http://pandao.github.io/editor.md/

2.主要特性

  • 支持“标准”Markdown / CommonMark和Github风格的语法,也可变身为代码编辑器;
  • 支持实时预览、图片(跨域)上传、预格式文本/代码/表格插入、代码折叠、搜索替换、只读模式、自定义样式主题和多语言语法高亮等功能;
  • 支持ToC(Table of Contents)、Emoji表情、Task lists、@链接等Markdown扩展语法;
  • 支持TeX科学公式(基于KaTeX)、流程图 Flowchart 和 时序图 Sequence Diagram;
  • 支持识别和解析HTML标签,并且支持自定义过滤标签解析,具有可靠的安全性和几乎无限的扩展性;
  • 支持 AMD / CMD 模块化加载(支持 Require.js & Sea.js),并且支持自定义扩展插件;
  • 兼容主流的浏览器(IE8+)和Zepto.js,且支持iPad等平板设备;
  • 支持自定义主题样式;

二、搭建环境


1.首先创建一个Django项目

python3 D:\soft\Anaconda3\Scripts\django-admin.exe startproject www
dir

manage.py
www
cd www
dir

settings.py
urls.py
wsgi.py
__init__.py

2.创建一个app

python3 D:\soft\Anaconda3\Scripts\django-admin.exe startapp work
cd work
dir

admin.py
apps.py
migrations
models.py
tests.py
views.py
__init__.py

四、编写代码


1.编辑setting文件

www/www/setting.py

INSTALLED_APPS = [
    'work',         #添加这行为新建的app:work
]

TEMPLATES = [
    {
        'DIRS': [os.path.join(BASE_DIR, 'templates')],      #定义templates
    }
]

DATABASES = {               #添加数据库
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'kjblog',
        'USER': 'root',
        'PASSWORD': 'redhat',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

2.添加url

www/www/urls.py

from django.conf.urls import url, include
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^mm/', include('work.urls')),     #增加这一行
]

3.修改创建数据库models

www/work/models.py

from __future__ import unicode_literals
from django.db import models

class UpFile(models.Model):
    up_file = models.FileField(upload_to='upload/')

    def __unicode__(self):
        return self.up_file

4.创建数据库

python3 manage.py makemigrations

No changes detected
python3 manage.py migrate

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, sessions, work
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying sessions.0001_initial... OK
  Applying work.0001_initial... OK
  Applying work.0002_auto_20171108_0958... OK

执行完命令后数据库会生产以上一些表,除了work_upfile外其他表均是Django自动生成用于存用户等;work_upfilemodels.py里定义的表,用于存放Markdown编辑器上传图片的存放路径;

5.编写视窗函数view

www/work/view.py

from django.shortcuts import render
from django import forms
from django.http import HttpResponse
import json
from work.models import UpFile
# Create your views here.

def login(request):
    return render(request, 'index.html')        #首页访问函数

class UpFiles(forms.Form):
    upfile = forms.FileField()

def upload(request):        #判断提交方式
    if request.method == "POST":
        up = UpFiles(request.POST, request.FILES)
        cc = UpFile(up_file=request.FILES['file'])
        cc.save()
        url = str(cc.up_file)
        resp = {'success':1,'message': "6666",'url': url}
        return HttpResponse(json.dumps(resp), content_type="application/json")
    else:
        resp = {'success': 0, 'message': "error meth"}
        return HttpResponse(json.dumps(resp), content_type="application/json")

6.添加urls

www/work/urls.py

from django.conf.urls import url
from . import views
from django.conf.urls.static import static
import os
from django.conf import settings

urlpatterns = [
    url(r'^$', views.login, name='login'),
    url(r'^uploadfile$', views.upload, name='upload'),
]

media_root = os.path.join(settings.BASE_DIR,'upload')
urlpatterns += static('/upload/', document_root=media_root)

五、写前端


1.直接下载官网开源软件

cd www/work/static/work
dir

css
editormd.js
editormd.min.js
fonts
images
jquery.min.js
lib
plugins

2.编写访问页面

www/work/templates/index.html

{% load staticfiles %}
<!DOCTYPE html>
<html lang="zh">
    <head>
        <meta charset="utf-8" />
        <title>Simple example - Editor.md examples</title>
        <link rel="stylesheet" href={% static 'work/css/style.css' %} />
        <link rel="stylesheet" href={% static 'work/css/editormd.css' %} />
        <link rel="shortcut icon" href="https://pandao.github.io/editor.md/favicon.ico" type="image/x-icon" />
    </head>

    <body>
        <div id="layout">
            <header>
                <h1>Simple example</h1>
            </header>
            <div id="test-editormd">
                <textarea style="display:none;">[TOC]</textarea>
            </div>
        </div>
        <script src={% static 'work/jquery.min.js' %}></script>
        <script src={% static 'work/editormd.min.js' %}></script>
        <script type="text/javascript">
        var testEditor;

        $(function() {
            testEditor = editormd("test-editormd", {
            width   : "90%",
            height  : 640,
            syncScrolling : "single",
            path    : "/static/work/lib/",
            //打开上传图片
            imageUpload : true,
            imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
            imageUploadURL : "./uploadfile",
            saveHTMLToTextarea : true,
            toolbarIcons : function() {
            // Or return editormd.toolbarModes[name]; // full, simple, mini
            // Using "||" set icons align right.
            //return ["undo", "redo", "|", "bold", "hr", "|", "preview", "watch", "|", "fullscreen", "file", "faicon", "||", "watch", "fullscreen", "preview"]
            return  ["bold", "del", "italic", "hr", "image", "table", "datetime", "|", "preview", "watch", "|", "fullscreen"];
            },

            //下面这一行将使用dark主题
            editorTheme: "pastel-on-dark",
            theme: "gray",
            previewTheme : "dark"
            //editor.md期望得到一个json格式的上传后的返回值,格式是这样的:
            /*
            {
            success : 0 | 1,           // 0 表示上传失败,1 表示上传成功
            message : "提示的信息,上传成功或上传失败及错误信息等。",
            url     : "图片地址"        // 上传成功时才返回
            }
            */
            });
            });
        </script>
    </body>
</html>

六、测试


1.启用

python3 manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
January 23, 2018 - 09:47:26
Django version 1.11.6, using settings 'upimg.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.

2.访问测试

127.0.0.1:8000/mm


上传完成后会在左边显示栏显示~


具体代码可以访问我的GitHub下载使用:

https://github.com/JarboU/markdown

Over~

留言
Loading...

发表评论

电子邮件地址不会被公开。 必填项已用*标注