如何制作一个Python SDK并实现私服上传下载

简介: 在我们日常工作中,经常需要与上下游交互,特别是当我们做一些基础服务时,需要提供个其他部门使用,因此,需要编写相应的SDK上传至公司私服,供其他部门使用。今天,果冻就来和大家一起实现一个简单的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)  # <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各参数简单介绍如下:

  • --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: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到私服的上传与下载。

相关文章
|
搜索推荐 API 开发工具
百宝箱开放平台 ✖️ Python SDK
百宝箱提供Python SDK,支持开发者集成其开放能力。需先发布应用,安装Python 3.6+环境后,通过pip安装tboxsdk,即可调用对话型、生成型智能体及文件上传等功能。
1245 87
百宝箱开放平台 ✖️  Python SDK
|
Web App开发 安全 数据安全/隐私保护
利用Python+Requests实现抖音无水印视频下载
利用Python+Requests实现抖音无水印视频下载
|
API 开发工具 网络架构
【Azure Service Bus】使用Python SDK创建Service Bus Namespace资源(中国区)
本文介绍了如何使用Python SDK创建Azure Service Bus Namespace资源。首先,通过Microsoft Entra ID注册应用获取Client ID、Client Secret和Tenant ID,完成中国区Azure认证。接着,初始化ServiceBusManagementClient对象,并调用`begin_create_or_update`方法创建资源。
403 30
|
小程序 PHP 图形学
热门小游戏源码(Python+PHP)下载-微信小程序游戏源码Unity发实战指南​
本文详解如何结合Python、PHP与Unity开发并部署小游戏至微信小程序。涵盖技术选型、Pygame实战、PHP后端对接、Unity转换适配及性能优化,提供从原型到发布的完整指南,助力开发者快速上手并发布游戏。
|
API 开发工具 Python
|
人工智能 API 开发工具
【AI大模型】使用Python调用DeepSeek的API,原来SDK是调用这个,绝对的一分钟上手和使用
本文详细介绍了如何使用Python调用DeepSeek的API,从申请API-Key到实现代码层对话,手把手教你快速上手。DeepSeek作为领先的AI大模型,提供免费体验机会,帮助开发者探索其语言生成能力。通过简单示例代码与自定义界面开发,展示了API的实际应用,让对接过程在一分钟内轻松完成,为项目开发带来更多可能。
|
机器学习/深度学习 数据采集 数据可视化
Python/Anaconda双方案加持!Jupyter Notebook全平台下载教程来袭
Jupyter Notebook 是一款交互式编程与数据科学分析工具,支持40多种编程语言,广泛应用于机器学习、数据清洗和学术研究。其核心优势包括实时执行代码片段、支持Markdown文档与LaTeX公式混排,并可导出HTML/PDF/幻灯片等格式。本文详细介绍了Jupyter Notebook的软件定位、特性、安装方案(Anaconda集成环境与原生Python+PIP安装)、首次运行配置及常见问题解决方案,帮助用户快速上手并高效使用该工具。
|
存储 XML 开发工具
【Azure Storage Account】利用App Service作为反向代理, 并使用.NET Storage Account SDK实现上传/下载操作
本文介绍了如何在Azure上使用App Service作为反向代理,以自定义域名访问Storage Account。主要内容包括: 1. **设置反向代理**:通过配置`applicationhost.xdt`和`web.config`文件,启用IIS代理功能并设置重写规则。 2. **验证访问**:测试原生URL和自定义域名的访问效果,确保两者均可正常访问Storage Account。 3. **.NET SDK连接**:使用共享访问签名(SAS URL)初始化BlobServiceClient对象,实现通过自定义域名访问存储服务。
368 0
|
开发工具 Android开发
X Android SDK file not found: adb.安卓开发常见问题-Android SDK 缺少 `adb`(Android Debug Bridge)-优雅草卓伊凡
X Android SDK file not found: adb.安卓开发常见问题-Android SDK 缺少 `adb`(Android Debug Bridge)-优雅草卓伊凡
1329 11
X Android SDK file not found: adb.安卓开发常见问题-Android SDK 缺少 `adb`(Android Debug Bridge)-优雅草卓伊凡
|
JavaScript 前端开发 Java
[Android][Framework]系统jar包,sdk的制作及引用
[Android][Framework]系统jar包,sdk的制作及引用
772 0

推荐镜像

更多