Skip to content

Commit 7c005d8

Browse files
committed
doc: update docs/fastapi.md
1 parent 1a829ec commit 7c005d8

File tree

1 file changed

+30
-11
lines changed

1 file changed

+30
-11
lines changed

docs/fastapi.md

Lines changed: 30 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -560,19 +560,27 @@ async def read_users():
560560

561561
安全性
562562
---
563-
### 基于Token的认证
563+
564+
### 基于 Token 的认证
565+
<!--rehype:wrap-class=col-span-2-->
564566

565567
```python
566568
from fastapi import FastAPI, Depends, HTTPException
567569
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
568570
from pydantic import BaseModel
569571

570572
app = FastAPI()
573+
```
574+
575+
使用 OAuth2PasswordBearer 创建一个 token 依赖
571576

572-
# 使用 OAuth2PasswordBearer 创建一个 token 依赖
577+
```python
573578
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
579+
```
580+
581+
假设这是你的用户数据库
574582

575-
# 假设这是你的用户数据库
583+
```python
576584
fake_users_db = {
577585
"johndoe": {
578586
"username": "johndoe",
@@ -582,15 +590,21 @@ fake_users_db = {
582590
"disabled": False,
583591
}
584592
}
593+
```
594+
595+
创建一个用户模型
585596

586-
# 创建一个用户模型
597+
```python
587598
class User(BaseModel):
588599
username: str
589600
email: str
590601
full_name: str
591602
disabled: bool
603+
```
604+
605+
创建一个简单的认证函数
592606

593-
# 创建一个简单的认证函数
607+
```python
594608
def fake_hash_password(password: str):
595609
return "fakehashed" + password
596610

@@ -603,8 +617,11 @@ def fake_decode_token(token: str):
603617
# 这个函数应该验证 token 并返回用户信息
604618
# 这里我们只是简单地返回了用户名
605619
return get_user(fake_users_db, token)
620+
```
621+
622+
创建一个依赖,用于从请求中获取 token 并验证用户
606623

607-
# 创建一个依赖,用于从请求中获取 token 并验证用户
624+
```python
608625
async def get_current_user(token: str = Depends(oauth2_scheme)):
609626
user = fake_decode_token(token)
610627
if not user:
@@ -636,20 +653,22 @@ async def read_users_me(current_user: User = Depends(get_current_user)):
636653
from fastapi import FastAPI
637654

638655
app = FastAPI()
656+
```
657+
658+
在生产环境中,你应该使用一个真正的证书和私钥,你可以从像 Let's Encrypt 这样的证书颁发机构获得免费的证书,或者使用 OpenSSL 生成自签名证书
639659

640-
# 在生产环境中,你应该使用一个真正的证书和私钥
641-
# 你可以从像 Let's Encrypt 这样的证书颁发机构获得免费的证书
642-
# 或者使用 OpenSSL 生成自签名证书
660+
```python
643661
@app.get("/https")
644662
async def read_https():
645663
return {"message": "Hello, HTTPS!"}
646-
647664
```
665+
648666
启动服务器时,使用以下命令来指定证书和私钥:
667+
649668
```bash
650669
uvicorn main:app --host 0.0.0.0 --port 443 --ssl-keyfile /path/to/your/key.pem --ssl-certfile /path/to/your/cert.pem
651-
652670
```
671+
653672
FastAPI 默认支持 HTTPS,你只需要提供证书和私钥即可。
654673

655674
待更新

0 commit comments

Comments
 (0)