python测试restful接口封装

代码未修剪,可供参考

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import requests, json
import os,sys,re,time
from rados import (Rados, Error, RadosStateError, Object, ObjectExists,
                   ObjectNotFound, ObjectBusy, requires, opt,
                   LIBRADOS_ALL_NSPACES, WriteOpCtx, ReadOpCtx,
                   LIBRADOS_SNAP_HEAD, LIBRADOS_OPERATION_BALANCE_READS, LIBRADOS_OPERATION_SKIPRWLOCKS, MonitorLog)

rados = Rados(conffile='')
rados.conf_parse_env('FOO_DOES_NOT_EXIST_BLAHBLAH')
rados.conf_parse_env()
rados.connect()

script_path = os.path.realpath(__file__)
option1=''
if len(sys.argv)>1:
    option1=sys.argv[1]
MY_ADMIN_TOKEN='eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJjZXBoLWRhc2hib2FyZCIsImlhdCI6MTYxOTQ4NTYxMCwidXNlcm5hbWUiOiJhZG1pbiIsImp0aSI6IjljNWQ2Y2YwLTQ0ZmQtNGUwZS04YjQ1LTJlNzJkYTVlMDRhMiIsImV4cCI6MTYxOTUxNDQxMH0.0lH3D_wPvQAM29pnYCqq6vgl-EeFcl2M6xeSU_DuYA0'

URL='http://192.168.110.187:8444'

def get_token():    #获取token
    url=URL+'/api/auth'
    headers={'Content-Type':'application/json',
            'Accept': 'application/vnd.ceph.api.v1.0+json',
            }
    data = {"username": "admin", "password": "admin"}
    result = requests.post(
        url,
        #data=json.dumps(data),
        json=data,
        headers=headers,
    )
    return result.json()['token']


def send_request(method,url,data,msg,return_json=True):    #发送post
    print(msg)
    headers={'Content-Type':'application/json',
            'Accept': 'application/vnd.ceph.api.v1.0+json',
            'Authorization':'Bearer ' +MY_ADMIN_TOKEN,
            }
    request_method=None
    if  method=='POST':
        request_method= requests.post
    elif  method=='GET':
        request_method= requests.get
    elif  method=='DELETE':
        request_method= requests.delete
    elif  method=='PUT':
        request_method= requests.put
    result = request_method(
        url,
        data=json.dumps(data),
        #json=data,
        headers=headers,
    )
    if return_json==True:
      return result.json()
    else:
      return {'status':result.status_code,'text':result.text}

if  option1== '-t':     #获取token
    token=get_token()
    content=''
    with open(script_path,'r') as me:
        script=me.read()
        pattern = re.compile(r'MY_ADMIN_TOKEN.+\'(?=\n)') 
        match=pattern.findall(script)
        #print(match)
    content = pattern.sub('MY_ADMIN_TOKEN=\''+token+'\'', script)
    with open(script_path,'w') as me:
        me.write(content)
    os.system('python '+script_path)
    exit()
elif  option1== '-d':   #删除export
    exports=send_request('GET',URL+'/api/nfs-ganesha/export', '', '查看export列表') 
    print ('删除导出   ', exports)
    for ex in exports:
      eid=''+str(ex['export_id'])
      print(eid)
      print(send_request('DELETE',URL+"/api/nfs-ganesha/export/_default_/"+eid+"?reload_daemons=true", '', '删除export :'+eid))
    exit()  
    
    
create_export= {     #创建nfs export
  "clients": [
    {
      "addresses": ["12"],
      "access_type": "RW",
      "squash": "root"
    }
  ],
  "pseudo": "/y",
  "squash": "root",
  "access_type": "RW",
  "security_label": "",
  "cluster_id": "_default_",
  "tag": "gdfjvh",
  "fsal": {
    "rgw_user_id": "admin",
    "sec_label_xattr": "111",
    "user_id": "admin",
    "name": "RGW",
    "filesystem": "RGW",
    "RGW":{
        "name":"client.rgw.",
        "ceph_conf":"/etc/ceph/ceph.conf",
        "cluster":"ceph",
        "init_args":"--log_file=/var/log/ganesha/rgw.log --debug-rgw=1 --rgw_nfs_s3_fast_attrs=true"
    }
  },
  "reload_daemons": True,
  "daemons": [
    "node1"
  ],
  "path": "/",
  "transports": [
    "TCP"
  ],
  "protocols": [
    4
  ],
  "expend": { 
    "expend": { 
    "grace_period": 10,
    "Anonymous_Uid": 0,
    "Anonymous_Gid": 0
  }
  }
}

def test_nfs():
  print(send_request('GET',URL+'/api/nfs-ganesha/daemon', '', '查看daemon列表') )  
  exports=send_request('GET',URL+'/api/nfs-ganesha/export', '', '查看export列表') 
  ioctx = rados.open_ioctx('ganesha_data')
  ioctx.set_namespace('ganesha-export-index')
  objs=ioctx.list_objects()
  keeys=[]
  for obj in objs:
      keeys.append(obj.key)
  print(keeys)
  print(exports) 

  print(send_request('GET',URL+'/api/host/hostsaddr', create_export, '获取集群节点列表'))
  print(send_request('GET',URL+'/api/host/rgwnfs', create_export, '获取rgw-nfs节点列表'))


#os.system('rados -p ganesha_data ls')
#print(rados.pool_exists('ganesha_data'))
ioctx = rados.open_ioctx('ganesha_data')
ioctx.set_namespace('ganesha-export-index')
ioctx.list_objects()
raw_config=' EXPORT {\
    grace_period = 0;\
    FSAL {\
        secret_access_key = "admin";\
        user_id = "admin";\
        name = "RGW";\
        access_key_id = "admin";\
    }\
\
    CLIENT {\
        clients = "132.45";\
        squash = "root_squash";\
        access_type = "RW";\
    }\
\
    Anonymous_Gidfsdfdfdfdf = 0;\
    pseudo = "/";\
    squash = "root_squash";\
    access_type = "RW";\
    tag = "gdfj11h";\
    Anonymous_Gid = 0;\
    Anonymous_Uid = 0;\
    path = "/i";\
    export_id = 1;\
    transports = "TCP";\
    protocols = 4;\
}\
\
RGW {\
    ceph_conf = "/etc/ceph/ceph.conf";\
    name = "client.rgw.node1";\
    init_args = "--log_file=/var/log/ganesha/rgw.log --debug-rgw=1 --rgw_nfs_s3_fast_attrs=true";\
    cluster = "ceph";\
}'

change_export= {     #创建nfs export
  "clients": [
    {
      "addresses": [
        "211","55"
      ],
      "access_type": "RW",
      "squash": "root"
    }
  ],
  "pseudo": "/y",
  "squash": "root",
  "access_type": "RW",
  "security_label": "",
  "cluster_id": "_default_",
  "tag": "test_change",
  "fsal": {
    "sec_label_xattr": "111",
    "user_id": "admin",
    "name": "RGW",
    "filesystem": "RGW",
    "RGW":{
        "name":"client.rgw.node1",
        "ceph_conf":"/etc/ceph/ceph.conf",
        "cluster":"ceph",
        "init_args":"--log_file=/var/log/ganesha/rgw.log --debug-rgw=1 --rgw_nfs_s3_fast_attrs=true"
    }
  },
  "reload_daemons": True,
  "daemons": [
    "node1"
  ],
  "path": "/",
  "transports": [
    "TCP"
  ],
  "protocols": [
    4
  ],
  "expend": { 
    "grace_period": 0,
    "Anonymous_Uid": 0,
    "Anonymous_Gid": 0
  }
}

#print(send_request('DELETE',URL+'/api/nfs-ganesha/export/_default_/1?reload_daemons=true', '', '删除export'))
change_clients= {     
  "clients": [
    {
      "addresses": [
        "187"
      ],
      "access_type": "RW",
      "squash": "root"
    },
    {
      "addresses": [
        "110"
      ],
      "access_type": "OR",
      "squash": "root_squash"
    }
  ]
}

def test_nfs():
  print(send_request('POST',URL+'/api/nfs-ganesha/export', create_export, '创建export'))
  print(send_request('GET',URL+'/api/nfs-ganesha/export', '', '查看export列表')) 
  print(send_request('GET',URL+'/api/nfs-ganesha/status', create_export, '查看ganesha状态'))
  print(send_request('PUT',URL+'/api/nfs-ganesha/export/_default_/1', change_export, '修改export'))
  print(send_request('PUT',URL+'/api/nfs-ganesha/export/_default_/2', change_export, '修改export'))
  print(send_request('PUT',URL+'/api/nfs-ganesha/client/_default_/1', change_clients, '修改clients'))
  print(send_request('GET',URL+'/api/nfs-ganesha/client/_default_/1', '', '查看clients'))
  print(send_request('GET',URL+'/ui-api/nfs-ganesha/clusters', '', '查看集群ID'))
  print(send_request('GET',URL+'/ui-api/nfs-ganesha/cephx/clients', '', 'test'))
  print(send_request('GET',URL+'/ui-api/nfs-ganesha/rgw/buckets', '', 'test'))
  #print(send_request('GET',URL+'/ui-api/nfs-ganesha/lsdir', '', 'test'))
  

domain_name={"domain_name":{
  "domain_name":"www.baidu2.com", 
  "ip_list":[
    "192.168.110.187",
    "192.168.110.123"
  ],
  "vip_list":[{
    'name':'vip001',
    'vip_ip':'192.168.110.1',
    'nfs_gateway_ip':[
      "192.168.110.187",
      "192.168.110.123"
    ]
    }
  ]
},
"cluster_id":"_default_"}
def test_domain_name():
  print(send_request('DELETE',URL+'/api/nfs-ganesha/domain_name/_default_/1', '' , '删除域名',return_json=False))
  print(send_request('DELETE',URL+'/api/nfs-ganesha/domain_name/_default_/2', '' , '删除域名',return_json=False))
  print(send_request('POST',URL+'/api/nfs-ganesha/domain_name', domain_name , '添加域名'))
  print(send_request('PUT',URL+'/api/nfs-ganesha/domain_name/_default_/1', domain_name , '修改域名'))
  print(send_request('GET',URL+'/api/nfs-ganesha/domain_name/_default_', '' , '查看域名'))
  #print(send_request('DELETE',URL+'/api/nfs-ganesha/domain_name/_default_/1', '' , '删除域名',return_json=False))
  print(send_request('GET',URL+'/api/nfs-ganesha/domain_name/_default_', '' , '查看域名'))

rgw_export={
    "daemon": "192.168.110.187",
    "clients": [
          "12561", "211","55"
    ],
    "bucket": "y",
    "tag": "nfs02",
    "cluster_id": "_default_",
    "reload_daemons": True,
    "rgw_user_id": "admin",
  }
rgw_export2={
    "daemon": "192.168.110.123",
    "clients": [
          "1211111", "211","55"
        ],
    "bucket": "y",
    "tag": "nfs01",
    "cluster_id": "_default_",
    "reload_daemons": True,
    "rgw_user_id": "admin"
  }
def test_rgw_export():  #测试rgw export接口
  #新的创建export接口
  
  print(send_request('POST',URL+'/api/nfs-ganesha/rgw-export', rgw_export, '创建rgw export'))
  #time.sleep(2)
  print(send_request('PUT',URL+'/api/nfs-ganesha/rgw-export/_default_/1', rgw_export2, '修改rgw export'))
  print(send_request('GET',URL+'/api/nfs-ganesha/rgw-export', '', '查看所有rgw export'))
  print(send_request('GET',URL+'/api/nfs-ganesha/rgw-export/_default_/1', '', '查看rgw export'))
  
def test_nfs_start():
  print(send_request('GET',URL+'/api/nfs-ganesha/daemon/_default_/1/start', '', '开启nfs服务'))
  print(send_request('GET',URL+'/api/nfs-ganesha/daemon/_default_/1/stop', '', '关闭nfs服务'))
  print(send_request('GET',URL+'/api/nfs-ganesha/rgw-export/status/_default_/1', '', '查看网关状态'))

def show_all_object(): #显示所有对象
  object_names = [obj.key for obj in ioctx.list_objects()]   #
  print('列出所有对象')
  print(object_names)
  for obj in ioctx.list_objects():
      size, _ = obj.stat()
      context = obj.read(size)
      context=context.decode("utf-8")
      print(obj.key+':', context)

def remove_all_object():
  #ioctx.write_full('export-2', raw_config.encode('utf-8'))
  ioctx.write_full('conf-node1', ''.encode('utf-8'))
  ioctx.remove_object('export-1')
  ioctx.remove_object('export-2')

def test_host():  #测试获取hosts
  print(send_request('GET',URL+'/api/host/hostsaddr', '' , '获取集群所有节点的host'))
  print(send_request('GET',URL+'/api/host/rgwnfs', '' , '获取集群rgw-nfs节点的host'))
  print(send_request('GET',URL+'/api/host/rgwhosts', '' , '获取集群rgw节点的host'))

def test_rgw():
  print(send_request('GET',URL+'/api/rgw/user', '' , '获取rgw用户信息'))


#test_host()
#test_rgw()

test_rgw_export()

test_domain_name()
test_nfs_start()
print(send_request('POST',URL+'/api/nfs-ganesha/rgw-export', rgw_export, '创建rgw export'))
#show_all_object()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Go语言(也称为Golang)是由Google开发的一种静态强类型、编译型的编程语言。它旨在成为一门简单、高效、安全和并发的编程语言,特别适用于构建高性能的服务器和分布式系统。以下是Go语言的一些主要特点和优势: 简洁性:Go语言的语法简单直观,易于学习和使用。它避免了复杂的语法特性,如继承、重载等,转而采用组合和接口来实现代码的复用和扩展。 高性能:Go语言具有出色的性能,可以媲美C和C++。它使用静态类型系统和编译型语言的优势,能够生成高效的机器码。 并发性:Go语言内置了对并发的支持,通过轻量级的goroutine和channel机制,可以轻松实现并发编程。这使得Go语言在构建高性能的服务器和分布式系统时具有天然的优势。 安全性:Go语言具有强大的类型系统和内存管理机制,能够减少运行时错误和内存泄漏等问题。它还支持编译时检查,可以在编译阶段就发现潜在的问题。 标准库:Go语言的标准库非常丰富,包含了大量的实用功能和工具,如网络编程、文件操作、加密解密等。这使得开发者可以更加专注于业务逻辑的实现,而无需花费太多时间在底层功能的实现上。 跨平台:Go语言支持多种操作系统和平台,包括Windows、Linux、macOS等。它使用统一的构建系统(如Go Modules),可以轻松地跨平台编译和运行代码。 开源和社区支持:Go语言是开源的,具有庞大的社区支持和丰富的资源。开发者可以通过社区获取帮助、分享经验和学习资料。 总之,Go语言是一种简单、高效、安全、并发的编程语言,特别适用于构建高性能的服务器和分布式系统。如果你正在寻找一种易于学习和使用的编程语言,并且需要处理大量的并发请求和数据,那么Go语言可能是一个不错的选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值