Compare commits
3 Commits
bb2f687c91
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4cdbefbd15 | ||
|
|
b4ee793b6f | ||
|
|
4348671562 |
178
.dockerignore
Normal file
178
.dockerignore
Normal file
@@ -0,0 +1,178 @@
|
||||
# ---> Python
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# UV
|
||||
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
#uv.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/latest/usage/project/#working-with-version-control
|
||||
.pdm.toml
|
||||
.pdm-python
|
||||
.pdm-build/
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
.idea/
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
|
||||
|
||||
data/
|
||||
4
.gitignore
vendored
4
.gitignore
vendored
@@ -166,7 +166,7 @@ cython_debug/
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
.idea/
|
||||
|
||||
# Ruff stuff:
|
||||
.ruff_cache/
|
||||
@@ -174,3 +174,5 @@ cython_debug/
|
||||
# PyPI configuration file
|
||||
.pypirc
|
||||
|
||||
|
||||
data/
|
||||
|
||||
22
Dockerfile
Normal file
22
Dockerfile
Normal file
@@ -0,0 +1,22 @@
|
||||
# 使用官方 Python 镜像作为基础
|
||||
FROM python:3.12-slim
|
||||
|
||||
# 设置工作目录
|
||||
WORKDIR /app
|
||||
|
||||
# 将你的项目文件复制到工作目录
|
||||
COPY . .
|
||||
|
||||
# 安装依赖
|
||||
# --no-cache-dir: 不存储缓存,保持镜像小巧
|
||||
# --upgrade pip: 升级 pip
|
||||
# -r requirements.txt: 从文件安装
|
||||
RUN pip install --no-cache-dir --upgrade pip -r requirements.txt
|
||||
|
||||
RUN chmod +x /app/start.sh
|
||||
|
||||
# 暴露 Gunicorn 运行的端口
|
||||
EXPOSE 8000
|
||||
|
||||
# 容器启动时运行的命令
|
||||
CMD ["/app/start.sh"]
|
||||
202
api_server.py
Normal file
202
api_server.py
Normal file
@@ -0,0 +1,202 @@
|
||||
import os
|
||||
import datetime
|
||||
from fastapi import FastAPI, Depends, HTTPException
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import create_engine, Column, String, Integer, Text
|
||||
from sqlalchemy.orm import sessionmaker, Session, declarative_base
|
||||
from enum import IntEnum
|
||||
|
||||
# --- 数据库设置 ---
|
||||
# 将数据库放在一个专门的 /data 子目录中
|
||||
DB_DIR = "/app/data"
|
||||
os.makedirs(DB_DIR, exist_ok=True)
|
||||
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/safe-marks.db"
|
||||
|
||||
engine = create_engine(
|
||||
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
|
||||
)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
# --- SQLAlchemy 模型 (表结构) ---
|
||||
class Extension(Base):
|
||||
__tablename__ = "extensions"
|
||||
ID = Column(String, primary_key=True, index=True)
|
||||
NAME = Column(String, nullable=False)
|
||||
SAFE = Column(Integer, nullable=False)
|
||||
UPDATE_DATE = Column(String, nullable=False)
|
||||
NOTES = Column(Text, nullable=True)
|
||||
|
||||
|
||||
# --- Pydantic 模型 (用于 API 数据验证) ---
|
||||
class SafeStatus(IntEnum):
|
||||
safe = 1
|
||||
unsure = 0
|
||||
unsafe = -1
|
||||
unknown = -2
|
||||
|
||||
|
||||
class ExtensionBase(BaseModel):
|
||||
ID: str = Field(..., description="插件唯一ID")
|
||||
NAME: str = Field(..., description="插件名称")
|
||||
NOTES: str | None = Field(None, description="备注")
|
||||
|
||||
|
||||
class ExtensionCreate(ExtensionBase):
|
||||
SAFE: SafeStatus = Field(..., description="安全状态: 1, 0, -1, -2")
|
||||
|
||||
|
||||
class ExtensionBatchCreateItem(ExtensionBase):
|
||||
pass
|
||||
|
||||
|
||||
class ExtensionUpdatePayload(BaseModel):
|
||||
NAME: str | None = None
|
||||
SAFE: SafeStatus | None = None
|
||||
NOTES: str | None = None
|
||||
|
||||
|
||||
class ExtensionInDB(ExtensionBase):
|
||||
SAFE: SafeStatus
|
||||
UPDATE_DATE: str
|
||||
|
||||
model_config = {
|
||||
"from_attributes": True
|
||||
}
|
||||
|
||||
|
||||
class ExtensionNecessary(BaseModel):
|
||||
ID: str
|
||||
SAFE: SafeStatus
|
||||
|
||||
model_config = {
|
||||
"from_attributes": True
|
||||
}
|
||||
|
||||
|
||||
# --- FastAPI 应用实例 ---
|
||||
app = FastAPI(title="Safe Marks API")
|
||||
|
||||
|
||||
# --- 数据库依赖 ---
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
# --- 辅助函数:获取数据库条目 ---
|
||||
def get_extension_by_id(db: Session, item_id: str) -> Extension | None:
|
||||
return db.query(Extension).filter(Extension.ID == item_id).first()
|
||||
|
||||
|
||||
# --- API 路由 ---
|
||||
|
||||
@app.get("/api/v1/ext/query_all", response_model=list[ExtensionInDB], summary="查询所有插件 (完整信息)")
|
||||
def query_all_extensions(db: Session = Depends(get_db)):
|
||||
extensions = db.query(Extension).all()
|
||||
return extensions
|
||||
|
||||
|
||||
@app.get("/api/v1/ext/query_necessary", response_model=list[ExtensionNecessary], summary="查询所有插件 (仅 ID 和 SAFE)")
|
||||
def query_necessary_extensions(db: Session = Depends(get_db)):
|
||||
extensions = db.query(Extension).all()
|
||||
return extensions
|
||||
|
||||
|
||||
@app.post("/api/v1/ext/add_one", response_model=ExtensionInDB, summary="添加单个插件")
|
||||
def add_one_extension(extension: ExtensionCreate, db: Session = Depends(get_db)):
|
||||
if get_extension_by_id(db, extension.ID):
|
||||
raise HTTPException(status_code=400, detail=f"Extension with ID {extension.ID} already exists.")
|
||||
|
||||
current_date = datetime.datetime.now().isoformat()
|
||||
# 已更新: 使用 .model_dump() 替代 .dict()
|
||||
db_extension = Extension(
|
||||
**extension.model_dump(),
|
||||
UPDATE_DATE=current_date
|
||||
)
|
||||
|
||||
db.add(db_extension)
|
||||
db.commit()
|
||||
db.refresh(db_extension)
|
||||
return db_extension
|
||||
|
||||
|
||||
@app.post("/api/v1/ext/add_batch", response_model=list[ExtensionInDB], summary="批量添加插件 (SAFE 自动设为 'unknown')")
|
||||
def add_batch_extensions(items: list[ExtensionBatchCreateItem], db: Session = Depends(get_db)):
|
||||
created_extensions = []
|
||||
current_date = datetime.datetime.now().isoformat()
|
||||
|
||||
for item in items:
|
||||
if get_extension_by_id(db, item.ID):
|
||||
# raise HTTPException(status_code=400, detail=f"Extension with ID {item.ID} already exists.")
|
||||
continue
|
||||
|
||||
# 已更新: 使用 .model_dump() 替代 .dict()
|
||||
db_extension = Extension(
|
||||
**item.model_dump(),
|
||||
SAFE=SafeStatus.unknown,
|
||||
UPDATE_DATE=current_date
|
||||
)
|
||||
db.add(db_extension)
|
||||
created_extensions.append(db_extension)
|
||||
|
||||
db.commit()
|
||||
for ext in created_extensions:
|
||||
db.refresh(ext)
|
||||
|
||||
return created_extensions
|
||||
|
||||
|
||||
@app.put("/api/v1/ext/update_one/{item_id}", response_model=ExtensionInDB, summary="更新单个插件")
|
||||
def update_one_extension(
|
||||
item_id: str,
|
||||
update_data: ExtensionUpdatePayload,
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
db_ext = get_extension_by_id(db, item_id)
|
||||
if not db_ext:
|
||||
raise HTTPException(status_code=404, detail=f"Extension with ID {item_id} not found.")
|
||||
|
||||
# 已更新: 使用 .model_dump() 替代 .dict()
|
||||
update_dict = update_data.model_dump(exclude_unset=True)
|
||||
if not update_dict:
|
||||
raise HTTPException(status_code=400, detail="No update data provided.")
|
||||
|
||||
updated = False
|
||||
for key, value in update_dict.items():
|
||||
if getattr(db_ext, key) != value:
|
||||
setattr(db_ext, key, value)
|
||||
updated = True
|
||||
|
||||
if updated:
|
||||
db_ext.UPDATE_DATE = datetime.datetime.now().isoformat()
|
||||
|
||||
db.commit()
|
||||
db.refresh(db_ext)
|
||||
return db_ext
|
||||
|
||||
|
||||
@app.delete("/api/v1/ext/delete_one/{item_id}", response_model=dict[str, str], summary="删除单个插件")
|
||||
def delete_one_extension(item_id: str, db: Session = Depends(get_db)):
|
||||
db_ext = get_extension_by_id(db, item_id)
|
||||
if not db_ext:
|
||||
raise HTTPException(status_code=404, detail=f"Extension with ID {item_id} not found.")
|
||||
|
||||
db.delete(db_ext)
|
||||
db.commit()
|
||||
|
||||
return {"message": f"Extension with ID {item_id} successfully deleted."}
|
||||
|
||||
|
||||
# --- 运行服务 (用于开发) ---
|
||||
# 注意:在生产环境中,应使用 Gunicorn 或 Uvicorn 命令行工具启动
|
||||
# 例如: uvicorn api_server:app --reload
|
||||
# if __name__ == "__main__":
|
||||
# import uvicorn
|
||||
#
|
||||
# print("启动 FastAPI 服务,访问 http://127.0.0.1:8000/docs 查看 API 文档")
|
||||
# uvicorn.run(app, host="127.0.0.1", port=8000)
|
||||
9
compose.yaml
Normal file
9
compose.yaml
Normal file
@@ -0,0 +1,9 @@
|
||||
services:
|
||||
api:
|
||||
build: .
|
||||
container_name: safe-marks-server-api
|
||||
ports:
|
||||
- "127.0.0.1:17701:8000"
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
restart: unless-stopped
|
||||
8
create_db.py
Normal file
8
create_db.py
Normal file
@@ -0,0 +1,8 @@
|
||||
from api_server import Base, engine
|
||||
|
||||
print("Creating database and tables...")
|
||||
|
||||
# create_all 会检查表是否存在,只创建不存在的表
|
||||
Base.metadata.create_all(bind=engine, checkfirst=True)
|
||||
|
||||
print("Database and tables created successfully (if they didn't exist).")
|
||||
5
requirements.txt
Normal file
5
requirements.txt
Normal file
@@ -0,0 +1,5 @@
|
||||
fastapi[all]
|
||||
sqlalchemy
|
||||
requests
|
||||
pydantic
|
||||
gunicorn
|
||||
Reference in New Issue
Block a user