python sanic 设置ssl证书_Python通过证书调用基于SSL的Webservice

首先,普及一下各种类型的证书知识,以及格式之间的转换方法:http://liuleijsjx.iteye.com/blog/433853

然后就是调用代码了:#!/usr/bin/env python

# -*- coding: utf-8 -*-

__author__ = 'tan9le'

import urllib2 as u2

from suds.client import Client

from suds.transport.http import HttpTransport, Reply, TransportError

import httplib

class HTTPSClientAuthHandler(u2.HTTPSHandler):

def __init__(self, key, cert):

u2.HTTPSHandler.__init__(self)

self.key = key

self.cert = cert

def https_open(self, req):

#Rather than pass in a reference to a connection class, we pass in

# a reference to a function which, for all intents and purposes,

# will behave as a constructor

return self.do_open(self.getConnection, req)

def getConnection(self, host, timeout=300):

return httplib.HTTPSConnection(host, key_file=self.key, cert_file=self.cert)

class HTTPSClientCertTransport(HttpTransport):

def __init__(self, key, cert, *args, **kwargs):

HttpTransport.__init__(self, *args, **kwargs)

self.key = key

self.cert = cert

def u2open(self, u2request):

tm = self.options.timeout

url = u2.build_opener(HTTPSClientAuthHandler(self.key, self.cert))

if self.u2ver() < 2.6:

socket.setdefaulttimeout(tm)

return url.open(u2request)

else:

return url.open(u2request, timeout=tm)

# These lines enable debug logging; remove them once everything works.

def getClient(url, key, cert):

import logging

logging.basicConfig(level=logging.INFO)

logging.getLogger('suds.client').setLevel(logging.DEBUG)

logging.getLogger('suds.transport').setLevel(logging.DEBUG)

c = Client(url,transport = HTTPSClientCertTransport(key, cert))

return c

def websevicewithcer(url):

#key文件是从pfx导出的,命令是:openssl pkcs12 -in xxx.pfx -nocerts -nodes -out private.key

key = 'D:/Work/cer/private.key' #这里换成你调用端的私钥文件

#cer是IE导出的,记得要用Base64编码格式的

cert = 'D:/Work/cer/public.cer' #这里换成你要调用的网址的客户端证书文件

client = getClient(url, key, cert)

result = client.service

return result

def 自定义方法(param):

wsdl_url = 'https://ip:port/xxx/services/portname?wsdl'

websev = websevicewithcer(wsdl_url)

#调用方式websev.方法名(参数)

ws = websev.方法名(param)

return ws

if __name__ == '__main__':

result = 自定义方法('参数')

print result

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值