# Fumadocs (Framework Mode, Next.js): Python
URL: /zh-TW/docs/next/integrations/content/python
Source: https://raw.githubusercontent.com/fuma-nama/fumadocs/refs/heads/main/apps/docs/content/docs/(framework)/[framework]/integrations/content/python.zh-TW.mdx

從 Python 套件產生 API 參考文件。

<Callout type="warn">
Python 支援目前仍處於實驗階段。
</Callout>

`fumadocs-python` 會根據 Python 套件的原始碼與 docstring 產生文件，並為每個模組與類別各建立一個頁面。先以 Python 指令將套件內容收集至 JSON 檔案，接著您可以將該檔案載入為內容來源，或轉換成 MDX 檔案。

## 設定 [#setup]

```package-install
fumadocs-python shiki
```

請使用 Python 指令產生 JSON 檔案：

```bash
# 安裝到您套件所使用的 Python 環境中
pip install ./node_modules/fumadocs-python

# 產生 httpx.json，可用 `--dir` 變更輸出目錄
fumapy-generate httpx

# 改以 NumPy 或 Sphinx 風格（而非 Google 風格）解析 docstring 區段
fumapy-generate httpx --docstring-style numpy
```

加入其元件的樣式：

```css title="Tailwind CSS"
@import 'tailwindcss';
@import 'fumadocs-ui/css/neutral.css';
@import 'fumadocs-ui/css/preset.css';
/* [!code ++] */
@import 'fumadocs-python/preset.css';
```

## 內容來源 [#content-source]

從 JSON 檔案建立來源，再將它傳入 `loader()`：

```ts title="lib/source.ts"
import { loader } from 'fumadocs-core/source';
import { createPython } from 'fumadocs-python';

const python = createPython({
  file: './httpx.json',
  // `httpx._client.Client` 的路徑為 `/docs/httpx/_client/Client`，
  // 若設為 `none`，路徑則為 `/docs/_client/Client`
  groupBy: 'module',
});

export const source = loader(await python.staticSource(), {
  baseUrl: '/docs',
  // 為側邊欄中的頁面加上 `module` 或 `class` 徽章
  plugins: [python.loaderPlugin()],
});
```

編譯並算繪頁面：

```tsx title="app/docs/[[...slug]]/page.tsx"
import { source } from '@/lib/source';
import { notFound } from 'next/navigation';
import { DocsBody, DocsPage, DocsTitle } from 'fumadocs-ui/layouts/docs/page';

export default async function Page({ params }: PageProps<'/docs/[[...slug]]'>) {
  const page = source.getPage((await params).slug);
  if (!page) notFound();

  const data = await page.data.load();
  // 傳入 MDX 元件以覆寫預設元件
  const { body, toc } = await data.render();

  return (
    <DocsPage toc={toc}>
      <DocsTitle>{page.data.title}</DocsTitle>
      <DocsBody>{body}</DocsBody>
    </DocsPage>
  );
}
```

### 編譯器選項 [#compiler-options]

Docstring 本身就是 Markdown，因此同樣可以套用 remark 與 rehype 外掛：

```ts title="lib/source.ts"
import { createPython } from 'fumadocs-python';
import remarkMath from 'remark-math';
import rehypeKatex from 'rehype-katex';

const python = createPython({
  file: './httpx.json',
  // 程式碼區塊的 Shiki 選項，例如原始碼與 docstring 範例
  rehypeCodeOptions: {
    themes: {
      light: 'github-light',
      dark: 'github-dark',
    },
  },
  remarkPlugins: [remarkMath],
  rehypePlugins: [rehypeKatex],
});
```

### Dynamic 來源 [#dynamic-source]

`staticSource()` 只會讀取 JSON 檔案一次。若要在不重新啟動伺服器的情況下讀取重新產生的檔案，請搭配使用 `dynamicSource()` 與 `dynamicLoader()`：

```ts title="lib/source.ts"
import { dynamicLoader } from 'fumadocs-core/source';

const pythonLoader = dynamicLoader(python.dynamicSource(), {
  baseUrl: '/docs',
  plugins: [python.loaderPlugin()],
});

export function getSource() {
  return pythonLoader.get();
}
```

請使用 `await getSource()` 取代 `source`。呼叫 `pythonLoader.invalidate()` 之後，下一次呼叫 `getSource()` 時就會重新讀取檔案。

## MDX 檔案 [#mdx-files]

若要將這些頁面與您的其他內容放在一起，請使用指令碼將 JSON 轉換為 MDX 檔案。頁面之間的連結會以 `baseUrl` 開頭，因此請將它設為輸出目錄的 URL：

```js tab="scripts/generate-docs.mjs"
import * as fs from 'node:fs/promises';
import * as Python from 'fumadocs-python';

const content = JSON.parse(await fs.readFile('./httpx.json', 'utf-8'));
// 移除已刪除模組的頁面
await fs.rm('content/docs/httpx', { recursive: true, force: true });

await Python.write(Python.convert(content, { baseUrl: '/docs' }), 'content/docs');
```

```tsx tab="components/mdx.tsx"
import defaultMdxComponents from 'fumadocs-ui/mdx';
import type { MDXComponents } from 'mdx/types';
import * as Python from 'fumadocs-python/components';

const { createPythonComponents, ...PythonComponents } = Python;

export function getMDXComponents(components?: MDXComponents): MDXComponents {
  return {
    ...defaultMdxComponents,
    ...PythonComponents,
    ...components,
  };
}
```