portal/plugins/cms_functions.py

98 lines
2.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
CMS Jinja2 模板函数插件
注册到 ServerEnv供 index.ui 等模板使用
函数:
get_site_config() → dict
get_published_content(content_type, limit) → list[dict]
get_latest_news(limit) → list[dict]
"""
from ahserver.serverenv import ServerEnv
from sqlor.dbpools import DBPools
from appPublic.jsonConfig import getConfig
import os
_workdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
_config = None
_db = None
def _get_db():
global _config, _db
if _db is None:
_config = getConfig(_workdir)
_db = DBPools(_config.databases)
return _db
async def get_site_config():
"""获取站点配置"""
try:
db = _get_db()
async with db.sqlorContext('ocai_cms') as sor:
rows = await sor.sqlExe(
"SELECT config_key, config_value FROM cms_site_config", {}
)
cfg = {}
for r in rows:
cfg[r['config_key']] = r['config_value']
return cfg
except Exception:
return {}
async def get_published_content(content_type, limit=10):
"""获取已发布内容"""
try:
db = _get_db()
async with db.sqlorContext('ocai_cms') as sor:
rows = await sor.sqlExe(
"SELECT c.id, c.title, c.subtitle, c.summary_text, c.image_url, "
"c.tags, c.body, cat.name as category_name "
"FROM cms_content c "
"LEFT JOIN cms_categories cat ON c.category_id = cat.id "
"WHERE c.content_type = %(ct)s AND c.status = 'published' "
"ORDER BY c.sort_order, c.created_at DESC "
"LIMIT %(lim)s",
{"ct": content_type, "lim": int(limit)}
)
return list(rows)
except Exception:
return []
async def get_latest_news(limit=3):
"""获取最新新闻"""
try:
db = _get_db()
async with db.sqlorContext('ocai_cms') as sor:
rows = await sor.sqlExe(
"SELECT c.id, c.title, c.subtitle, c.summary_text, c.image_url, "
"c.published_at, cat.name as category_name "
"FROM cms_content c "
"LEFT JOIN cms_categories cat ON c.category_id = cat.id "
"WHERE c.content_type = 'news' AND c.status = 'published' "
"ORDER BY c.published_at DESC, c.created_at DESC "
"LIMIT %(lim)s",
{"lim": int(limit)}
)
return list(rows)
except Exception:
return []
def get_module_dbname(module_name):
"""Portal 所有模块共用 ocai_cms 数据库"""
return 'ocai_cms'
def load_cms():
g = ServerEnv()
g.get_site_config = get_site_config
g.get_published_content = get_published_content
g.get_latest_news = get_latest_news
g.get_module_dbname = get_module_dbname
load_cms()