Skip to content

Commit 64f2a13

Browse files
authored
update to python3.10 (#29)
1 parent 4e6284e commit 64f2a13

File tree

14 files changed

+46
-44
lines changed

14 files changed

+46
-44
lines changed

.pre-commit-config.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,10 @@ repos:
1818
rev: 23.3.0
1919
hooks:
2020
- id: black
21-
language_version: python3.8
21+
language_version: python3.10
2222
args:
2323
- '--skip-string-normalization'
2424
- '--line-length'
2525
- '120'
2626
- '--target-version'
27-
- 'py38'
27+
- 'py310'

.ruff.toml

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,14 @@ select = [
99
"PGH004",
1010
"PLE1142",
1111
"RUF100",
12+
"I002",
13+
"F404",
14+
"TCH",
15+
"UP007"
1216
]
13-
ignore = ["F401"]
1417
line-length = 120
1518
format = "grouped"
16-
target-version = "py38"
19+
target-version = "py310"
1720
cache-dir = "./.ruff_cache"
1821

1922
[flake8-pytest-style]
@@ -34,3 +37,8 @@ ignore-variadic-names = true
3437
[isort]
3538
lines-between-types = 1
3639
order-by-type = true
40+
41+
[per-file-ignores]
42+
"backend/app/api/v1/*.py" = ["TCH"]
43+
"backend/app/models/*.py" = ["TCH003"]
44+
"backend/app/**/__init__.py" = ["F401"]

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ This is a base project of the FastAPI framework.
55
It‘s purpose is to allow you to develop your project directly with it
66
as your base project
77

8+
Support python3.10 and above
9+
810
## Skill
911

1012
- [x] FastAPI

backend/app/api/jwt.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33
from datetime import datetime, timedelta
4-
from typing import Any, Union
4+
from typing import Any
55

66
from fastapi import Depends
77
from fastapi.security import OAuth2PasswordBearer
@@ -42,7 +42,7 @@ def password_verify(plain_password: str, hashed_password: str) -> bool:
4242
return pwd_context.verify(plain_password, hashed_password)
4343

4444

45-
def create_access_token(data: Union[int, Any], expires_delta: Union[timedelta, None] = None) -> str:
45+
def create_access_token(data: int | Any, expires_delta: timedelta | None = None) -> str:
4646
"""
4747
Generate encryption token
4848

backend/app/common/pagination.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from __future__ import annotations
44

55
import math
6-
from typing import TypeVar, Generic, Sequence, Dict, Union
6+
from typing import TypeVar, Generic, Sequence, Dict
77

88
from fastapi import Query
99
from fastapi_pagination.bases import AbstractPage, AbstractParams, RawParams
@@ -35,7 +35,7 @@ class Page(AbstractPage[T], Generic[T]):
3535
page: int # 第n页
3636
size: int # 每页数量
3737
total_pages: int # 总页数
38-
links: Dict[str, Union[str, None]] # 跳转链接
38+
links: Dict[str, str | None] # 跳转链接
3939

4040
__params_type__ = Params # 使用自定义的Params
4141

backend/app/common/response/response_schema.py

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33
from datetime import datetime
4-
from typing import Optional, Any, Union, Set, Dict
4+
from typing import Any, Union, Set, Dict
55

66
from fastapi.encoders import jsonable_encoder
77
from pydantic import validate_arguments, BaseModel
88

9-
_JsonEncoder = Union[Set[Union[int, str]], Dict[Union[int, str], Any]]
9+
_JsonEncoder = Union[Set[int | str], Dict[int | str, Any]]
1010

1111
__all__ = ['ResponseModel', 'response_base']
1212

@@ -18,7 +18,7 @@ class ResponseModel(BaseModel):
1818

1919
code: int = 200
2020
msg: str = 'Success'
21-
data: Optional[Any] = None
21+
data: Any | None = None
2222

2323
class Config:
2424
json_encoders = {datetime: lambda x: x.strftime('%Y-%m-%d %H:%M:%S')}
@@ -31,9 +31,7 @@ def __encode_json(data: Any):
3131

3232
@staticmethod
3333
@validate_arguments
34-
def success(
35-
*, code: int = 200, msg: str = 'Success', data: Optional[Any] = None, exclude: Optional[_JsonEncoder] = None
36-
):
34+
def success(*, code: int = 200, msg: str = 'Success', data: Any | None = None, exclude: _JsonEncoder | None = None):
3735
"""
3836
请求成功返回通用方法
3937
@@ -48,13 +46,13 @@ def success(
4846

4947
@staticmethod
5048
@validate_arguments
51-
def fail(*, code: int = 400, msg: str = 'Bad Request', data: Any = None, exclude: Optional[_JsonEncoder] = None):
49+
def fail(*, code: int = 400, msg: str = 'Bad Request', data: Any = None, exclude: _JsonEncoder | None = None):
5250
data = data if data is None else ResponseBase.__encode_json(data)
5351
return ResponseModel(code=code, msg=msg, data=data).dict(exclude={'data': exclude})
5452

5553
@staticmethod
5654
@validate_arguments
57-
def response_200(*, msg: str = 'Success', data: Optional[Any] = None, exclude: Optional[_JsonEncoder] = None):
55+
def response_200(*, msg: str = 'Success', data: Any | None = None, exclude: _JsonEncoder | None = None):
5856
data = data if data is None else ResponseBase.__encode_json(data)
5957
return ResponseModel(code=200, msg=msg, data=data).dict(exclude={'data': exclude})
6058

backend/app/core/conf.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33
from functools import lru_cache
4-
from typing import Optional
54

65
from pydantic import BaseSettings, root_validator
76

@@ -35,9 +34,9 @@ class Settings(BaseSettings):
3534
TITLE: str = 'FastAPI'
3635
VERSION: str = '0.0.1'
3736
DESCRIPTION: str = 'FastAPI Best Architecture'
38-
DOCS_URL: Optional[str] = '/v1/docs'
39-
REDOCS_URL: Optional[str] = '/v1/redocs'
40-
OPENAPI_URL: Optional[str] = '/v1/openapi'
37+
DOCS_URL: str | None = '/v1/docs'
38+
REDOCS_URL: str | None = '/v1/redocs'
39+
OPENAPI_URL: str | None = '/v1/openapi'
4140

4241
@root_validator
4342
def validator_api_url(cls, values):

backend/app/crud/base.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
3-
from typing import Any, Dict, Generic, Type, TypeVar, Union, Optional, NoReturn
3+
from typing import Any, Dict, Generic, Type, TypeVar, NoReturn
44

55
from pydantic import BaseModel
66
from sqlalchemy import select, update, delete
@@ -17,7 +17,7 @@ class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
1717
def __init__(self, model: Type[ModelType]):
1818
self.model = model
1919

20-
async def get(self, db: AsyncSession, pk: int) -> Optional[ModelType]:
20+
async def get(self, db: AsyncSession, pk: int) -> ModelType | None:
2121
"""
2222
通过主键 id 获取一条数据
2323
@@ -28,7 +28,7 @@ async def get(self, db: AsyncSession, pk: int) -> Optional[ModelType]:
2828
model = await db.execute(select(self.model).where(self.model.id == pk))
2929
return model.scalars().first()
3030

31-
async def create(self, db: AsyncSession, obj_in: CreateSchemaType, user_id: Optional[int] = None) -> NoReturn:
31+
async def create(self, db: AsyncSession, obj_in: CreateSchemaType, user_id: int | None = None) -> NoReturn:
3232
"""
3333
新增一条数据
3434
@@ -44,7 +44,7 @@ async def create(self, db: AsyncSession, obj_in: CreateSchemaType, user_id: Opti
4444
db.add(db_obj)
4545

4646
async def update(
47-
self, db: AsyncSession, pk: int, obj_in: Union[UpdateSchemaType, Dict[str, Any]], user_id: Optional[int] = None
47+
self, db: AsyncSession, pk: int, obj_in: UpdateSchemaType | Dict[str, Any], user_id: int | None = None
4848
) -> int:
4949
"""
5050
通过主键 id 更新一条数据

backend/app/crud/crud_user.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
3-
from typing import Optional, NoReturn
3+
from typing import NoReturn
44

55
from sqlalchemy import func, select, update, desc
66
from sqlalchemy.ext.asyncio import AsyncSession
@@ -13,10 +13,10 @@
1313

1414

1515
class CRUDUser(CRUDBase[User, CreateUser, UpdateUser]):
16-
async def get_user_by_id(self, db: AsyncSession, user_id: int) -> Optional[User]:
16+
async def get_user_by_id(self, db: AsyncSession, user_id: int) -> User | None:
1717
return await self.get(db, user_id)
1818

19-
async def get_user_by_username(self, db: AsyncSession, username: str) -> Optional[User]:
19+
async def get_user_by_username(self, db: AsyncSession, username: str) -> User | None:
2020
user = await db.execute(select(self.model).where(self.model.username == username))
2121
return user.scalars().first()
2222

backend/app/database/base_class.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
# -*- coding: utf-8 -*-
33
import uuid
44
from datetime import datetime
5-
from typing import Optional
65

76
from sqlalchemy import func
87
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, declared_attr, MappedAsDataclass
@@ -24,9 +23,9 @@ class _BaseMixin(MappedAsDataclass):
2423
"""
2524

2625
create_user: Mapped[int] = mapped_column(sort_order=9999, comment='创建者')
27-
update_user: Mapped[Optional[int]] = mapped_column(init=False, default=None, sort_order=9999, comment='修改者')
26+
update_user: Mapped[int | None] = mapped_column(init=False, default=None, sort_order=9999, comment='修改者')
2827
created_time: Mapped[datetime] = mapped_column(init=False, default=func.now(), sort_order=9999, comment='创建时间')
29-
updated_time: Mapped[Optional[datetime]] = mapped_column(
28+
updated_time: Mapped[datetime | None] = mapped_column(
3029
init=False, onupdate=func.now(), sort_order=9999, comment='更新时间'
3130
)
3231

backend/app/models/user.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33
from datetime import datetime
4-
from typing import Optional
54

65
from sqlalchemy import func, String
76
from sqlalchemy.orm import Mapped, mapped_column
@@ -21,7 +20,7 @@ class User(DataClassBase):
2120
email: Mapped[str] = mapped_column(String(50), unique=True, index=True, comment='邮箱')
2221
is_superuser: Mapped[bool] = mapped_column(default=False, comment='超级权限')
2322
is_active: Mapped[bool] = mapped_column(default=True, comment='用户账号状态')
24-
avatar: Mapped[Optional[str]] = mapped_column(String(255), default=None, comment='头像')
25-
mobile_number: Mapped[Optional[str]] = mapped_column(String(11), default=None, comment='手机号')
23+
avatar: Mapped[str | None] = mapped_column(String(255), default=None, comment='头像')
24+
mobile_number: Mapped[str | None] = mapped_column(String(11), default=None, comment='手机号')
2625
time_joined: Mapped[datetime] = mapped_column(init=False, default=func.now(), comment='注册时间')
27-
last_login: Mapped[Optional[datetime]] = mapped_column(init=False, onupdate=func.now(), comment='上次登录')
26+
last_login: Mapped[datetime | None] = mapped_column(init=False, onupdate=func.now(), comment='上次登录')

backend/app/schemas/token.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
3-
from typing import Optional
43

54
from pydantic import BaseModel
65

@@ -10,4 +9,4 @@ class Token(BaseModel):
109
msg: str = 'Success'
1110
access_token: str
1211
token_type: str = 'Bearer'
13-
is_superuser: Optional[bool] = None
12+
is_superuser: bool | None = None

backend/app/schemas/user.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33
import datetime
4-
from typing import Optional
54

65
from pydantic import BaseModel, Field, HttpUrl
76

@@ -18,7 +17,7 @@ class CreateUser(Auth):
1817
class UpdateUser(BaseModel):
1918
username: str
2019
email: str
21-
mobile_number: Optional[str] = None
20+
mobile_number: str | None = None
2221

2322

2423
class Avatar(BaseModel):
@@ -28,9 +27,9 @@ class Avatar(BaseModel):
2827
class GetUserInfo(UpdateUser):
2928
id: int
3029
uid: str
31-
avatar: Optional[str] = None
30+
avatar: str | None = None
3231
time_joined: datetime.datetime = None
33-
last_login: Optional[datetime.datetime] = None
32+
last_login: datetime.datetime | None = None
3433
is_superuser: bool
3534
is_active: bool
3635

docker_conf.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
#!/usr/bin/env python3
22
# -*- coding: utf-8 -*-
33
from functools import lru_cache
4-
from typing import Optional
54

65
from pydantic import BaseSettings
76

@@ -11,9 +10,9 @@ class Settings(BaseSettings):
1110
TITLE: str = 'FastAPI'
1211
VERSION: str = 'v0.0.1'
1312
DESCRIPTION: str = 'FastAPI Best Architecture'
14-
DOCS_URL: Optional[str] = '/v1/docs'
15-
REDOCS_URL: Optional[str] = None
16-
OPENAPI_URL: Optional[str] = '/v1/openapi'
13+
DOCS_URL: str | None = '/v1/docs'
14+
REDOCS_URL: str | None = None
15+
OPENAPI_URL: str | None = '/v1/openapi'
1716

1817
# Static Server
1918
STATIC_FILES: bool = False

0 commit comments

Comments
 (0)