Skip to content

(feat)因在#16pr中引入了uv包管理,修改readme中运行部分的命令#28

Open
akiooo45 wants to merge 2 commits intoembyplus:mainfrom
akiooo45:doc
Open

(feat)因在#16pr中引入了uv包管理,修改readme中运行部分的命令#28
akiooo45 wants to merge 2 commits intoembyplus:mainfrom
akiooo45:doc

Conversation

@akiooo45
Copy link
Contributor

@akiooo45 akiooo45 commented Feb 17, 2025

因在#16pr中引入了uv包管理,修改readme中运行部分的命令

好的,这是翻译成中文的 pull request 总结:

Sourcery 总结

更新项目以使用 uv 包管理器,并切换到使用 aiohttp 的异步 HTTP 请求。更新 README,包含新的运行说明。

增强功能:

  • 从使用 requests 库切换到 aiohttp 以进行异步 HTTP 请求

文档:

  • 更新 README 以反映使用 uv 包管理器的新安装和运行说明
Original summary in English

Summary by Sourcery

Update the project to use the uv package manager and switch to asynchronous HTTP requests using aiohttp. Update the README with new run instructions.

Enhancements:

  • Switch from using the requests library to aiohttp for making asynchronous HTTP requests

Documentation:

  • Update the README to reflect the new installation and running instructions using the uv package manager

@sourcery-ai
Copy link

sourcery-ai bot commented Feb 17, 2025

## Sourcery 评审者指南

此 Pull Request 将项目迁移到使用 `aiohttp` 进行异步 HTTP 请求,以提高性能和响应速度。它还更新了 readme 文件,以反映包管理从 pip 更改为 uv。

#### 使用 aiohttp 的 EmbyApi._request 的序列图

```mermaid
sequenceDiagram
  participant Client
  participant EmbyApi
  participant aiohttp.ClientSession
  participant EmbyServer

  Client->>EmbyApi: _request(method, path, data, params)
  activate EmbyApi
  EmbyApi->>aiohttp.ClientSession: Create ClientSession with timeout
  activate aiohttp.ClientSession
  aiohttp.ClientSession-->>EmbyApi: ClientSession
  deactivate aiohttp.ClientSession
  EmbyApi->>aiohttp.ClientSession: session.request(method, url, params, json, headers)
  activate aiohttp.ClientSession
  aiohttp.ClientSession->>EmbyServer: HTTP Request (method, url, params, json, headers)
  activate EmbyServer
  EmbyServer-->>aiohttp.ClientSession: HTTP Response (status, body)
  deactivate EmbyServer
  alt response.status != 200
    aiohttp.ClientSession-->>EmbyApi: Raise Exception
    EmbyApi-->>Client: Exception
  else response.status == 200
    aiohttp.ClientSession-->>EmbyApi: response.json()
    EmbyApi-->>Client: JSON Data
  end
  deactivate aiohttp.ClientSession
  deactivate EmbyApi

EmbyApi 的更新后的类图

classDiagram
  class EmbyApi {
    -str emby_url
    -str emby_api
    -int timeout
    +__init__(emby_url: str, emby_api: str, timeout: int = 10)
    +async _request(method: str, path: str, data: dict = None, params: dict = None)
    +async get_user(emby_id: str)
    +async create_user(name: str)
    +async ban_user(emby_id: str)
    +async set_default_policy(emby_id: str)
    +async update_user_policy(emby_id: str, policy_data: dict)
    +async reset_user_password(emby_id: str)
    +async set_user_password(emby_id: str, new_pass: str)
    +async check_emby_site() bool
    +async count()
  }
  note for EmbyApi "Uses aiohttp for asynchronous requests"
Loading

EmbyRouterAPI 的更新后的类图

classDiagram
  class EmbyRouterAPI {
    -str api_url
    -str api_key
    -int timeout
    +__init__(api_url: str, api_key: str = "", timeout: int = 10)
    +async call_api(path: str)
    +async query_all_route()
    +async query_user_route(user_id: str)
    +async update_user_route(user_id: str, new_index: str)
  }
  note for EmbyRouterAPI "Uses aiohttp for asynchronous requests"
Loading

文件级别更改

变更 详情 文件
使用 aiohttp 替换 requests 库以进行异步 HTTP 请求。
  • 导入了 aiohttpasyncio
  • aiohttp 异步调用替换了 requests 调用。
  • 实现了 aiohttp.ClientErrorasyncio.TimeoutError 的错误处理。
  • 修改了 _request 和所有 API 方法以使其异步。
core/emby_api.py
更新了 readme 文件,以反映包管理从 pip 更改为 uv。
  • 添加了关于使用 uv 进行包管理和运行应用程序的说明。
  • 修改了安装和运行说明,以使用 uv syncuv run app.py 代替 python3 -m pip install -r requirements.txtpython3 app.py
readme.md

提示和命令

与 Sourcery 交互

  • 触发新的审查: 在 Pull Request 上评论 @sourcery-ai review
  • 继续讨论: 直接回复 Sourcery 的审查评论。
  • 从审查评论生成 GitHub issue: 通过回复审查评论,要求 Sourcery 从该评论创建一个 issue。您也可以回复审查评论并使用 @sourcery-ai issue 从该评论创建一个 issue。
  • 生成 Pull Request 标题: 在 Pull Request 标题中的任何位置写入 @sourcery-ai 以随时生成标题。您也可以在 Pull Request 上评论 @sourcery-ai title 以随时(重新)生成标题。
  • 生成 Pull Request 摘要: 在 Pull Request 正文中的任何位置写入 @sourcery-ai summary 以随时在您想要的位置生成 PR 摘要。您也可以在 Pull Request 上评论 @sourcery-ai summary 以随时(重新)生成摘要。
  • 生成评审者指南: 在 Pull Request 上评论 @sourcery-ai guide 以随时(重新)生成评审者指南。
  • 解决所有 Sourcery 评论: 在 Pull Request 上评论 @sourcery-ai resolve 以解决所有 Sourcery 评论。如果您已经解决了所有评论并且不想再看到它们,这将非常有用。
  • 驳回所有 Sourcery 审查: 在 Pull Request 上评论 @sourcery-ai dismiss 以驳回所有现有的 Sourcery 审查。如果您想重新开始新的审查,这将特别有用 - 不要忘记评论 @sourcery-ai review 以触发新的审查!
  • 为 issue 生成行动计划: 在 issue 上评论 @sourcery-ai plan 以生成行动计划。

自定义您的体验

访问您的 仪表板 以:

  • 启用或禁用审查功能,例如 Sourcery 生成的 Pull Request 摘要、评审者指南等。
  • 更改审查语言。
  • 添加、删除或编辑自定义审查说明。
  • 调整其他审查设置。

获取帮助

```
Original review guide in English

