You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

重写Confluence page_exists函数遇self未定义错误,求自定义实现方案

问题描述

我尝试基于atlassian-python-api的Confluence模块中page_exists函数的逻辑,从零编写自定义Python脚本,目的是后续能根据需求定制Confluence相关函数。但运行代码时出现“self未定义”错误,错误出现在这一行:

response = self.get(url, params=params)

以下是我的代码:

from atlassian import Confluence

f = open('log.txt','w')
print('file open', file=f) # Python 3.x

confluence = Confluence(
    url='https://site_name.atlassian.net',
    username='email',
    password='Token_API',
    cloud=True)

print('connetion established', file=f) # Python 3.x

space='TEAM'
title="new page"

print('variables defined', file=f) # Python 3.x

url = "rest/api/content"
params = {}
if space is not None:
            params["spaceKey"] = str(space)
if title is not None:
            params["title"] = str(title)
if type is not None:
            params["type"] = str(type)

try:
            response = self.get(url, params=params)
except HTTPError as e:
            if e.response.status_code == 404:
                raise ApiPermissionError(
                    "The calling user does not have permission to view the content",
                    reason=e,
                )

            raise

print('bgin the if', file=f) # Python 3.x

if response.get("results"):
            print('page exists', file=f) # Python 3.x
else:
           print('page does not exist', file=f) # Python 3.x

请问重写该函数的最佳方式是什么?


解决方案

核心问题分析

你遇到的self未定义错误,是因为原page_exists是Confluence类的成员方法,self代表类的实例对象,但你在全局代码里直接用self,Python找不到这个变量。你应该用自己创建的confluence实例来调用get方法。

另外你的代码还有两个潜在问题:

  1. 缺少HTTPError和ApiPermissionError的导入
  2. type变量未定义,会触发NameError

重写后的完整代码

from atlassian import Confluence
from requests.exceptions import HTTPError
from atlassian.errors import ApiPermissionError

def check_page_exists(confluence_instance, space_key, page_title):
    """自定义检查页面是否存在的函数"""
    url = "rest/api/content"
    params = {
        "spaceKey": str(space_key),
        "title": str(page_title),
        "type": "page"  # 固定指定类型为page,避免歧义
    }
    
    try:
        # 使用传入的confluence实例调用get方法,替代原代码的self.get
        response = confluence_instance.get(url, params=params)
    except HTTPError as e:
        if e.response.status_code == 404:
            raise ApiPermissionError(
                "当前用户没有查看该内容的权限",
                reason=e,
            )
        raise
    
    # 判断结果列表是否非空,非空则页面存在
    return bool(response.get("results"))

# 主逻辑
if __name__ == "__main__":
    with open('log.txt', 'w') as f:
        print('文件已打开', file=f)
        
        # 初始化Confluence连接
        confluence = Confluence(
            url='https://site_name.atlassian.net',
            username='email',
            password='Token_API',
            cloud=True)
        print('连接已建立', file=f)
        
        # 检查页面是否存在
        space = 'TEAM'
        title = "new page"
        print('变量已定义', file=f)
        
        try:
            page_exists = check_page_exists(confluence, space, title)
            if page_exists:
                print('页面存在', file=f)
            else:
                print('页面不存在', file=f)
        except Exception as e:
            print(f'检查出错: {str(e)}', file=f)

关键优化点

  • 把检查逻辑封装成独立函数check_page_exists,方便后续扩展和复用
  • 使用with语句管理文件,自动关闭资源,避免文件泄漏
  • 固定type参数为page,因为原page_exists函数默认检查的就是页面类型
  • 增加异常捕获,避免程序意外崩溃
  • 用返回值替代直接打印,让函数更通用(可以根据返回值做后续逻辑)

内容的提问来源于stack exchange,提问作者supertosti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 09:43:20