go解析markdown转成html

一、代码

package main

import (
    "fmt"
    "github.com/microcosm-cc/bluemonday"
    "github.com/russross/blackfriday"
    "io/ioutil"
    "os"
)

func ReadAll(filePth string) ([]byte, error) {
    f, err := os.Open(filePth)
    if err != nil {
        return nil, err
    }
    return ioutil.ReadAll(f)
}

func MarkdownToHTML(md string) string {
    myHTMLFlags := 0 |
        blackfriday.HTML_USE_XHTML |
        blackfriday.HTML_USE_SMARTYPANTS |
        blackfriday.HTML_SMARTYPANTS_FRACTIONS |
        blackfriday.HTML_SMARTYPANTS_DASHES |
        blackfriday.HTML_SMARTYPANTS_LATEX_DASHES

    myExtensions := 0 |
        blackfriday.EXTENSION_NO_INTRA_EMPHASIS |
        blackfriday.EXTENSION_TABLES |
        blackfriday.EXTENSION_FENCED_CODE |
        blackfriday.EXTENSION_AUTOLINK |
        blackfriday.EXTENSION_STRIKETHROUGH |
        blackfriday.EXTENSION_SPACE_HEADERS |
        blackfriday.EXTENSION_HEADER_IDS |
        blackfriday.EXTENSION_BACKSLASH_LINE_BREAK |
        blackfriday.EXTENSION_DEFINITION_LISTS |
        blackfriday.EXTENSION_HARD_LINE_BREAK

    renderer := blackfriday.HtmlRenderer(myHTMLFlags, "", "")
    bytes := blackfriday.MarkdownOptions([]byte(md), renderer, blackfriday.Options{
        Extensions: myExtensions,
    })
    theHTML := string(bytes)
    return bluemonday.UGCPolicy().Sanitize(theHTML)
}

func main() {
    path:="C:\\Users\\ffm11\\Desktop\\md文件库\\Celery.md"
    res,err:=ReadAll(path)
    if err !=nil{
        panic(err)
    }

    result:=MarkdownToHTML(string(res))
    fmt.Println(result)
}

二、结果

<h1>Celery</h1>

<h2>1.什么是Celery</h2>

<p>Celery是一个简单、灵活且可靠的,处理大量消息的分布式系统</p>

<p>专注于实时处理的异步任务队列</p>

<p>同时也支持任务调度</p>

<h3>Celery架构</h3>

<p><img alt="20150314100608_187"/></p>

<p>Celery的架构由三部分组成,消息中间件(message broker),任务执行单元(worker)和任务执行结果存储(task result store)组成。</p>

<h4>消息中间件</h4>

<p>Celery本身不提供消息服务,但是可以方便的和第三方提供的消息中间件集成。包括,RabbitMQ, Redis等等</p>

<h4>任务执行单元</h4>

<p>Worker是Celery提供的任务执行的单元,worker并发的运行在分布式的系统节点中。</p>

<h4>任务结果存储</h4>

<p>Task result store用来存储Worker执行的任务的结果,Celery支持以不同方式存储任务的结果,包括AMQP, redis等</p>

<h3>版本支持情况</h3>

<pre><code>Celery version 4.0 runs on
        Python ❨2.7, 3.4, 3.5❩
        PyPy ❨5.4, 5.5❩
    This is the last version to support Python 2.7, and from the next version (Celery 5.x) Python 3.5 or newer is required.

    If you’re running an older version of Python, you need to be running an older version of Celery:

        Python 2.6: Celery series 3.1 or earlier.
        Python 2.5: Celery series 3.0 or earlier.
        Python 2.4 was Celery series 2.2 or earlier.

    Celery is a project with minimal funding, so we don’t support Microsoft Windows. Please don’t open any issues related to that platform.
</code></pre>

<h2>2.使用场景</h2>

<p>异步任务:将耗时操作任务提交给Celery去异步执行,比如发送短信/邮件、消息推送、音视频处理等等</p>

<p>定时任务:定时执行某件事情,比如每天数据统计</p>

<h2>3.Celery的安装配置</h2>

<p>pip install celery</p>

<p>消息中间件:RabbitMQ/Redis</p>

<p>app=Celery(‘任务名’,backend=‘xxx’,broker=‘xxx’)</p>

<h2>4.Celery执行异步任务</h2>

<h4>基本使用</h4>

<p>创建项目celerytest</p>

<p>创建py文件:celery_app_task.py</p>

