Pythonの小さなWebサービスweb.pyの簡単なチュートリアル
Python Small Web Service Web
最近、Javaを介してPythonサービスを呼び出す必要があるプロジェクトがあります。優れたフレームワークであり、通信効率の高いgRPCを検討しました。しかし、十分に良いという原則に基づいて、単純なHTTP通信方法、サーバーを確立するためのPython、JSON APIの公開、JavaがAPIを介してPythonサービスを呼び出すことを選択しました。以下は、web.pyの簡単なチュートリアルです。
web.py
Web.pyは、シンプルで強力なPythonWebフレームワークです。
web.pyをインストールします
pip install web.py
デモコード
次のコード実装の機能は、呼び出しますhttp://localhost:8080/upper/TEXT
TEXTに対応する大文字を返します。 transfer http://localhost:8080/lower/TEXT
TEXTに対応する小文字を返します。
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テンプレート
APIに加えて、HTMLも一般的に使用されていますtemplates
hello.html
documentというフォルダーの下に名前を作成します。
$def with (content) Recognition result: $content
hello.html
名前は非常に重要であり、次のrender.hello
対応しています$content
渡されたパラメーターの名前です。
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などの静的リソースへの参照。
in images
カタログの下にシートを置きますimage.jpg
の写真
HTMLを変更する
$def with (content) Recognition result: $content
Pythonコードを変更します。次の追加コードは、include js
、css
、images
パスのリクエストが静的リソースを返すことを意味しますが、通常は推奨されますnginx
静的リソースを実現するため。
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, 'r') return f.read() except: return '' if __name__ == '__main__': app.run()
テスト
http:// localhost / upper_html / Wiki
プロジェクトの構造
├── images │ └── image.jpg ├── templates │ └── hello.html ├── web_demo.py