fastapi-authly 0.1.3__tar.gz → 0.1.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/PKG-INFO +3 -1
  2. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/pyproject.toml +3 -1
  3. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/src/fastapi_authly/__about__.py +1 -1
  4. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/src/fastapi_authly/auth.py +4 -2
  5. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/src/fastapi_authly/core/config.py +31 -9
  6. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/src/fastapi_authly/core/security.py +8 -1
  7. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/src/fastapi_authly/docs.py +20 -0
  8. fastapi_authly-0.1.4/src/fastapi_authly/static/favicon.svg +1 -0
  9. fastapi_authly-0.1.4/test.py +73 -0
  10. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/uv.lock +19 -1
  11. fastapi_authly-0.1.3/test.py +0 -177
  12. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/.gitignore +0 -0
  13. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/LICENSE +0 -0
  14. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/README.md +0 -0
  15. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/README.zh.md +0 -0
  16. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/coverage.xml +0 -0
  17. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/docs//345/207/275/346/225/260/345/274/217/347/274/226/347/250/213/344/270/203/346/255/246/345/231/250.md" +0 -0
  18. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/examples/correct_usage.py +0 -0
  19. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/.gitignore +0 -0
  20. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/class_index.html +0 -0
  21. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/coverage_html_cb_dd2e7eb5.js +0 -0
  22. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/favicon_32_cb_c827f16f.png +0 -0
  23. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/function_index.html +0 -0
  24. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/index.html +0 -0
  25. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/keybd_closed_cb_900cfef5.png +0 -0
  26. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/status.json +0 -0
  27. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/style_cb_9ff733b0.css +0 -0
  28. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/z_af1bec017750c6fc___init___py.html +0 -0
  29. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/z_af1bec017750c6fc_user_py.html +0 -0
  30. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/z_b9d93864b1b0ad6e___about___py.html +0 -0
  31. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/z_b9d93864b1b0ad6e___init___py.html +0 -0
  32. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/z_b9d93864b1b0ad6e_auth_py.html +0 -0
  33. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/z_b9d93864b1b0ad6e_interfaces_py.html +0 -0
  34. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/z_d015ea9b27b0258e___init___py.html +0 -0
  35. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/z_d015ea9b27b0258e_config_py.html +0 -0
  36. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/z_d015ea9b27b0258e_security_py.html +0 -0
  37. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/z_ddd01122054512b0___init___py.html +0 -0
  38. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/z_ddd01122054512b0_tortoise_pg_py.html +0 -0
  39. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/z_feee2d9ae7f7fd96___init___py.html +0 -0
  40. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/htmlcov/z_feee2d9ae7f7fd96_user_py.html +0 -0
  41. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/src/fastapi_authly/__init__.py +0 -0
  42. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/src/fastapi_authly/contrib/__init__.py +0 -0
  43. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/src/fastapi_authly/contrib/tortoise_pg.py +0 -0
  44. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/src/fastapi_authly/core/__init__.py +0 -0
  45. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/src/fastapi_authly/deps.py +0 -0
  46. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/src/fastapi_authly/interfaces.py +0 -0
  47. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/src/fastapi_authly/models/__init__.py +0 -0
  48. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/src/fastapi_authly/models/user.py +0 -0
  49. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/src/fastapi_authly/schemas/__init__.py +0 -0
  50. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/src/fastapi_authly/schemas/user.py +0 -0
  51. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/src/fastapi_authly/static/scalar/standalone.js +0 -0
  52. {fastapi_authly-0.1.3 → fastapi_authly-0.1.4}/src/fastapi_authly/static/scalar/style.css +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fastapi-authly
3
- Version: 0.1.3
3
+ Version: 0.1.4
4
4
  Summary: A modular authentication system for FastAPI with OAuth2, JWT, and password recovery
5
5
  Project-URL: Homepage, https://github.com/yourusername/fastapi-auth-module
6
6
  Project-URL: Documentation, https://yourusername.github.io/fastapi-auth-module/
@@ -25,6 +25,7 @@ Classifier: Programming Language :: Python :: 3.12
25
25
  Classifier: Topic :: Internet :: WWW/HTTP :: Session
