在Python中调用网站接口通常有以下几种方法:
1. 使用`requests`库
import requests
url = 'https://api.example.com'
params = {'key': 'value'}
response = requests.get(url, params=params)
if response.status_code == 200:
data = response.json()
print(data)
else:
print('Error:', response.status_code)
2. 使用`urllib2`库
import urllib2
github_url = 'https://api.github.com/user/repos'
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, github_url, 'user', 'password')
auth = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth)
urllib2.install_opener(opener)
request = urllib2.Request(github_url, urllib.urlencode({'name': 'Test repo', 'description': 'Some test repository'}))
response = opener.open(request)
print(response.read())
3. 使用`suds-jurko`库调用SOAP接口
from suds.client import Client
url = 'http://116.62.123.123:5080/WebService/?wsdl'
client = Client(url)
print(client)
num1 = client.service.GetVarValue('', 8, '')
print(num1)
4. 使用`Ladon`框架封装Python为Webservice接口
from ladon.server import LadonWSGIApplication
app = LadonWSGIApplication(['appapi.views'], [os.path.join(os.path.dirname(__file__), os.path.pardir)], catalog_name='OPS APP API', catalog_desc='This is the root of my cool webservice catalog')
请根据接口类型和需求选择合适的方法。如果接口是HTTP接口,推荐使用`requests`库,因为它更简单、易用,且功能强大。如果接口是SOAP接口,可以使用`suds-jurko`库。如果需要自己编写Webservice接口,可以使用`Ladon`框架。