python开发一个接口(此处以django为例),供第三方访问

Python编写API接口

要求通过http://172.17.37.62:8888/create_copy_task/?src=/mnt/source1/qin.txt&dst=/mnt/target1/qin.txt进行访问,参数src和dst分别代表源文件路径和目标端文件路径

1.编写应用url:浏览器会自动将?后面识别为参数。

urlpatterns = [
    url(r'^create_copy_task/$', copytask, name='copytask'),
]

2.编写view:

python开发一个接口(此处以django为例),供第三方访问
def copytask(request):
    source = request.GET['src']
    destination = request.GET['dst']
    copy_type = request.GET['copy_type']
    print(source,destination,copy_type)
    m = 'source:'source + 'target:'destination
    return HttpResponse(str(m))
python开发一个接口(此处以django为例),供第三方访问

浏览器返回json类型结果:

python开发一个接口(此处以django为例),供第三方访问
import json
def copytask(request):
    source = request.GET['src']
    destination = request.GET['dst']
    copy_type = request.GET['copy_type']
    print(source,destination,copy_type)
    rets = {"source":source,'target':destination}
    retsj = json.dumps(rets) #返回json类型数据 {"source": "/mnt/source1/qin.txt", "target": "/mnt/target1/qin.txt"}
    return HttpResponse(retsj)
python开发一个接口(此处以django为例),供第三方访问

 

在浏览器中访问http://172.17.37.62:8888/create_copy_task/?src=/mnt/source1/qin.txt&dst=/mnt/target1/qin.txt,返回值为:“source”和“target”

其中http://172.17.37.62:8888/create_copy_task为接口地址,src=/mnt/source1/qin.txt&dst=/mnt/target1/qin.txt为所接收到的参数,如下图所示:(图不是此处的,但类似)

python开发一个接口(此处以django为例),供第三方访问

在python中访问该接口:

python开发一个接口(此处以django为例),供第三方访问
import urllib,urllib2,cookielib

url = 'http://172.17.37.62:8888/create_copy_task/?' #定义接口地址
headers = {
   'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko'
}
headers = {'User-agent':'Mozilla/5.0'} #---OK
url_args = urllib.urlencode({  #定义参数
                            "source":'/mnt/source1/qin.txt',
                            "target":'/mnt/target1/qin.txt',
                            "copy_task":'0'}) 
print url_args #返回:source=/mnt/source1/qin.txt&...

urls = '%s%s' %(url,url_args)# 拼接URL路径
print urls #返回:http://172.17.37.62:8888/create_copy_task/?source=/mnt/source1/qin.txt&target=/mnt/target1/qin.txt&..
req = urllib2.Request(url=urls,headers=headers) #需要添加一个header,否则会提示403forbidden
print urllib2.urlopen(req).read() #返回:json格式的source和target
#urllib2.urlopen()函数不支持验证、cookie或者其它HTTP高级功能。要支持这些功能,必须使用build_opener()函数创建自定义Opener对象
python开发一个接口(此处以django为例),供第三方访问