Skip to content

Commit d6cf5d8

Browse files
committed
update the ruff rules and format the code
1 parent 5b09237 commit d6cf5d8

File tree

20 files changed

+73
-59
lines changed

20 files changed

+73
-59
lines changed

.pre-commit-config.yaml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,5 @@ repos:
2323
- '--skip-string-normalization'
2424
- '--line-length'
2525
- '120'
26+
- '--target-version'
27+
- 'py38'

.ruff.toml

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,15 @@
1+
select = [
2+
"E",
3+
"F",
4+
"W505",
5+
"PT018",
6+
"Q000",
7+
"SIM101",
8+
"SIM114",
9+
"PGH004",
10+
"PLE1142",
11+
"RUF100",
12+
]
113
ignore = ["F401"]
214
line-length = 120
315
format = "grouped"
@@ -14,7 +26,7 @@ parametrize-values-type = "tuple"
1426
avoid-escape = false
1527
docstring-quotes = "double"
1628
inline-quotes = "single"
17-
multiline-quotes = "double"
29+
multiline-quotes = "single"
1830

1931
[flake8-unused-arguments]
2032
ignore-variadic-names = true

backend/app/alembic/env.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
sys.path.append('../../')
1313

14-
from backend.app.core import path_conf # noqa
14+
from backend.app.core import path_conf # noqa: E402
1515

1616
if not os.path.exists(path_conf.Versions):
1717
os.makedirs(path_conf.Versions)
@@ -26,12 +26,12 @@
2626

2727
# add your model's MetaData object here
2828
# for 'autogenerate' support
29-
from backend.app.models import MappedBase # noqa
29+
from backend.app.models import MappedBase # noqa: E402
3030

3131
target_metadata = MappedBase.metadata
3232

3333
# other values from the config, defined by the needs of env.py,
34-
from backend.app.database.db_mysql import SQLALCHEMY_DATABASE_URL # noqa
34+
from backend.app.database.db_mysql import SQLALCHEMY_DATABASE_URL # noqa: E402
3535

3636
config.set_main_option('sqlalchemy.url', SQLALCHEMY_DATABASE_URL)
3737

@@ -48,12 +48,12 @@ def run_migrations_offline():
4848
script output.
4949
5050
"""
51-
url = config.get_main_option("sqlalchemy.url")
51+
url = config.get_main_option('sqlalchemy.url')
5252
context.configure(
5353
url=url,
5454
target_metadata=target_metadata,
5555
literal_binds=True,
56-
dialect_opts={"paramstyle": "named"},
56+
dialect_opts={'paramstyle': 'named'},
5757
)
5858

5959
with context.begin_transaction():
@@ -77,7 +77,7 @@ async def run_migrations_online():
7777
connectable = AsyncEngine(
7878
engine_from_config(
7979
config.get_section(config.config_ini_section),
80-
prefix="sqlalchemy.",
80+
prefix='sqlalchemy.',
8181
poolclass=pool.NullPool,
8282
future=True,
8383
)

backend/app/api/jwt.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
from fastapi import Depends
77
from fastapi.security import OAuth2PasswordBearer
8-
from jose import jwt # noqa
8+
from jose import jwt
99
from passlib.context import CryptContext
1010
from pydantic import ValidationError
1111
from typing_extensions import Annotated
@@ -54,7 +54,7 @@ def create_access_token(data: Union[int, Any], expires_delta: Union[timedelta, N
5454
expires = datetime.utcnow() + expires_delta
5555
else:
5656
expires = datetime.utcnow() + timedelta(settings.TOKEN_EXPIRE_MINUTES)
57-
to_encode = {"exp": expires, "sub": str(data)}
57+
to_encode = {'exp': expires, 'sub': str(data)}
5858
encoded_jwt = jwt.encode(to_encode, settings.TOKEN_SECRET_KEY, settings.TOKEN_ALGORITHM)
5959
return encoded_jwt
6060

backend/app/api/v1/task_demo.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -24,17 +24,17 @@ async def task_demo_get():
2424
for job in scheduler.get_jobs():
2525
tasks.append(
2626
{
27-
"id": job.id,
28-
"func_name": job.func_ref,
29-
"trigger": str(job.trigger),
30-
"executor": job.executor,
27+
'id': job.id,
28+
'func_name': job.func_ref,
29+
'trigger': str(job.trigger),
30+
'executor': job.executor,
3131
# "args": str(job.args),
3232
# "kwargs": job.kwargs,
33-
"name": job.name,
34-
"misfire_grace_time": job.misfire_grace_time,
35-
"coalesce": job.coalesce,
36-
"max_instances": job.max_instances,
37-
"next_run_time": job.next_run_time,
33+
'name': job.name,
34+
'misfire_grace_time': job.misfire_grace_time,
35+
'coalesce': job.coalesce,
36+
'max_instances': job.max_instances,
37+
'next_run_time': job.next_run_time,
3838
}
3939
)
4040
return {'msg': 'success', 'data': tasks}

backend/app/common/exception/exception_handler.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ def _get_exception_code(status_code):
2727
"""
2828
try:
2929
STATUS_PHRASES[status_code]
30-
except Exception: # noqa
30+
except Exception:
3131
code = 400
3232
else:
3333
code = status_code
@@ -36,7 +36,7 @@ def _get_exception_code(status_code):
3636