26
26
  Classifier: Topic :: Security
27
27
  Requires-Python: >=3.10
28
+ Requires-Dist: asyncpg>=0.31.0
28
29
  Requires-Dist: emails>=0.6.0
29
30
  Requires-Dist: fastapi>=0.100.0
30
31
  Requires-Dist: jinja2>=3.0.0
@@ -35,6 +36,7 @@ Requires-Dist: pydantic[email]>=2.0.0
35
36
  Requires-Dist: python-jose[cryptography]>=3.3.0
36
37
  Requires-Dist: python-multipart>=0.0.6
37
38
  Requires-Dist: tortoise-orm[psycopg]>=0.25.3
39
+ Requires-Dist: uvicorn>=0.40.0
38
40
  Provides-Extra: docs
39
41
  Requires-Dist: mkdocs-material>=9.0.0; extra == 'docs'
40
42
  Requires-Dist: mkdocs>=1.5.0; extra == 'docs'
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "fastapi-authly"
7
- version = "0.1.3"
7
+ version = "0.1.4"
8
8
  description = "A modular authentication system for FastAPI with OAuth2, JWT, and password recovery"
9
9
  readme = "README.md"
10
10
  license = {text = "MIT"}
@@ -49,6 +49,8 @@ dependencies = [
49
49
  "jinja2>=3.0.0",
50
50
  "jwt>=1.3.1",
51
51
  "tortoise-orm[psycopg]>=0.25.3",
52
+ "uvicorn>=0.40.0",
53
+ "asyncpg>=0.31.0",
52
54
  ]
53
55
 
54
56
  [project.optional-dependencies]
@@ -1,3 +1,3 @@
1
1
  """Version information."""
2
2
 
3
- __version__ = "0.1.3"
3
+ __version__ = "0.1.4"
@@ -103,12 +103,14 @@ class AuthModule:
103
103
  status_code=status.HTTP_400_BAD_REQUEST,
104
104
  detail="Incorrect username or password",
105
105
  )
106
- if not self.password_hasher.verify(body.password, getattr(user, "hashed_password", "")):
106
+
107
+ hashed_password = getattr(user, "hashed_password", None) or ""
108
+ if not hashed_password or not self.password_hasher.verify(body.password, hashed_password):
107
109
  raise HTTPException(
108
110
  status_code=status.HTTP_400_BAD_REQUEST,
109
111
  detail="Incorrect username or password",
110
112
  )
111
-
113
+
112
114
  if not user.is_active:
113
115
  raise HTTPException(status_code=400, detail="Inactive user")
114
116
 
@@ -1,8 +1,8 @@
1
1
  """Configuration settings for fastapi-authly."""
2
2
 
3
- from typing import List, Optional, Any
3
+ from typing import List, Optional, Any, Union
4
4
  from datetime import timedelta
5
- from pydantic import BaseModel, Field, ConfigDict
5
+ from pydantic import BaseModel, Field, ConfigDict, model_validator
6
6
  from pydantic_settings import BaseSettings, SettingsConfigDict
7
7
 
8
8
  class JwtConfig(BaseModel):
@@ -26,8 +26,6 @@ class JwtConfig(BaseModel):
26
26
  return timedelta(days=self.refresh_token_expires_days)
27
27
 
28
28
 
29
-
30
-
31
29
  class AuthConfig(BaseSettings):
32
30
  """
33
31
  Runtime configuration loaded from environment variables with ``AUTH_`` prefix.
@@ -35,10 +33,11 @@ class AuthConfig(BaseSettings):
35
33
  Host applications can still pass an ``AuthConfig`` instance directly;
36
34
  in that case, the passed values override the environment values.
37
35
  """
38
- jwt: JwtConfig = JwtConfig()
36
+ jwt: Union[JwtConfig, dict] = Field(default_factory=JwtConfig)
39
37
 
40
38
  router_prefix: str = "/auth"
41
39
  router_tags: List[str] = Field(default_factory=lambda: ["authentication"])
40
+ token_url: str = "login" # OAuth2 token URL path
42
41
 
