python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python SDK私服上传下载

Python SDK实现私服上传下载的示例

作者:王嘉尔学Python

本文主要介绍了Python SDK实现私服上传下载的示例,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下<BR>

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

到此这篇关于Python SDK实现私服上传下载的示例的文章就介绍到这了,更多相关Python SDK私服上传下载内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文