3737
def register_exception(app: FastAPI):
3838
@app.exception_handler(HTTPException)
39-
def http_exception_handler(request: Request, exc: HTTPException): # noqa
39+
def http_exception_handler(request: Request, exc: HTTPException):
4040
"""
4141
全局HTTP异常处理
4242
@@ -51,7 +51,7 @@ def http_exception_handler(request: Request, exc: HTTPException): # noqa
5151
)
5252

5353
@app.exception_handler(Exception)
54-
def all_exception_handler(request: Request, exc): # noqa
54+
def all_exception_handler(request: Request, exc):
5555
"""
5656
全局异常处理
5757

backend/app/common/log.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,16 @@ def log() -> loguru.Logger:
1717
os.mkdir(path_conf.LogPath)
1818

1919
# 日志文件
20-
log_file = os.path.join(path_conf.LogPath, "FastBlog.log")
20+
log_file = os.path.join(path_conf.LogPath, 'FastBlog.log')
2121

2222
# loguru日志
2323
# more: https://github.com/Delgan/loguru#ready-to-use-out-of-the-box-without-boilerplate
2424
logger.add(
2525
log_file,
2626
encoding='utf-8',
27-
level="DEBUG",
27+
level='DEBUG',
2828
rotation='00:00', # 每天 0 点创建一个新日志文件
29-
retention="7 days", # 定时自动清理文件
29+
retention='7 days', # 定时自动清理文件
3030
enqueue=True, # 异步安全
3131
backtrace=True, # 错误跟踪
3232
diagnose=True,

backend/app/common/pagination.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from fastapi_pagination.links.bases import create_links
1111
from pydantic import BaseModel
1212

13-
T = TypeVar("T")
13+
T = TypeVar('T')
1414

1515
"""
1616
重写分页库:fastapi-pagination
@@ -19,8 +19,8 @@
1919

2020

2121
class Params(BaseModel, AbstractParams):
22-
page: int = Query(1, ge=1, description="Page number")
23-
size: int = Query(20, gt=0, le=100, description="Page size") # 默认 20 条记录
22+
page: int = Query(1, ge=1, description='Page number')
23+
size: int = Query(20, gt=0, le=100, description='Page size') # 默认 20 条记录
2424

2525
def to_raw_params(self) -> RawParams:
2626
return RawParams(
@@ -51,10 +51,10 @@ def create(
5151
total_pages = math.ceil(total / params.size)
5252
links = create_links(
5353
**{
54-
"first": {"page": 1, "size": f"{size}"},
55-
"last": {"page": f"{math.ceil(total / params.size)}", "size": f"{size}"} if total > 0 else None,
56-
"next": {"page": f"{page + 1}", "size": f"{size}"} if (page + 1) <= total_pages else None,
57-
"prev": {"page": f"{page - 1}", "size": f"{size}"} if (page - 1) >= 1 else None,
54+
'first': {'page': 1, 'size': f'{size}'},
55+
'last': {'page': f'{math.ceil(total / params.size)}', 'size': f'{size}'} if total > 0 else None,
56+
'next': {'page': f'{page + 1}', 'size': f'{size}'} if (page + 1) <= total_pages else None,
57+
'prev': {'page': f'{page - 1}', 'size': f'{size}'} if (page - 1) >= 1 else None,
5858
}
5959
).dict()
6060

backend/app/common/redis.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,10 @@ async def open(self):
2828
try:
2929
await self.ping()
3030
except TimeoutError:
31-
log.error("❌ 数据库 redis 连接超时")
31+
log.error('❌ 数据库 redis 连接超时')
3232
sys.exit()
3333
except AuthenticationError:
34-
log.error("❌ 数据库 redis 连接认证失败")
34+
log.error('❌ 数据库 redis 连接认证失败')
3535
sys.exit()
3636
except Exception as e:
3737
log.error('❌ 数据库 redis 连接异常 {}', e)

backend/app/common/response/response_schema.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,13 @@ class ResponseModel(BaseModel):
2121
data: Optional[Any] = None
2222

2323
class Config:
24-
json_encoders = {datetime: lambda x: x.strftime("%Y-%m-%d %H:%M:%S")}
24+
json_encoders = {datetime: lambda x: x.strftime('%Y-%m-%d %H:%M:%S')}
2525

2626

2727
class ResponseBase:
2828
@staticmethod
2929
def __encode_json(data: Any):
30-
return jsonable_encoder(data, custom_encoder={datetime: lambda x: x.strftime("%Y-%m-%d %H:%M:%S")})
30+
return jsonable_encoder(data, custom_encoder={datetime: lambda x: x.strftime('%Y-%m-%d %H:%M:%S')})
3131

3232
@staticmethod
3333
@validate_arguments

0 commit comments

Comments
 (0)