Python 使用 kombu 连接信息中包含#号问题排查

本文讲述了在使用Python的kombu库时,遇到在生产环境中连接AMQP服务器的错误,问题源于URL中包含的#号导致端口号解析失败。作者通过创建虚拟环境、管理依赖并详细排查,展示了如何解决这个问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python 项目部署生产环境遇到一个错误问题 raise ValueError(f"Port could not be cast to integer value as {port!r}") ValueError: Port could not be cast to integer value as 'guest 测试环境和本地调试都没有问题,但是到生产之后就有问题,本章复现有问题的mq连接配置的导致的错误信息,记录问题排查过程

版本信息

框架版本
python3.11.7
kombu5.3.4

环境搭建

python 虚拟环境

Python 虚拟环境(Virtual Environment)是一个隔离的 Python 解释器环境,它允许你为每个 Python 项目安装其特定的依赖包,而不会干扰到全局 Python 环境或其他项目。这样,你可以确保每个项目都有其独立的、一致的依赖环境,避免了版本冲突和依赖混乱的问题。

Python 中有几个流行的工具用于创建和管理虚拟环境,其中最常用的是 venv 和 virtualenv

venv 创建 python 虚拟环境

python -m venv .venv

执行该命令之后,会创建一个虚拟的环境,产生 .venv文件夹, 目录结构如下
在这里插入图片描述

激活虚拟环境

.venv\Scripts\activate

在这里插入图片描述
激活虚拟环境之后,文件夹前面会有括号显示虚拟环境的名称
在这里插入图片描述

退出虚拟环境

deactivate

在这里插入图片描述

虚拟环境下查看python、pip版本

在这里插入图片描述
查询pip 配置信息

(.venv) F:\Python\mq>pip config list
global.index-url='http://mirrors.aliyun.com/pypi/simple/'
install.trusted-host='mirrors.aliyun.com'

安装依赖

编写 requirements.txt

kombu==5.3.4

在虚拟环境里面安装依赖

pip install -r requirements.txt

问题复现以及问题排查

  1. 消息发布端 hello_publisher.py
from __future__ import annotations

import datetime

from kombu import Connection

with Connection('amqp://guest:guest#2024@localhost:5672//') as conn:
    simple_queue = conn.SimpleQueue('simple_queue')
    message = f'helloworld, sent at {datetime.datetime.today()}'
    simple_queue.put(message)
    print(f'Sent: {message}')
    simple_queue.close()
  1. 在虚拟环境运行代码,出现如下报错信息
(.venv) F:\Python\mq>python hello_publisher.py
Traceback (most recent call last):
  File "F:\Python\mq\hello_publisher.py", line 7, in <module>
    with Connection('amqp://guest:guest#2024@localhost:5672//') as conn:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "F:\Python\mq\.venv\Lib\site-packages\kombu\connection.py", line 203, in __init__
    url_params = parse_url(hostname)
                 ^^^^^^^^^^^^^^^^^^^
  File "F:\Python\mq\.venv\Lib\site-packages\kombu\utils\url.py", line 38, in parse_url
    scheme, host, port, user, password, path, query = _parse_url(url)
                                                      ^^^^^^^^^^^^^^^
  File "F:\Python\mq\.venv\Lib\site-packages\kombu\utils\url.py", line 70, in url_to_parts
    parts.port,
    ^^^^^^^^^^
  File "E:\Anaconda\Lib\urllib\parse.py", line 182, in port
    raise ValueError(f"Port could not be cast to integer value as {port!r}")
ValueError: Port could not be cast to integer value as 'guest'

看到报错的堆栈信息,首先定位到代码行 File "F:\Python\mq\.venv\Lib\site-packages\kombu\utils\url.py", line 70 ,在此处加一个断点,调试一下(生产服务不能调试就print输出一下信息)

  1. 调试出问题的代码
    报错的代码方法如下
def url_to_parts(url):
    # type: (str) -> urlparts
    """Parse URL into :class:`urlparts` tuple of components."""
    scheme = urlparse(url).scheme
    schemeless = url[len(scheme) + 3:]
    # parse with HTTP URL semantics
    parts = urlparse('http://' + schemeless)
    path = parts.path or ''
    path = path[1:] if path and path[0] == '/' else path
    return urlparts(
        scheme,
        unquote(parts.hostname or '') or None,
        parts.port,
        unquote(parts.username or '') or None,
        unquote(parts.password or '') or None,
        unquote(path or '') or None,
        dict(parse_qsl(parts.query)),
    )