Reviewer's Guide by Sourcery

This pull request migrates the project to use aiohttp for asynchronous HTTP requests to improve performance and responsiveness. It also updates the readme to reflect the change in package management from pip to uv.

Sequence diagram for EmbyApi._request with aiohttp

sequenceDiagram
  participant Client
  participant EmbyApi
  participant aiohttp.ClientSession
  participant EmbyServer

  Client->>EmbyApi: _request(method, path, data, params)
  activate EmbyApi
  EmbyApi->>aiohttp.ClientSession: Create ClientSession with timeout
  activate aiohttp.ClientSession
  aiohttp.ClientSession-->>EmbyApi: ClientSession
  deactivate aiohttp.ClientSession
  EmbyApi->>aiohttp.ClientSession: session.request(method, url, params, json, headers)
  activate aiohttp.ClientSession
  aiohttp.ClientSession->>EmbyServer: HTTP Request (method, url, params, json, headers)
  activate EmbyServer
  EmbyServer-->>aiohttp.ClientSession: HTTP Response (status, body)
  deactivate EmbyServer
  alt response.status != 200
    aiohttp.ClientSession-->>EmbyApi: Raise Exception
    EmbyApi-->>Client: Exception
  else response.status == 200
    aiohttp.ClientSession-->>EmbyApi: response.json()
    EmbyApi-->>Client: JSON Data
  end
  deactivate aiohttp.ClientSession
  deactivate EmbyApi
Loading

Updated class diagram for EmbyApi

classDiagram
  class EmbyApi {
    -str emby_url
    -str emby_api
    -int timeout
    +__init__(emby_url: str, emby_api: str, timeout: int = 10)
    +async _request(method: str, path: str, data: dict = None, params: dict = None)
    +async get_user(emby_id: str)
    +async create_user(name: str)
    +async ban_user(emby_id: str)
    +async set_default_policy(emby_id: str)
    +async update_user_policy(emby_id: str, policy_data: dict)
    +async reset_user_password(emby_id: str)
    +async set_user_password(emby_id: str, new_pass: str)
    +async check_emby_site() bool
    +async count()
  }
  note for EmbyApi "Uses aiohttp for asynchronous requests"
Loading

Updated class diagram for EmbyRouterAPI

