关于如何把markdown转化成html
1.首先是配置
md.py文件:
import os
import time
import markdown
from lib.log import logging
MD_FOLDER = "static/md"
HTML_FOLDER = "html/md_content"
if not os.path.exists(HTML_FOLDER):
os.mkdir(HTML_FOLDER)
def need_update(md_fp, html_fp):
if not os.path.exists(html_fp):
return True
if os.stat(md_fp).st_ctime > os.stat(html_fp).st_mtime:
return True
return False
def makesure_html_exists(filename, folder=""):
logging.debug(f"convert: {filename} in {folder}")
md_fp = os.path.join(MD_FOLDER, folder, f"{filename}.md")
html_fp = os.path.join(HTML_FOLDER, folder, f"{filename}.html")
if need_update(md_fp, html_fp):
logging.debug(f"convert: {md_fp} --> {html_fp} ing")
markdown.markdownFromFile(input=md_fp, output=html_fp, encoding="utf-8", extensions=["toc", "tables"])
logging.info(f"convert: {md_fp} --> {html_fp}")
log.md文件:
import os
import logging
LOG_FOLDER = "../log"
if not os.path.exists(LOG_FOLDER):
os.mkdir(LOG_FOLDER)
LOG_FORMAT = "[%(asctime)s] [%(levelname)s] %(message)s"
DATE_FORMAT = "%Y/%m/%d %H:%M:%S %p"
logging.basicConfig(level=logging.DEBUG, format=LOG_FORMAT, datefmt=DATE_FORMAT)
logging.debug("debug log")
logging.info("info log")
logging.warning("warning log")
logging.error("error log")
logging.critical("critical log")
auth.py文件
import os
import time
import datetime
import hashlib
from lib.log import logging
from lib.data_base import set_filedata, get_filedata, has_filedata, is_filedata, del_filedata
USERS_FILENAME = "users"
TOKENS_FILENAME = "tokens"
TOKEN_ALIVE_TIMEINTERVAL = 12 * 3600 # 12小时后登录超时
def has_user(username):
return has_filedata(USERS_FILENAME, username)
def is_user(username, mp):
return is_filedata(USERS_FILENAME, username, mp)
def add_user(username, mp):
set_filedata(USERS_FILENAME, username, mp)
def add_token(username, token):
set_filedata(
TOKENS_FILENAME,
token,
{
"username": username,
"timestamp": time.mktime(time.localtime(time.time())),
},
)
def make_token(username):
token = str(hashlib.sha1(os.urandom(24)).hexdigest())
add_token(username, token)
return token
def calculate_md5(username, password):
# 当前策略:前端计算md5传输过来,后端再加对每个人都不同的盐
m = hashlib.md5()
m.update((password + username + "cbzz!").encode("utf-8"))
return m.hexdigest()
def do_the_login(username, password):
mp = calculate_md5(username, password)
if not has_user(username):
add_user(username, mp)
return True, "Register", make_token(username)
elif is_user(username, mp):
return True, "Login", make_token(username)
else:
return False, "Login", ""
def is_alive(ts):
dt = datetime.datetime.utcfromtimestamp(ts)
dt_now = datetime.datetime.now()
return (dt_now - dt).seconds < TOKEN_ALIVE_TIMEINTERVAL
def search_token(token):
value = get_filedata(TOKENS_FILENAME, token)
if value and is_alive(value["timestamp"]):
return value["username"]
return None
def do_the_logout(token):
del_filedata(TOKENS_FILENAME, token)
def get_auth_status(cookies):
status = cookies.get("status", None)
action = cookies.get("action", None)
token = cookies.get("token", None)
logging.info(f"get_auth_status() in: status={status} action={action} token={token}")
content = {}
if status == None:
content = {"status": 0}
elif status == "True":
username = search_token(token)
if username != None:
content = {"status": 1, "action": action, "username": username}
else:
content = {"status": 2}
else:
content = {"status": 3}
status_comment = {
0: "游客进入主页",
1: "登录成功/注册成功",
2: "令牌失效(超时)",
3: "登陆失败(密码错误)",
}
logging.info(f"get_auth_status() out: {status_comment[content['status']]}, content={content}")
return content
main.py文件
from flask import request, Flask, render_template, redirect
from lib.md import makesure_html_exists
from lib.log import logging
from lib.auth import get_auth_status, do_the_login, do_the_logout
main = Flask(__name__, static_folder="static", static_url_path="/static", template_folder="html")
@main.route("/test")
def test():
content["n"] = request.args.get('n', type = int)
content["m"] = request.args.get('m', type = int)
content = get_auth_status(request.cookies)
return render_template("test.html", **content)
@main.route("/contact")
def contact():
content = get_auth_status(request.cookies)
return render_template("contact.html", **content)
@main.route("/introduction")
def introduction():
content = get_auth_status(request.cookies)
content["filename"] = "introduction"
makesure_html_exists("introduction")
return render_template("introduction.html", **content)
@main.route("/try1")
def try1():
content = get_auth_status(request.cookies)
content["filename"] = "try1"
makesure_html_exists("try1")
return render_template("index.html", **content)
@main.route("/")
def index():
content = get_auth_status(request.cookies)
return render_template("index.html", **content)
@main.route("/login", methods=["POST"])
def login():
"""
login (or register)
"""
username = request.form["nick_name"]
password = request.form["password"]
status, action, token = do_the_login(username, password)
resp = redirect(request.referrer)
resp.set_cookie("status", str(status))
resp.set_cookie("action", action)
resp.set_cookie("token", token)
return resp
@main.route("/logout", methods=["POST"])
def logout():
"""
logout
"""
token = request.cookies.get("token", None)
do_the_logout(token)
resp = redirect(request.referrer)
resp.delete_cookie("status")
resp.delete_cookie("action")
resp.delete_cookie("token")
return resp
2.如何转化
首先先创个md文件,内容根据markdown格式来
然后在main.py文件中插入@main.route指令
会自动生成一个html文件,而这个html文件显示的内容就是markdown转化而成的
在模版中插入 {% include "md_content/"+filename+".html" %}就相当于把markdown转化成html的内容放到这里