parts.port 获取的值从 urlparse 方法中解析出来的
在这里插入图片描述
执行完 urlparse 方法之后获取到的数值如下
在这里插入图片描述
port 的解析在 urlparse 这一步出了问题,重点来看看这个方法的逻辑
在这里插入图片描述
经过调试发现问题出在切割方法里面 urllib.parse.urlsplit,具体处理出问题代码在如下片段
在这里插入图片描述
链接中有 # 号导致切割之后端口号错位未获取到

  1. 去除链接中的#号的正常解析的数据如下
    在这里插入图片描述
    链接中没有 # 号之后,端口可以正常解析了
dkl@dkl-VMware-Virtual-Platform:~/learn/graph/study_celery$ celery -A celery_task worker -I info Usage: celery [OPTIONS] COMMAND [ARGS]... Try &#39;celery --help&#39; for help. Error: Invalid value for &#39;-A&#39; / &#39;--app&#39;: Unable to load celery application. While trying to load the module celery_task the following error occurred: Traceback (most recent call last): File "/home/dkl/learn/env/lib/python3.12/site-packages/celery/app/utils.py", line 389, in find_app found = sym.app ^^^^^^^ AttributeError: module &#39;celery_task&#39; has no attribute &#39;app&#39; During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/dkl/learn/env/lib/python3.12/site-packages/celery/app/utils.py", line 394, in find_app found = sym.celery ^^^^^^^^^^ AttributeError: module &#39;celery_task&#39; has no attribute &#39;celery&#39; During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/dkl/learn/env/lib/python3.12/site-packages/celery/app/utils.py", line 383, in find_app sym = symbol_by_name(app, imp=imp) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/dkl/learn/env/lib/python3.12/site-packages/kombu/utils/imports.py", line 64, in symbol_by_name return getattr(module, cls_name) if cls_name else module ^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: module &#39;celery_task&#39; has no attribute &#39;celery&#39; During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/dkl/learn/env/lib/python3.12/site-packages/celery/bin/celery.py", line 58, in convert return find_app(value) ^^^^^^^^^^^^^^^ File "/home/dkl/learn/env/lib/python3.12/site-packages/celery/app/utils.py", line 401, in find_app return find_app( ^^^^^^^^^ File "/home/dkl/learn/env/lib/python3.12/site-packages/celery/app/utils.py", line 386, in find_app sym = imp(app) ^^^^^^^^ File "/home/dkl/learn/env/lib/python3.12/site-packages/celery/utils/imports.py", line 109, in import_from_cwd return imp(module, package=package) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/lib/python3.12/importlib/__init__.py", line 90, in import_module return _bootstrap._gcd_import(name[level:], package, level) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<frozen importlib._bootstrap>", line 1387, in _gcd_import File "<frozen importlib._bootstrap>", line 1360, in _find_and_load File "<frozen importlib._bootstrap>", line 1331, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 935, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 995, in exec_module File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed File "/home/dkl/learn/graph/study_celery/celery_task/celery.py", line 30, in <module> &#39;schedule&#39;: crontab(seconds=10), ^^^^^^^^^^^^^^^^^^^ File "/home/dkl/learn/env/lib/python3.12/site-packages/celery/schedules.py", line 409, in __init__ super().__init__(**kwargs) TypeError: BaseSchedule.__init__() got an unexpected keyword argument &#39;seconds&#39;
03-28
python manage.py createsuperuser Traceback (most recent call last): File "E:\learn\ttsxzjc\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\core\management\__init__.py", line 347, in execute django.setup() File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\__init__.py", line 16, in setup from django.urls import set_script_prefix File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\urls\__init__.py", line 1, in <module> from .base import ( File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\urls\base.py", line 8, in <module> from .exceptions import NoReverseMatch, Resolver404 File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\urls\exceptions.py", line 1, in <module> from django.http import Http404 File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\http\__init__.py", line 5, in <module> from django.http.response import ( File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\http\response.py", line 13, in <module> from django.core.serializers.json import DjangoJSONEncoder File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\core\serializers\__init__.py", line 23, in <module> from django.core.serializers.base import SerializerDoesNotExist File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\core\serializers\base.py", line 6, in <module> from django.db import models File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\db\models\__init__.py", line 3, in <module> from django.db.models.aggregates import * # NOQA ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "E:\learn\ttsxzjc\.venv\Lib\site-packages\django\db\models\aggregates.py", line 5, in <module> from django.db.models.expressions import Case, Func, Star, When File "E:\learn\ttsxzjc\.venv\Lib\site-packages\djan
03-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Chengdu.S

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值