43
42
  enable_password_recovery: bool = True
44
43
  enable_user_registration: bool = True
@@ -59,26 +58,47 @@ class AuthConfig(BaseSettings):
59
58
  extra="ignore",
60
59
  )
61
60
 
61
+ @model_validator(mode='after')
62
+ def _ensure_jwt_is_config(self):
63
+ """确保 jwt 字段始终是 JwtConfig 实例"""
64
+ if isinstance(self.jwt, dict):
65
+ self.jwt = JwtConfig(**self.jwt)
66
+ elif not isinstance(self.jwt, JwtConfig):
67
+ self.jwt = JwtConfig()
68
+ return self
69
+
70
+ def _ensure_jwt_config(self) -> JwtConfig:
71
+ """确保 jwt 是 JwtConfig 实例,如果不是则转换"""
72
+ if isinstance(self.jwt, dict):
73
+ self.jwt = JwtConfig(**self.jwt)
74
+ elif not isinstance(self.jwt, JwtConfig):
75
+ self.jwt = JwtConfig()
76
+ return self.jwt
77
+
62
78
  # 属性访问器:直接访问 jwt 中的属性,兼容现有代码
63
79
  @property
64
80
  def secret_key(self) -> str:
65
81
  """JWT secret key"""
66
- return self.jwt.secret_key
82
+ jwt_config = self._ensure_jwt_config()
83
+ return jwt_config.secret_key
67
84
 
68
85
  @property
69
86
  def algorithm(self) -> str:
70
87
  """JWT algorithm"""
71
- return self.jwt.algorithm
88
+ jwt_config = self._ensure_jwt_config()
89
+ return jwt_config.algorithm
72
90
 
73
91
  @property
74
92
  def access_token_expire_minutes(self) -> Optional[int]:
75
93
  """Access token expiration in minutes (compatible with auth.py)"""
76
- return self.jwt.access_token_expires_minutes
94
+ jwt_config = self._ensure_jwt_config()
95
+ return jwt_config.access_token_expires_minutes
77
96
 
78
97
  @property
79
98
  def refresh_token_expire_days(self) -> int:
80
99
  """Refresh token expiration in days"""
81
- return self.jwt.refresh_token_expire_days
100
+ jwt_config = self._ensure_jwt_config()
101
+ return jwt_config.refresh_token_expires_days
82
102
 
83
103
  _config = AuthConfig()
84
104
 
@@ -95,4 +115,6 @@ class AuthDependencyConfig(BaseModel):
95
115
  token_service: Optional[Any] = None
96
116
  mailer: Optional[Any] = None
97
117
  # 可选:自定义 token 提取依赖(例如自定义 Bearer/JWT 解析)
118
+ # token_dependency: Optional[Any] = Noneptional[Any] = None
119
+ # 可选:自定义 token 提取依赖(例如自定义 Bearer/JWT 解析)
98
120
  token_dependency: Optional[Any] = None
@@ -3,6 +3,7 @@ from typing import Any, Dict, Optional
3
3
 
4
4
  from jose import JWTError, jwt
5
5
  from passlib.context import CryptContext
6
+ from passlib.exc import UnknownHashError
6
7
 
7
8
  from ..interfaces import PasswordHasher, TokenService
8
9
 
@@ -18,7 +19,13 @@ class BcryptPasswordHasher(PasswordHasher):
18
19
  return self._ctx.hash(password)
19
20
 
20
21
  def verify(self, password: str, hashed: str) -> bool:
21
- return self._ctx.verify(password, hashed)
22
+ if not hashed:
23
+ return False
24
+ try:
25
+ return self._ctx.verify(password, hashed)
26
+ except UnknownHashError:
27
+ # 如果哈希格式无法识别,返回 False
28
+ return False
22
29
 
23
30
 
24
31
  class JWTTokenService(TokenService):
@@ -21,6 +21,7 @@ def setup_scalar_docs(
21
21
  static_url: str = "/static",
22
22
  title: Optional[str] = None,
23
23
  openapi_url: Optional[str] = None,
24
+ favicon_url: Optional[str] = None,
24
25
  ) -> None:
