Skip to content

Python

python
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import hmac, base64, hashlib, requests, json
import time
# auth
class Api_Auth(object):
	def __init__(self):
     # replace following params with your ak sk
		self.ak = 'ak'
		self.sk = bytes('sk', encoding='utf-8')
		self.host = "api.niulinkcloud.com"

	def getSignKey(self, data):
		sign = hmac.new(self.sk, data, hashlib.sha1).digest()
		token = self.ak + ":" + base64.urlsafe_b64encode(sign).decode("utf-8")
		return "Qiniu " + token

	def getRequestData(self, method, path, queryStr="", bodyStr="", contentType="application/json"):
		data = method+" "+path
		if queryStr != "":
			data += "?"+queryStr
		data += "\nHost: "+self.host
		if bodyStr != "":
			data += "\nContent-Type: " + contentType
		data += "\n\n"
		if bodyStr != "" and bodyStr != "application/octet-stream":
			data += bodyStr
		return data

# get status
class Api_Data(object):
	# use /v1/nodes/status as an example of GET api
	def get_data(self):
		url = 'https://api.niulinkcloud.com/v1/nodes/status'
		path = '/v1/nodes/status'
		data = Api_Auth().getRequestData("GET", path, "", "")
		signkey = Api_Auth().getSignKey(data.encode('utf-8'))
		headers = {
			'Authorization': signkey,
		}
		response = requests.get(url, headers=headers, data='')
		return response.content.decode()

	# use /v1/nodes/:nodeId/submit as an example of POST api, path is like '/v1/nodes/aaa/submit'
	# PUT DELETE PATCH api can refer to this api
	def post_data(self, path, jsonData):
		api = Api_Auth()
		data = Api_Auth().getRequestData("POST", path, "", json.dumps(jsonData))
		signkey = Api_Auth().getSignKey(data.encode('utf-8'))
		headers = {
			'Authorization': signkey,
		  'Content-Type': 'application/json',
		}
		# print(signkey)

		url = 'https://'+api.host+path
		response = requests.post(url, headers=headers,  data=json.dumps(jsonData))
		return response.content.decode()

print(Api_Data().get_data())
# 节点id为aaa的专线节点提交
submitData = {"province":"浙江","city":"杭州","isp":"电信","usbw":1000,"bwNum":1,"natType":"public","dialType":"staticNetSingle"}
print(Api_Data().post_data('/v1/nodes/aaa/submit',submitData))