如何制作一个Python 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)  # 
logging.info(type(r))  # 
logging.info(r.status_code)  # 200

代码写完了之后,打包并上传到私服。

打包并上传私服

安装twine包

pip install twine

编写构建工具setup.py进行打包

# -*- coding:utf8 -*-
"""
@author: guodong.li
@email: [email protected]
@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="[email protected]",  # 作者的联系邮箱
    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各参数简单介绍如下:

  • –name 包名称
  • –version (-V) 包版本
  • –author 程序的作者
  • –author_email 程序的作者的邮箱地址
  • –maintainer 维护者
  • –maintainer_email 维护者的邮箱地址
  • –url 程序的官网地址
  • –license 程序的授权信息
  • –description 程序的简单描述
  • –long_description 程序的详细描述
  • –platforms 程序适用的软件平台列表
  • –classifiers 程序的所属分类列表
  • –keywords 程序的关键字列表
  • –packages 需要处理的包目录(包含__init__.py的文件夹)
  • –py_modules 需要打包的python文件列表
  • –download_url 程序的下载地址
  • –data_files 打包时需要打包的数据文件,如图片,配置文件等
  • –scripts 安装时需要执行的脚步列表
  • –package_dir 告诉setuptools哪些目录下的文件被映射到哪个源码包。一个例子:package_dir = {’’: ‘lib’},表示“root package”中的模块都在lib 目录中。
  • –requires 定义依赖哪些模块
  • –provides 定义可以为哪些模块提供依赖
  • –find_packages() 对于简单工程来说,手动增加packages参数很容易,刚刚我们用到了这个函数,它默认在和setup.py同一目录下搜索各个含有 init.py的包。其实我们可以将包统一放在一个src目录中,另外,这个包内可能还有aaa.txt文件和data数据文件夹。还可以排除一些特定的包find_packages(exclude=[".tests", ".tests.", "tests.", “tests”])
  • –install_requires = [“requests”] 需要安装的依赖包
  • –entry_points 动态发现服务和插件

新增.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:[email protected]: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)  # 
2020-07-02 11:32:15,420 - <stdin>[line:1] - INFO: <Response [200]>
>>> 
>>> logging.info(type(r))  # 
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到私服的上传与下载。

你可能感兴趣的:(Python,python,程序人生,编程语言,源码,sdk)