Python 调用示例

import json
import os
import urllib.parse
import urllib.request
from hashlib import md5

send_qywx_text_url = "http://10.10.255.196/api/v2/qywxsend/text"
key = "da1f4cddca568b9337d793b5e520c6204b6556b7"
upload_media_url = "http://10.150.26.29:8000/api/v2/media/upload"


def do_get(url):
    """
        get 请求
    :param url: 请求全链接
    """
    req = urllib.request.Request(url=url, method='GET')
    try:
        res = urllib.request.urlopen(req)
        print(json.loads(str(res.read(), encoding='utf-8')))
    except Exception as e:
        print(e)


def do_post(url, to, sendtext):
    """
        post 请求
    :param url: 请求地址
    :param to: 目的接收人
    :param sendtext   发送内容(单一)
    """
    data = {
        'key': key,
        'to': to,
        'body': sendtext,
    }
    data = bytes(json.dumps(data), encoding='utf-8')
    req = urllib.request.Request(url=url, data=data, method='POST')
    try:
        res = urllib.request.urlopen(req)
        print(json.loads(str(res.read(), encoding='utf-8')))
    except Exception as e:
        print(e)


def do_post_upload(url, media_path):
    """
        文件上传Post
    :param url: 请求链接
    :param media_path: 上传文件路径
    """
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6',
        'Content-MD5': _get_file_md5(media_path),
        'Content-Type': 'text/plain',
        'Content-Length': _get_file_size(media_path),
        'Content-Disposition': urllib.parse.quote(os.path.basename(media_path)),
        'key': key
    }
    data = _get_file_content(media_path)
    req = urllib.request.Request(url=url, data=data, method='POST', headers=headers)
    try:
        res = urllib.request.urlopen(req)
        print(json.loads(str(res.read(), encoding='utf-8')))
    except Exception as e:
        print(e.read())


def _get_file_content(f, method='rb'):
    fp = open(f, method)
    s = fp.read()
    fp.close()
    return s


def _get_file_size(f):
    return os.stat(f).st_size


def _get_file_md5(f):
    if not os.path.isfile(f):
        return
    myhash = md5()
    f = open(f, 'rb')
    while True:
        b = f.read(1024 * 10240)
        if not b:
            break
        myhash.update(b)
    f.close()
    return myhash.hexdigest()

results matching ""

    No results matching ""