classDiagram
  class EmbyRouterAPI {
    -str api_url
    -str api_key
    -int timeout
    +__init__(api_url: str, api_key: str = "", timeout: int = 10)
    +async call_api(path: str)
    +async query_all_route()
    +async query_user_route(user_id: str)
    +async update_user_route(user_id: str, new_index: str)
  }
  note for EmbyRouterAPI "Uses aiohttp for asynchronous requests"
Loading

File-Level Changes

Change Details Files
Replaced the requests library with aiohttp for asynchronous HTTP requests.
  • Imported aiohttp and asyncio.
  • Replaced requests calls with aiohttp asynchronous calls.
  • Implemented error handling for aiohttp.ClientError and asyncio.TimeoutError.
  • Modified _request and all API methods to be asynchronous.
core/emby_api.py
Updated the readme to reflect the change in package management from pip to uv.
  • Added a note about using uv for package management and running the application.
  • Modified the installation and running instructions to use uv sync and uv run app.py instead of python3 -m pip install -r requirements.txt and python3 app.py.
readme.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!
  • Generate a plan of action for an issue: Comment @sourcery-ai plan on
    an issue to generate a plan of action for it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@akiooo45 - 我已经查看了你的更改 - 这里有一些反馈:

总体评论

  • 考虑添加一条注释,解释为什么你要从 requests 切换到 aiohttp
  • 看起来 EmbyApiEmbyRouterAPI 中的所有方法现在都可以是 async
以下是我在审查期间查看的内容
  • 🟡 一般问题:发现 3 个问题
  • 🟢 安全性:一切看起来都不错
  • 🟢 测试:一切看起来都不错
  • 🟡 复杂性:发现 1 个问题
  • 🟢 文档:一切看起来都不错

Sourcery 对开源是免费的 - 如果您喜欢我们的评论,请考虑分享它们 ✨
帮助我更有用!请点击每个评论上的 👍 或 👎,我将使用反馈来改进您的评论。
Original comment in English

Hey @akiooo45 - I've reviewed your changes - here's some feedback:

Overall Comments:

  • Consider adding a comment explaining why you're switching from requests to aiohttp.
  • It looks like all the methods in EmbyApi and EmbyRouterAPI can now be async.
Here's what I looked at during the review
  • 🟡 General issues: 3 issues found
  • 🟢 Security: all looks good
  • 🟢 Testing: all looks good
  • 🟡 Complexity: 1 issue found
  • 🟢 Documentation: all looks good

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

elif method.upper() == "POST":
response = requests.post(
url, params=params, json=data, timeout=self.timeout, headers=headers
async with aiohttp.ClientSession(
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (performance): 考虑重用 ClientSession 以提高性能。

为每个请求创建一个新的 ClientSession 可能会导致不必要的开销和连接重建。根据使用模式,为类或应用程序的生命周期管理一个持久的 ClientSession 可能会有所帮助。

建议的实施方案:

    def __init__(self, timeout):
        self.timeout = timeout
        # Create a persistent aiohttp ClientSession for reuse
        self._session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=self.timeout))
        # any other initialization code
            try:
                async with self._session.request(
                    method, url, params=params, json=data, headers=headers
                ) as response:
                    if response.status != 200:
                        raise Exception(
                            f"Request failed with status code {response.status}"
                        )
                    return await response.json()
            except aiohttp.ClientError as e:

由于 ClientSession 现在在初始化期间创建一次并且是持久的,因此您还应该添加一个方法,以便在您的类完成时关闭会话(例如,在关闭应用程序时)。
例如:
async def close(self):
await self._session.close()
您需要在应用程序生命周期的适当部分调用此 close() 方法。

Original comment in English

suggestion (performance): Consider reusing a ClientSession for performance.

Creating a new ClientSession for each request may lead to unnecessary overhead and connection re-establishment. Depending on the usage pattern, it might be beneficial to manage a persistent ClientSession for the lifetime of the class or application.

Suggested implementation:

    def __init__(self, timeout):
        self.timeout = timeout
        # Create a persistent aiohttp ClientSession for reuse
        self._session = aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=self.timeout))
        # any other initialization code
            try:
                async with self._session.request(
                    method, url, params=params, json=data, headers=headers
                ) as response:
                    if response.status != 200:
                        raise Exception(
                            f"Request failed with status code {response.status}"
                        )
                    return await response.json()
            except aiohttp.ClientError as e:

Since the ClientSession is now created once during initialization and is persistent, you should also add a method to close the session when your class is done with it (for example, when shutting down the application).
For example:
async def close(self):
await self._session.close()
You'll need to call this close() method in the appropriate part of your application lifecycle.

- 限时或限量开放注册。

### 安装及运行
本项目用[uv](https://github.com/astral-sh/uv)管理及运行
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (typo): “用”字后缺少冒号

“用”字后似乎应该有一个冒号,以提高可读性。它应该读作“本项目用:uv管理及运行”

Suggested change
本项目用[uv](https://github.com/astral-sh/uv)管理及运行
本项目用[uv](https://github.com/astral-sh/uv)管理及运行
Original comment in English

suggestion (typo): Missing colon after "用"

It seems like there should be a colon after the word "用" to improve readability. It should read as "本项目用:uv管理及运行"

Suggested change
本项目用[uv](https://github.com/astral-sh/uv)管理及运行
本项目用[uv](https://github.com/astral-sh/uv)管理及运行

### Thanks
- [Pyrogram](https://docs.pyrogram.org/) - Telegram API for Python
- [SQLAlchemy](https://www.sqlalchemy.org/) - Python SQL Toolkit and Object-Relational Mapping
- [Emby服管理bot by小草](https://github.com/xiaocao666tzh/EmbyBot) No newline at end of file
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (typo): 缺少空格和损坏的链接

“Emby”和“服管理bot”之间应该有一个空格。此外,“No newline at end of file”之前的反斜杠破坏了链接。

Original comment in English

issue (typo): Missing space and broken link

There should be a space between "Emby" and "服管理bot". Also, the backslash before "No newline at end of file" is breaking the link.

@@ -1,5 +1,6 @@
import logging
import requests
import aiohttp
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (complexity): 考虑将网络调用和错误处理逻辑提取到共享的帮助函数中,以减少代码重复。

考虑将网络调用和错误处理逻辑提取到共享的帮助函数中。例如,对于异步请求,您可以创建一个如下的助手:

```python
async def _fetch(session, method, url, *, headers=None, params=None, json=None):
    try:
        async with session.request(method, url, headers=headers, params=params, json=json) as response:
            if response.status != 200:
                raise Exception(f"Request failed with status code {response.status}")
            return await response.json()
    except aiohttp.ClientError as e:
        logger.error(f"Client error during {method} {url}: {e}", exc_info=True)
        raise Exception(f"请求路由服务时发生错误: {str(e)}")
    except asyncio.TimeoutError:
        logger.error(f"Request to {url} timed out", exc_info=True)
        raise Exception("请求路由服务超时,请稍后重试或检查网络连接。")

然后更新您的 call_api(和类似的方法)以使用它:

async def call_api(self, path: str):
    url = f"{self.api_url}{path}"
    headers = {"Authorization": f"Bearer {self.api_key}"} if self.api_key else {}
    logger.debug(f"Calling API at {url}")
    async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=self.timeout)) as session:
        return await _fetch(session, "GET", url, headers=headers)

您可以类似地为您的同步请求创建带有 requests 的助手,以减少重复。这保持了功能完整,同时减少了重复的嵌套和 try/except 块。


<details>
<summary>Original comment in English</summary>

**issue (complexity):** Consider extracting the network call and error-handling logic into a shared helper function to reduce code duplication.

```markdown
Consider extracting the network call and error‐handling logic into a shared helper. For example, for asynchronous requests you can create a helper like:

```python
async def _fetch(session, method, url, *, headers=None, params=None, json=None):
    try:
        async with session.request(method, url, headers=headers, params=params, json=json) as response:
            if response.status != 200:
                raise Exception(f"Request failed with status code {response.status}")
            return await response.json()
    except aiohttp.ClientError as e:
        logger.error(f"Client error during {method} {url}: {e}", exc_info=True)
        raise Exception(f"请求路由服务时发生错误: {str(e)}")
    except asyncio.TimeoutError:
        logger.error(f"Request to {url} timed out", exc_info=True)
        raise Exception("请求路由服务超时,请稍后重试或检查网络连接。")

Then update your call_api (and similar methods) to use it:

async def call_api(self, path: str):
    url = f"{self.api_url}{path}"
    headers = {"Authorization": f"Bearer {self.api_key}"} if self.api_key else {}
    logger.debug(f"Calling API at {url}")
    async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=self.timeout)) as session:
        return await _fetch(session, "GET", url, headers=headers)

You can similarly create a helper for your synchronous requests with requests to reduce duplication. This keeps functionality intact while reducing the repeated nesting and try/except blocks.


</details>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant