赞
踩
在我们日常工作中,经常需要与上下游交互,特别是当我们做一些基础服务时,需要提供个其他部门使用,因此,需要编写相应的SDK上传至公司私服,供其他部门使用。今天,果冻就来和大家一起实现一个简单的Python SDK,并进行私服的上传和下载。
工程目录结构
├──── easyhttp // SDK目录
│ ├── __init__.py
│ ├── https.py // http工具类
├── tests // 单元测试目录
│ ├── __init__.py
│ ├── test_https.py // http单元测试
├── README.md
├── requirements.txt //依赖包
└── setup.py //setuptools安装
requirements.txt
requests==2.24.0
https.py
# -*- coding:utf8 -*-
"""
@Project: easyhttp
@File: https.py
@Version: v1.0.0
@Time: 2020/6/24 17:22
@Author: guodong.li
@Description: http
"""
from typing import Optional
import requests
import logging
from requests import Response
logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',
level=logging.DEBUG)
class HttpUtils:
headers = {
"Content-Type": "application/json"
}
# http://10.193.199.44:5610/api/v1/manual/sleep?time=0
@staticmethod
def base_get(base_path: str='', detail_path: str='', params: Optional[dict]=None)-> Response:
"""
GET请求
:param base_path: 域名
:param detail_path: 接口详情
:param params: 参数
:return:
"""
logging.info("请求方式:GET, 请求url: %s , 请求参数: %s " % (base_path + detail_path, params))
response = requests.get(base_path + detail_path, params=params)
logging.info("请求方式:GET, 请求url: %s , 请求参数: %s , 结果:%s" % (base_path + detail_path, params, response))
return response
@classmethod
def base_post(cls, base_path: str='', detail_path: str='', params: Optional[dict]=None)-> Response:
"""
POST请求
:param cls:
:param base_path: 域名
:param detail_path: 接口详情
:param params: 参数
:return:
"""
logging.info("请求方式:POST, 请求url: %s ,请求参数: %s " % (base_path + detail_path, params))
response = requests.post(base_path + detail_path, data=params, headers=cls.headers)
logging.info("请求方式:POST, 请求url: %s , 请求参数: %s , 结果:%s" % (base_path + detail_path, params, response))
return response
test_https.py
import requests
import logging
from easyhttp.https import HttpUtils
logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',
level=logging.DEBUG)
r = requests.get("http://xxx.xxx.xxx.xxx:5610/api/v1/manual/sleep?time=0")
logging.info(r) # <Response [200]>
logging.info(type(r)) # <class 'requests.models.Response'>
logging.info(r.status_code) # 200
代码写完了之后,打包并上传到私服。
安装twine包
pip install twine
编写构建工具setup.py进行打包
# -*- coding:utf8 -*-
"""
@author: guodong.li
@email: liguodongiot@163.com
@time: 2019/7/31 14:04
@file: setup.py
@desc:
"""
# 引入构建包信息的模块
from setuptools import setup, find_packages
try: # for pip >= 10
from pip._internal.req import parse_requirements
from pip._internal.network.session import PipSession
except ImportError: # for pip <= 9.0.3
from pip.req import parse_requirements
from pip.download import PipSession
# parse_requirements() returns generator of pip.req.InstallRequirement objects
install_reqs = parse_requirements('requirements.txt', session=PipSession())
# reqs is a list of requirement
# e.g. ['django==1.5.1', 'mezzanine==1.4.6']
reqs = [str(ir.req) for ir in install_reqs]
# 定义发布的包文件的信息
setup(
name="easyhttp", # 发布的包的名称
version="1.0.0", # 发布包的版本序号
description="easy use http", # 发布包的描述信息
author="guodong.li", # 发布包的作者信息
author_email="liguodongiot@163.com", # 作者的联系邮箱
packages=["easyhttp"],
# include_package_data=True, # include everything in source control
# ...but exclude README.txt from all packages
exclude_package_data={'': ['README.md'],
'tests': ['*.py']},
install_requires=reqs,
)
setup.py各参数简单介绍如下:
新增.pypirc文件
touch ~/.pypirc
在.pypirc文件添加如下配置
[distutils]
index-servers =
pypi
nexus
[pypi]
repository:https://pypi.python.org/pypi
username:your_username
password:your_password
[nexus]
repository=http://192.168.12.196:8081/repository/mypypi-hosted/
username=your_username
password=your_password
打包并上传至私服仓库nexus
python setup.py sdist bdist_wheel upload -r nexus
或者打包命令和上传命令分开操作
1、打包命令
python setup.py sdist bdist_wheel
2、上传命令
twine upload -r nexus dist/* # -r 可以选择仓库地址
创建虚拟环境
virtualenv -p /usr/bin/python venv
激活虚拟环境
source venv/bin/activate
下载包
pip install easyhttp==1.0.0 -i http://your_username:your_password@192.168.12.196:8081/repository/mypypi-hosted/simple/ --trusted-host 192.168.12.196
进入python shell环境
python
代码验证
>>> from pai.utils.https import HttpUtils
>>> import logging
>>> logging.basicConfig(format='%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s',level=logging.INFO)
>>> r = requests.get("http://10.xxx.xxx.xxx:5610/api/v1/manual/sleep?time=0")
2020-07-02 11:31:50,903 - /root/python/20200702/venv/lib/python3.7/site-packages/urllib3/connectionpool.py[line:230] - DEBUG: Starting new HTTP connection (1): 10.xxx.xxx.xxx:5610
2020-07-02 11:31:51,065 - /root/python/20200702/venv/lib/python3.7/site-packages/urllib3/connectionpool.py[line:442] - DEBUG: http://10.xxx.xxx.xxx:5610 "GET /api/v1/manual/sleep?time=0 HTTP/1.1" 200 None
>>> logging.info(r) # <Response [200]>
2020-07-02 11:32:15,420 - <stdin>[line:1] - INFO: <Response [200]>
>>>
>>> logging.info(type(r)) # <class 'requests.models.Response'>
2020-07-02 11:32:27,371 - <stdin>[line:1] - INFO: <class 'requests.models.Response'>
>>> logging.info(r.status_code) # 200
2020-07-02 11:32:39,069 - <stdin>[line:1] - INFO: 200
至此,一个简单的Python SDK就已经制作完成,并且实现了SDK到私服的上传与下载。
你好,我叫果冻,创作不易,如果觉得我的博文能够帮助到你,期待你的点赞,祝好~~~
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。