p

python

用 bcrypt 進行密碼加密與驗證,支援 salt、自動安全雜湊,保護你的使用者資料不被爆破!適合登入驗證與帳號系統 🚀

0 0 0 1
1 import bcrypt
2
3
4 def encode_password(password: str) -> str:
5 salt = bcrypt.gensalt()
6 hashed = bcrypt.hashpw(password.encode(), salt)
7 return hashed.decode()
8
9
10 def check_password(password: str, hashed: str) -> bool:

這是一個使用 Streamlit 實現的簡單計算器,支援中英文語系,提供加法和減法運算功能,適合快速數學計算。

0 0 0 1
1 import streamlit as st
2
3 # 多國語系字典
4 LANGUAGES = {
5 "zh": {
6 "title": "簡單計算器",
7 "instruction": "請輸入兩個數字,選擇運算方式:",
8 "num1": "數字 1",
9 "num2": "數字 2",
10 "operation": "選擇運算方式",

此程式碼用於取得目前 Python 環境中所有已安裝的套件名稱和版本,並將結果整理成 CSV 檔案,方便進行記錄、分享或系統排查。

0 0 0 1
1 # 引入需要用到的套件
2 import pandas as pd # 用來處理資料,還能幫我們存成 CSV 檔
3 from pkg_resources import working_set # 用來拿到所有已安裝的套件清單
4
5 # 步驟 1: 把所有已安裝的套件名稱和版本抓出來,直接變成 Pandas DataFrame
6 # 用列表生成式搭配 DataFrame,省去不必要的中間變數
7 df_packages = pd.DataFrame(
8 [(pkg.key, pkg.version) for pkg in working_set],
9 columns=["Package", "Version"]
10 ).sort_values(by="Package")
Last active 5 hours ago api authentication fastapi header python security

FastAPI 可透過 Header 讀取請求標頭,並透過 Depends 進行依賴注入(Dependency Injection),適用於 API Token 驗證、身份驗證、請求處理 等場景。

0 0 0 3
1 from fastapi import FastAPI, Header, HTTPException
2
3 app = FastAPI()
4
5 @app.get("/secure-data")
6 async def secure_data(api_key: str = Header(None)):
7 if api_key != "my_secure_token":
8 raise HTTPException(status_code=401, detail="無效的 API 金鑰")
9 return {"message": "驗證成功,提供安全數據"}

contextlib.contextmanager 可用於建立自訂的 with 語句上下文管理器,適用於 資源管理(如檔案、資料庫連線、鎖定機制),確保進入與退出時執行適當的操作。

0 0 0 3
1 from contextlib import contextmanager
2
3 @contextmanager
4 def custom_context(name):
5 print(f"進入上下文: {name}")
6 try:
7 yield name # 提供資源
8 finally:
9 print(f"退出上下文: {name}")
Last active 5 hours ago errno error-handling file-io python system-calls

errno 提供標準錯誤代碼,適用於 檔案操作、系統調用、例外處理,可提高錯誤訊息的可讀性,並方便比對特定錯誤類型。

0 0 0 3
1 import errno
2 import os
3
4 try:
5 os.remove("non_existent_file.txt") # 嘗試刪除不存在的檔案
6 except OSError as e:
7 if e.errno == errno.ENOENT:
8 print("錯誤:檔案不存在")
9 elif e.errno == errno.EACCES:
10 print("錯誤:權限不足")