25
26
  """
26
27
  为 FastAPI 应用设置 Scalar API 文档
@@ -31,6 +32,8 @@ def setup_scalar_docs(
31
32
  static_url: 静态文件 URL 前缀,默认为 "/static"
32
33
  title: 文档标题,默认使用 app.title
33
34
  openapi_url: OpenAPI schema URL,默认使用 app.openapi_url
35
+ favicon_url: Favicon 图标 URL,默认为 "{static_url}/favicon.svg"
36
+ 如果设置为 None,将尝试使用默认路径
34
37
  """
35
38
  static_dir = get_static_dir()
36
39
 
@@ -42,6 +45,22 @@ def setup_scalar_docs(
42
45
  doc_title = title or app.title
43
46
  api_url = openapi_url or app.openapi_url
44
47
 
48
+ if favicon_url is None:
49
+ static_dir = get_static_dir()
50
+ # 优先尝试 SVG,然后是 ICO
51
+ if os.path.exists(static_dir / "favicon.svg"):
52
+ favicon_url = f"{static_url}/favicon.svg"
53
+ else:
54
+ favicon_url = f"{static_url}/favicon.ico"
55
+
56
+ favicon_type = "image/x-icon" # 默认 ICO
57
+ if favicon_url.lower().endswith(".svg"):
58
+ favicon_type = "image/svg+xml"
59
+ elif favicon_url.lower().endswith(".png"):
60
+ favicon_type = "image/png"
61
+ elif favicon_url.lower().endswith(".ico"):
62
+ favicon_type = "image/x-icon"
63
+
45
64
  # 创建文档路由
46
65
  @app.get(docs_url, include_in_schema=False)
47
66
  async def scalar_html():
@@ -52,6 +71,7 @@ def setup_scalar_docs(
52
71
  <title>{doc_title}</title>
53
72
  <meta charset="utf-8"/>
54
73
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
74
+ <link rel="icon" type="{favicon_type}" href="{favicon_url}">
55
75
  <link rel="stylesheet" href="{static_url}/scalar/style.css">
56
76
  </head>
57
77
  <body>
@@ -0,0 +1 @@
1
+ <?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1769412556021" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5147" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M24.856135 296.081347L490.69745 507.422478a51.196979 51.196979 0 0 0 42.595887 0l465.841316-211.341131c33.073249-15.000715 33.073249-65.020164 0-80.020879L533.293337 4.668141a51.196979 51.196979 0 0 0-42.595887 0l-465.892512 211.289933c-33.073249 15.051912-33.073249 65.020164 0 80.072076z m974.278518 176.578382l-116.217144-52.681692-323.20653 146.525755a114.732431 114.732431 0 0 1-95.43117 0L141.022081 419.978037 24.804938 472.659729c-33.073249 15.000715-33.073249 65.020164 0 79.969682l465.892512 211.18754c13.618397 6.143638 28.97749 6.143638 42.595887 0l465.841316-211.18754c33.073249-15.000715 33.073249-65.020164 0-79.969682z m0 255.575321l-115.705174-52.476904-323.7185 146.730543a114.732431 114.732431 0 0 1-95.43117 0l-323.667304-146.730543-115.75637 52.476904c-33.124446 15.000715-33.124446 65.020164 0 79.969682l465.841315 211.18754c13.618397 6.143638 28.97749 6.143638 42.595887 0l465.841316-211.18754c33.073249-15.000715 33.073249-65.020164 0-79.969682z" fill="#03CDC1" p-id="5148"></path></svg>
@@ -0,0 +1,73 @@
1
+ """
2
+ 正确的使用方式示例
3
+ """
4
+
5
+ from fastapi import FastAPI
6
+ from tortoise.contrib.fastapi import register_tortoise
7
+ from src.fastapi_authly import (
8
+ AuthConfig,
9
+ AuthDependencyConfig,
10
+ create_auth_router,
11
+ JwtConfig,
12
+ setup_scalar_docs
13
+ )
14
+ from src.fastapi_authly.contrib.tortoise_pg import TortoiseUserRepository
15
+
16
+ app = FastAPI(title="FastAPI Authly 测试应用", docs_url="/old_docs",)
17
+
18
+ # 初始化 Tortoise + Postgres
19
+ register_tortoise(
20
+ app,
21
+ db_url="postgres://postgres:Dnect2016@192.168.0.81:5432/testdb",
22
+ modules={"models": ["src.fastapi_authly.models.user"]},
23
+ generate_schemas=True,
24
+ add_exception_handlers=True,
25
+ )
26
+
27
+ # 方式 1: 使用 JwtConfig 实例(推荐)
28
+ config = AuthConfig(
29
+ jwt=JwtConfig(
30
+ secret_key="django-insecure-7qi2d#57gzg7br&sx-1n9c16)kf979m)jg+%vu^z80ti_#&d*_",
31
+ algorithm="HS256",
32
+ access_token_expires_minutes=30,
33
+ refresh_token_expires_days=7,
34
+ ),
35
+ router_prefix="/auth",
36
+ )
37
+
38
+ # 方式 2: 使用字典更新(也可以)
39
+ # config = AuthConfig(
40
+ # jwt={
41
+ # "secret_key": "your-secret-key-change-in-production",
42
+ # "algorithm": "HS256",
43
+ # "access_token_expires_minutes": 30,
44
+ # },
45
+ # router_prefix="/auth",
46
+ # token_url="login",
47
+ # )
48
+
49
+ # 方式 3: 使用默认配置,然后通过环境变量覆盖
50
+ # 设置环境变量: AUTH_JWT__SECRET_KEY=your-secret-key
51
+ # config = AuthConfig(
52
+ # router_prefix="/auth",
53
+ # token_url="login",
54
+ # )
55
+
56
+ deps = AuthDependencyConfig(
57
+ user_repository=TortoiseUserRepository(),
58
+ )
59
+
60
+ # 注册认证路由
61
+ auth_router = create_auth_router(config=config, dependencies=deps)
62
+ app.include_router(auth_router)
63
+
64
+ # 设置 Scalar 文档
65
+ setup_scalar_docs(app, docs_url="/docs", static_url="/static")
66
+
67
+ @app.get("/")
68
+ async def root():
69
+ return {"message": "FastAPI Authly 测试应用已启动"}
70
+
71
+ if __name__ == "__main__":
72
+ import uvicorn
73
+ uvicorn.run(app, host="0.0.0.0", port=8001)
@@ -625,9 +625,10 @@ wheels = [
625
625
 
626
626
  [[package]]
627
627
  name = "fastapi-authly"
628
- version = "0.1.0"
628
+ version = "0.1.3"
629
629
  source = { editable = "." }
630
630
  dependencies = [
631
+ { name = "asyncpg" },
631
632
  { name = "emails" },
632
633
  { name = "fastapi" },
633
634
  { name = "jinja2" },
@@ -638,6 +639,7 @@ dependencies = [
638
639
  { name = "python-jose", extra = ["cryptography"] },
639
640
  { name = "python-multipart" },
640
641
  { name = "tortoise-orm", extra = ["psycopg"] },
642
+ { name = "uvicorn" },
641
643
  ]
642
644
 
643
645
  [package.optional-dependencies]
@@ -662,6 +664,7 @@ tortoise = [
662
664
  [package.metadata]
663
665
  requires-dist = [
664
666
  { name = "alembic", marker = "extra == 'sqlalchemy'", specifier = ">=1.12.0" },
667
+ { name = "asyncpg", specifier = ">=0.31.0" },
665
668
  { name = "emails", specifier = ">=0.6.0" },
666
669
  { name = "faker", marker = "extra == 'test'", specifier = ">=20.0.0" },
667
670
  { name = "fastapi", specifier = ">=0.100.0" },
@@ -680,6 +683,7 @@ requires-dist = [
680
683
  { name = "sqlalchemy", marker = "extra == 'sqlalchemy'", specifier = ">=2.0.0" },
681
684
  { name = "tortoise-orm", extras = ["asyncpg"], marker = "extra == 'tortoise'", specifier = ">=0.20.0" },
682
685
  { name = "tortoise-orm", extras = ["psycopg"], specifier = ">=0.25.3" },
686
+ { name = "uvicorn", specifier = ">=0.40.0" },
683
687
  ]
684
688
  provides-extras = ["tortoise", "sqlalchemy", "docs", "test"]
685
689
 
@@ -1908,6 +1912,20 @@ wheels = [
1908
1912
  { url = "https://files.pythonhosted.org/packages/39/08/aaaad47bc4e9dc8c725e68f9d04865dbcb2052843ff09c97b08904852d84/urllib3-2.6.3-py3-none-any.whl", hash = "sha256:bf272323e553dfb2e87d9bfd225ca7b0f467b919d7bbd355436d3fd37cb0acd4", size = 131584, upload-time = "2026-01-07T16:24:42.685Z" },
1909
1913
  ]
1910
1914
 
1915
+ [[package]]
1916
+ name = "uvicorn"
1917
+ version = "0.40.0"
1918
+ source = { registry = "https://pypi.org/simple" }
1919
+ dependencies = [
1920
+ { name = "click" },
1921
+ { name = "h11" },
1922
+ { name = "typing-extensions", marker = "python_full_version < '3.11'" },
1923
+ ]
1924
+ sdist = { url = "https://files.pythonhosted.org/packages/c3/d1/8f3c683c9561a4e6689dd3b1d345c815f10f86acd044ee1fb9a4dcd0b8c5/uvicorn-0.40.0.tar.gz", hash = "sha256:839676675e87e73694518b5574fd0f24c9d97b46bea16df7b8c05ea1a51071ea", size = 81761, upload-time = "2025-12-21T14:16:22.45Z" }
1925
+ wheels = [
1926
+ { url = "https://files.pythonhosted.org/packages/3d/d8/2083a1daa7439a66f3a48589a57d576aa117726762618f6bb09fe3798796/uvicorn-0.40.0-py3-none-any.whl", hash = "sha256:c6c8f55bc8bf13eb6fa9ff87ad62308bbbc33d0b67f84293151efe87e0d5f2ee", size = 68502, upload-time = "2025-12-21T14:16:21.041Z" },
1927
+ ]
1928
+
1911
1929
  [[package]]
1912
1930
  name = "watchdog"
1913
1931
  version = "6.0.0"
@@ -1,177 +0,0 @@
1
-
2
- """
3
- 题 1(入门)
4
- 给定 nums = [1, 2, 3, 4, 5],用 map 得到每个元素的平方,输出为列表。
5
-
6
- """
7
- numbers = [1,2,3,4,5,6,7,8,9]
8
- content = map(lambda x: x**2, numbers)
9
- print(list(content))
10
-
11
-
12
- """
13
- 给定 words = [" Alice ", "BOB", "cHaRlIe "]
14
- 用 map 把每个元素转换成:去掉两端空格 + 全部小写。
15
- """
16
-
17
- a = 'Word'
18
- words = [" Alice ", "BOB", "cHaRlIe "]
19
-
20
- new_words = map(lambda x: x.strip().lower(), words)
21
-
22
- print(list(new_words))
23
-
24
- """
25
- ### 题 3(类型转换 + 容错)
26
- 给定 `raw = ["1", "2", "x", "3", ""]`
27
- 实现一个转换函数:能转成 int 的转 int,不能转的返回 `None`。
28
- 用 `map` 得到结果列表。
29
- """
30
-
31
- raw = ["1", "2", "x", "3", ""]
32
-
33
- def change(x):
34
- try:
35
- return int(x)
36
- except ValueError:
37
- return None
38
-
39
- content = map(change, raw)
40
-
41
- print(list(content))
42
-
43
-
44
- """
45
- ### 题 4(多个 iterable)
46
- 给定:
47
-
48
- ```python
49
- a = [1, 2, 3, 4]
50
- b = [10, 20, 30]
51
- ```
52
-
53
- 用 `map` 生成 `a[i] + b[i]` 的列表,并解释为什么结果长度是多少。
54
- """
55
-
56
- a = [1, 2, 3, 4]
57
- b = [10, 20, 30]
58
-
59
- def _add(x,y):
60
- print(x,y)
61
-
62
- content = map(lambda x,y:x+y, a, b)
63
-
64
- print(list(content))
65
- # 长度为最短的那个可迭代对象的长度,因为灰爆出stop什么来着
66
-
67
-
68
- """
69
- ### 题 5(嵌套数据处理)
70
- 给定:
71
-
72
- ```python
73
- records = [
74
- {"name": "alice", "score": "98"},
75
- {"name": "bob", "score": "87"},
76
- {"name": "cathy", "score": "100"},
77
- ]
78
- ```
79
-
80
- 用 `map` 输出一个列表:每个元素是 `(NAME_UPPER, score_int)`。
81
- """
82
-
83
- records = [
84
- {"name": "alice", "score": "98"},
85
- {"name": "bob", "score": "87"},
86
- {"name": "cathy", "score": "100"},
87
- ]
88
-
89
- content = map(lambda x: (x["name"].upper(), x["score"]), records)
90
-
91
- print(list(content))
92
-
93
-
94
- """
95
- ### 题 6(惰性验证题)
96
- 写一段最短代码证明:`map` 不会立刻执行函数,而是在迭代时执行。
97
- 要求:必须能从输出看出来“什么时候调用”。
98
- """
99
-
100
- numbers = [1,2,3,4,5,6,7,8,9]
101
-
102
- content = map(lambda x: print(f"当前{x}"), numbers)
103
-
104
- print(next(content))
105
-
106
-
107
- """
108
- ### 题 7(组合题:map + filter)
109
- 给定 `nums = list(range(-5, 6))`
110
- 用 **filter 先筛掉负数**,再用 **map 转平方**,输出列表。
111
- (要求用函数式写法,不用列表推导式。)
112
- """
113
- nums = list(range(-5, 6))
114
-
115
- filtered = filter(lambda x: x > 0, nums)
116
-
117
- new_nums = map(lambda x: x**2, filtered)
118
- print(list(new_nums))
119
-
120
- """
121
- ### 题 8(进阶:并行处理 + 缺失值)
122
- 给定:
123
-
124
- ```python
125
- names = ["alice", "bob", "cathy", "dan"]
126
- scores = ["100", "", "87", "x"]
127
- ```
128
-
129
- 目标输出一个列表:`["Alice:100", "Bob:NA", "Cathy:87", "Dan:NA"]`
130
- 规则:分数能转 int 就用该数字,否则用 `"NA"`。
131
- 要求:用 `map`,并尽量把逻辑放进一个清晰的转换函数里。
132
-
133
- """
134
- names = ["alice", "bob", "cathy", "dan"]
135
- scores = ["100", "", "87", "x"]
136
-
137
- def chang(name,score):
138
- try:
139
- score = int(score)
140
- return f"{name}:{score}"
141
- except ValueError:
142
- return f"{name}:NA"
143
-
144
- content = map(chang, names, scores)
145
-
146
- print(list(content))
147
-
148
- print(callable(chang))
149
-
150
- """
151
- ### 题 9(较难:实现你自己的 map)
152
- 实现一个函数 `my_map(func, iterable)`,返回一个**生成器**,行为尽量像 `map`(惰性、一次产出一个)。
153
- 然后用它跑一下题 1 的例子验证。
154
- """
155
-
156
- from typing import Callable
157
-
158
- def my_map(func: Callable, iterable):
159
- if not callable(func):
160
- raise "func 应该是一个函数"
161
-
162
- # todo 应该增加iterable 的判断,判断他是一个可迭代的对象
163
-
164
- # todo 应该增加可是传递多个可迭代对象,但是我不知道怎么做
165
- for item in iterable:
166
- yield func(item)
167
-
168
- numbers = [1,2,3,4,5,6,7,8,9]
169
-
170
- content = my_map(lambda x: x**2, numbers)
171
-
172
- print(next(content))
173
-
174
- print(list(content))
175
-
176
-
177
- print(map.__doc__)
File without changes
File without changes