Python編寫API介面

2022-06-15 07:36:08 字數 1442 閱讀 6843

要求通過進行訪問,引數a="aa",b="bb",c="00"

1.編寫url:瀏覽器會自動將?後面識別為引數。

urlpatterns =[

url(r

'^calc/$

', aptest.calc, name='

calc'),

]

2.編寫view:

瀏覽器返回json型別結果:

import

json

defcalc(request):

a = request.get['a'

] b = request.get['b'

] c = request.get['c'

]

print

a,b,c

m = a+b+c

n = b+a

rets =

retsj = json.dumps(rets) #

返回json型別資料

在瀏覽器中訪問,返回值為:「aabb00」

在python中訪問該介面:

import

urllib,urllib2,cookielib

url = '

' #定義介面位址

headers =

headers = #---ok

url_args =urllib.urlencode()

print url_args #

返回:a=aa&c=00&b=bb

urls = '

%s%s

' %(url,url_args)

print urls #

返回:req = urllib2.request(url=urls,headers=headers) #

需要新增乙個header,否則會提示403forbidden

print urllib2.urlopen(req).read() #

返回:aabb00

#urllib2.urlopen()函式不支援驗證、cookie或者其它http高階功能。要支援這些功能,必須使用build_opener()函式建立自定義opener物件

python編寫api原則 編寫api需要一些建議

聽起來好像您已經在python方法中定義了所有api功能,因此您可以使用pythonweb服務框架來直接或通過簡單的包裝器服務類公開它們。我建議你看看關於web services at python.org的wiki頁面。在 如果您想使用json作為web服務的傳輸協議,我建議您使用json rpc...

python通過flask編寫API

pip install json pip install flask import flask,json from flask import request flask seb框架,通過flask提供的裝飾器 server.route 將普通函式轉換為服務 登入介面,需要傳入url,username...

python 封裝API介面

1.對一天中通話,按時段進行分析 輸入資料為.txt檔案,資料部分展示如下 u110107 02169228380 530005 20190228125930 61aa.u110107 18895672550 530005 20190228165337 ffffe06f.u110107 188956...