<pre><code>import celery
import time
# broker=&#39;redis://127.0.0.1:6379/2&#39; 不加密码
backend=&#39;redis://:123456@127.0.0.1:6379/1&#39;
broker=&#39;redis://:123456@127.0.0.1:6379/2&#39;
cel=celery.Celery(&#39;test&#39;,backend=backend,broker=broker)
@cel.task
def add(x,y):
    return x+y


</code></pre>

<p>创建py文件:add_task.py,添加任务</p>

<pre><code>from celery_app_task import add
result = add.delay(4,5)
print(result.id)
</code></pre>

<p>创建py文件:run.py,执行任务,或者使用命令执行:celery worker -A celery_app_task -l info</p>

<p>注:windows下:celery worker -A celery_app_task -l info -P eventlet</p>

<pre><code>from celery_app_task import cel
if __name__ == &#39;__main__&#39;:
    cel.worker_main()
    # cel.worker_main(argv=[&#39;--loglevel=info&#39;)
</code></pre>

<p>创建py文件:result.py,查看任务执行结果</p>

<pre><code>from celery.result import AsyncResult
from celery_app_task import cel

async = AsyncResult(id=&#34;e919d97d-2938-4d0f-9265-fd8237dc2aa3&#34;, app=cel)

if async.successful():
    result = async.get()
    print(result)
    # result.forget() # 将结果删除
elif async.failed():
    print(&#39;执行失败&#39;)
elif async.status == &#39;PENDING&#39;:
    print(&#39;任务等待中被执行&#39;)
elif async.status == &#39;RETRY&#39;:
    print(&#39;任务异常后正在重试&#39;)
elif async.status == &#39;STARTED&#39;:
    print(&#39;任务已经开始被执行&#39;)
</code></pre>

<p>执行 add_task.py,添加任务,并获取任务ID</p>

<p>执行 run.py ,或者执行命令:celery worker -A celery_app_task -l info</p>

<p>执行 result.py,检查任务状态并获取结果</p>

<h4>多任务结构</h4>

<pre><code>pro_cel
    ├── celery_task# celery相关文件夹
    │   ├── celery.py   # celery连接和配置相关文件,必须叫这个名字
    │   └── tasks1.py    #  所有任务函数
    │    └── tasks2.py    #  所有任务函数
    ├── check_result.py # 检查结果
    └── send_task.py    # 触发任务
</code></pre>

<p>celery.py</p>

<pre><code>from celery import Celery

cel = Celery(&#39;celery_demo&#39;,
             broker=&#39;redis://127.0.0.1:6379/1&#39;,
             backend=&#39;redis://127.0.0.1:6379/2&#39;,
             # 包含以下两个任务文件,去相应的py文件中找任务,对多个任务做分类
             include=[&#39;celery_task.tasks1&#39;,
                      &#39;celery_task.tasks2&#39;
                      ])

# 时区
cel.conf.timezone = &#39;Asia/Shanghai&#39;
# 是否使用UTC
cel.conf.enable_utc = False
</code></pre>

<p>tasks1.py</p>

<pre><code>import time
from celery_task.celery import cel

@cel.task
def test_celery(res):
    time.sleep(5)
    return &#34;test_celery任务结果:%s&#34;%res
</code></pre>

<p>tasks2.py</p>

<pre><code>import time
from celery_task.celery import cel
@cel.task
def test_celery2(res):
    time.sleep(5)
    return &#34;test_celery2任务结果:%s&#34;%res
</code></pre>

<p>check_result.py</p>

<pre><code>from celery.result import AsyncResult
from celery_task.celery import cel

async = AsyncResult(id=&#34;08eb2778-24e1-44e4-a54b-56990b3519ef&#34;, app=cel)

if async.successful():
    result = async.get()
    print(result)
    # result.forget() # 将结果删除,执行完成,结果不会自动删除
    # async.revoke(terminate=True)  # 无论现在是什么时候,都要终止
    # async.revoke(terminate=False) # 如果任务还没有开始执行呢,那么就可以终止。
elif async.failed():
    print(&#39;执行失败&#39;)
elif async.status == &#39;PENDING&#39;:
    print(&#39;任务等待中被执行&#39;)
elif async.status == &#39;RETRY&#39;:
    print(&#39;任务异常后正在重试&#39;)
elif async.status == &#39;STARTED&#39;:
    print(&#39;任务已经开始被执行&#39;)
</code></pre>

<p>send_task.py</p>

<pre><code>from celery_task.tasks1 import test_celery
from celery_task.tasks2 import test_celery2

# 立即告知celery去执行test_celery任务,并传入一个参数
result = test_celery.delay(&#39;第一个的执行&#39;)
print(result.id)
result = test_celery2.delay(&#39;第二个的执行&#39;)
print(result.id)
</code></pre>

<p>添加任务(执行send_task.py),开启work:celery worker -A celery_task -l info  -P  eventlet,检查任务执行结果(执行check_result.py)</p>

<h2>5.Celery执行定时任务</h2>

<h4>设定时间让celery执行一个任务</h4>

<p>add_task.py</p>

<pre><code>from celery_app_task import add
from datetime import datetime

# 方式一
# v1 = datetime(2019, 2, 13, 18, 19, 56)
# print(v1)
# v2 = datetime.utcfromtimestamp(v1.timestamp())
# print(v2)
# result = add.apply_async(args=[1, 3], eta=v2)
# print(result.id)

# 方式二
ctime = datetime.now()
# 默认用utc时间
utc_ctime = datetime.utcfromtimestamp(ctime.timestamp())
from datetime import timedelta
time_delay = timedelta(seconds=10)
task_time = utc_ctime + time_delay

# 使用apply_async并设定时间
result = add.apply_async(args=[4, 3], eta=task_time)
print(result.id)
</code></pre>

<h4>类似于contab的定时任务</h4>

<p>多任务结构中celery.py修改如下</p>

<pre><code>from datetime import timedelta
from celery import Celery
from celery.schedules import crontab

cel = Celery(&#39;tasks&#39;, broker=&#39;redis://127.0.0.1:6379/1&#39;, backend=&#39;redis://127.0.0.1:6379/2&#39;, include=[
    &#39;celery_task.tasks1&#39;,
    &#39;celery_task.tasks2&#39;,
])
cel.conf.timezone = &#39;Asia/Shanghai&#39;
cel.conf.enable_utc = False

cel.conf.beat_schedule = {
    # 名字随意命名
    &#39;add-every-10-seconds&#39;: {
        # 执行tasks1下的test_celery函数
        &#39;task&#39;: &#39;celery_task.tasks1.test_celery&#39;,
        # 每隔2秒执行一次
        # &#39;schedule&#39;: 1.0,
        # &#39;schedule&#39;: crontab(minute=&#34;*/1&#34;),
        &#39;schedule&#39;: timedelta(seconds=2),
        # 传递参数
        &#39;args&#39;: (&#39;test&#39;,)
    },
    # &#39;add-every-12-seconds&#39;: {
    #     &#39;task&#39;: &#39;celery_task.tasks1.test_celery&#39;,
    #     每年4月11号,8点42分执行
    #     &#39;schedule&#39;: crontab(minute=42, hour=8, day_of_month=11, month_of_year=4),
    #     &#39;schedule&#39;: crontab(minute=42, hour=8, day_of_month=11, month_of_year=4),
    #     &#39;args&#39;: (16, 16)
    # },
}
</code></pre>

<p>启动一个beat:celery beat -A celery_task -l info</p>

<p>启动work执行:celery worker -A celery_task -l info -P  eventlet</p>

<h2>6.Django中使用Celery</h2>

<p>安装包</p>

<pre><code>celery==3.1.25
django-celery==3.1.20
</code></pre>

<p>在项目目录下创建celeryconfig.py</p>

<pre><code>import djcelery
djcelery.setup_loader()
CELERY_IMPORTS=(
    &#39;app01.tasks&#39;,
)
#有些情况可以防止死锁
CELERYD_FORCE_EXECV=True
# 设置并发worker数量
CELERYD_CONCURRENCY=4
#允许重试
CELERY_ACKS_LATE=True
# 每个worker最多执行100个任务被销毁,可以防止内存泄漏
CELERYD_MAX_TASKS_PER_CHILD=100
# 超时时间
CELERYD_TASK_TIME_LIMIT=12*30
</code></pre>

<p>在app01目录下创建tasks.py</p>

<pre><code>from celery import task
@task
def add(a,b):
    with open(&#39;a.text&#39;, &#39;a&#39;, encoding=&#39;utf-8&#39;) as f:
        f.write(&#39;a&#39;)
    print(a+b)
</code></pre>

<p>视图函数views.py</p>

<pre><code>from django.shortcuts import render,HttpResponse
from app01.tasks import add
from datetime import datetime
def test(request):
    # result=add.delay(2,3)
    ctime = datetime.now()
    # 默认用utc时间
    utc_ctime = datetime.utcfromtimestamp(ctime.timestamp())
    from datetime import timedelta
    time_delay = timedelta(seconds=5)
    task_time = utc_ctime + time_delay
    result = add.apply_async(args=[4, 3], eta=task_time)
    print(result.id)
    return HttpResponse(&#39;ok&#39;)
</code></pre>

<p>settings.py</p>

<pre><code>
INSTALLED_APPS = [
    ...
    &#39;djcelery&#39;,
    &#39;app01&#39;
]

...

from djagocele import celeryconfig
BROKER_BACKEND=&#39;redis&#39;
BOOKER_URL=&#39;redis://127.0.0.1:6379/1&#39;
CELERY_RESULT_BACKEND=&#39;redis://127.0.0.1:6379/2&#39;
</code></pre>

 

posted @ 2019-11-26 16:54  Maple_feng  阅读(1457)  评论(0编辑  收藏  举报