常見的簡易 Web server 用法:
$ cd /path/workdir
$ python -m SimpleHTTPServer
安裝 bottle (單純下載單一檔案):
$ wget --no-check-certificate http://bottlepy.org/bottle.py
撰寫相關程式碼(main.py):
from bottle import Bottle, request, response, run
import json
#import sqlite3
#conn = sqlite3.connect('/tmp/example.db')
app = Bottle()
@app.route('/test')
def test():
out = { 'status': True }
#print request.headers
response.headers['Accept-Ranges'] = 'none'
return json.dumps(out)
@app.route('/')
def rootTest():
out = { 'status': True }
out['request.url'] = request.url
out['request.urlparts'] = request.urlparts
out['request.fullpath'] = request.fullpath
out['request.query_string'] = request.query_string
out['request.script_name'] = request.script_name
out['request.content_type'] = request.content_type
out['request.is_xhr'] = request.is_xhr
out['request.is_ajax'] = request.is_ajax
out['request.auth'] = request.auth
out['request.remote_route'] = request.remote_route
out['request.remote_addr'] = request.remote_addr
response.headers['X-My-Resonse-Header'] = 'none'
return json.dumps(out)
run(app, host='127.0.0.1', port=8000)
執行:
$ python main.py
Bottle v0.12-dev server starting up (using WSGIRefServer())...
Listening on http://127.0.0.1:8000/
Hit Ctrl-C to quit.
如此就有一個包含 web server 跟簡易 APIs 可以被呼叫測試,並且不需去安裝 web server、處理 python cgi 等問題,十分方便啊。
此例執行結果:
提供 http://127.0.0.1:8000/test 位置,並回傳 {"status": true} 資料。
沒有留言:
張貼留言