Files
mica/README.md
T

63 lines
3.5 KiB
Markdown
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.
# MICA
**Modular Infrastructure for Content Applications**(面向内容应用的模块化基础设施)是一个 Python 内容后端。社区站可以用它发布短帖,新闻站可以用它发布文章。前端通过同一套 HTTP 接口提交内容和读取已发布内容,自行决定如何展示。
名字里的 **Modular** 指核心和插件各有职责,**Infrastructure** 指多个前端可以共用这个后端,**Content Applications** 指围绕写入、发布和展示构建的应用。英文单词 *mica* 意为“云母”,读作 *MY-kuh*。代码使用小写包名 `mica`,核心契约位于 `mica.core`,内置扩展位于 `mica.extensions`。
## 第一版
核心维护内容 ID、草稿和发布状态,在 SQLite 中保存内容,并通过 HTTP 提供写入鉴权和公开查询。内容扩展声明字段规则,两种前端共用存储和发布流程。
| 扩展 | 写入类型 | 必填文本 | 可选文本 |
| --- | --- | --- | --- |
| 短帖 | `posts` | `body` | 无 |
| 文章 | `articles` | `title`、`body` | `summary` |
首版适合由一个受信任的编辑服务写入。终端用户登录、作者权限、评论、关注和个性化排序留待后续版本。
## 在本地试用
需要 Python 3.9 或以上版本,仅使用标准库。在仓库根目录运行以下命令。请在同一个终端保留生成的令牌,供写入客户端使用。
```sh
export MICA_WRITE_TOKEN="$(python3 -c 'import secrets; print(secrets.token_urlsafe(32))')"
python3 -m mica &
```
开发服务器默认监听 `127.0.0.1:8000`,数据库是当前目录下的 `mica.sqlite3`。可通过 `MICA_PORT` 和 `MICA_DATABASE` 修改。部署时可用 WSGI 服务器调用 `mica.api.create_app(database, write_token)`,并在对外入口启用 HTTPS。写入令牌只应由受信任的服务端持有。
创建草稿,取出响应里的 ID,发布并公开读取:
```sh
id=$(curl -fsS http://127.0.0.1:8000/content \
-H "Authorization: Bearer $MICA_WRITE_TOKEN" -H 'Content-Type: application/json' \
-d '{"type":"articles","fields":{"title":"社区简报","body":"本周六举行读书会。"}}' \
| python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])')
curl -fsS -X POST -H "Authorization: Bearer $MICA_WRITE_TOKEN" \
"http://127.0.0.1:8000/content/$id/publish"
curl -fsS "http://127.0.0.1:8000/content/$id"
curl -fsS 'http://127.0.0.1:8000/content?type=articles&limit=20&offset=0'
```
草稿的 `published_at` 为 `null`,公开列表会跳过它,按 ID 读取返回 404。首次发布写入 UTC 时间,重复发布保留原时间。列表按发布时间倒序,相同时间按 ID 倒序。默认每页 20 条,上限 100 条。写入时需提供非空文本,未知字段会返回 400;JSON 请求体上限为 1 MiB。
## 加一个内容类型
扩展组织参考 [OpenBB Platform](https://github.com/openbq-org/OpenBB/tree/develop/openbb_platform)。MICA 启动时发现并导入 `mica/extensions/` 下名称不以下划线开头的模块。每个模块导出一个名为 `content_type` 的 `ContentType` 实例;类型重名或未提供契约时启动失败。扩展是会在服务进程中执行的受信任 Python 代码。
例如新建 `mica/extensions/notices.py`:
```python
from ..core import ContentType
content_type = ContentType("notices", required=("subject", "body"))
```
重启服务后即可用 `"type":"notices"` 创建公告草稿,并按同一套接口发布和查询。
## 检查
```sh
python3 -B -m unittest discover -s tests -v
```