最近有個項目需要通過Java調(diào)用Python的服務(wù),有考慮過gRPC,那是一個很好的框架,通信效率高。但是基于夠用就好的原則,決定選擇使用簡單的HTTP通信方式,Python建立服務(wù)器,公開JSON API,Java通過API方式調(diào)用Python的服務(wù),下面是web.py的簡單使用教程。
web.py
web.py 是一個Python 的web 框架,它簡單而且功能強(qiáng)大。
安裝web.py
pip install web.py
Demo代碼
下面的代碼實現(xiàn)的功能是,調(diào)用http://localhost:8080/upper/TEXT,返回TEXT對應(yīng)的大寫。調(diào)用http://localhost:8080/lower/TEXT,返回TEXT對應(yīng)的小寫。
import web
urls = (
'/upper/(.*)', 'upper',
'/lower/(.*)', 'lower'
)
app = web.application(urls, globals())
class upper:
def GET(self, text):
print('input:' + text)
return text.upper()
class lower:
def GET(self, text):
print('input:' + text)
return text.lower()
if __name__ == "__main__":
app.run()
測試
http://localhost:8080/upper/Wiki
http://localhost:8080/lower/Wiki
HTML模板
我們開發(fā)除了API外,HTML也是常用,在templates文件夾下創(chuàng)建一個名稱叫做hello.html的文件。
$def with (content)
<html>
<body>
<p>識別結(jié)果:$content</p>
</body>
</html>
hello.html的名稱很重要,和下面的render.hello是對應(yīng)的,$content是傳入的參數(shù)名稱。
import web
urls = (
'/upper_html/(.*)', 'upper_html'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class upper_html:
def GET(self, text):
print('input:' + text)
return render.hello(content=text.upper())
if __name__ == "__main__":
app.run()
測試
http://localhost/upper_html/Wiki
圖片、js、css等靜態(tài)資源的引用
在images目錄下放一張image.jpg的圖片
修改HTML
$def with (content)
<html>
<body>
<p>識別結(jié)果:$content</p>
<img src="/images/image.jpg" width="400">
</body>
</html>
修改python代碼,下面增加的代碼的意思是,把包含js、css、images路徑的請求,返回靜態(tài)資源,但是通常建議使用nginx來實現(xiàn)靜態(tài)資源。
import web
urls = (
'/upper_html/(.*)', 'upper_html',
'/(js|css|images)/(.*)', 'static'
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class upper_html:
def GET(self, text):
print('input:' + text)
return render.hello(content=text.upper())
class static:
def GET(self, media, file):
try:
f = open(media+'/'+file, 'rb')
return f.read()
except:
return ''
if __name__ == "__main__":
app.run()
測試
http://localhost/upper_html/Wiki
項目結(jié)構(gòu)
├── images
│ └── image.jpg
├── templates
│ └── hello.html
├── web_demo.py