klein文檔
klein是一個小型的web框架,在服務器運行爬蟲腳本的時候,可能沒辦法監測爬蟲狀態,使用Klein可以使我們隨時打開瀏覽器查看想要監控的東西。
1.安裝
pip install klein
2.使用
2.1基本使用
from klein import run, route
@route('/')
def home(request):
return 'Hello, world!'
run("localhost", 8080)
它在端口8080上啟動一個Twisted Web服務器,偵聽回環地址。打開網頁localhost:8080看看
通過創建Klein實例,然后調用run和route方法,就可以使路由變得不全局。
from klein import Klein
app = Klein()
@app.route('/')
def home(request):
return 'Hello, world!'
app.run("localhost", 8080)
2.2設置多個路由
from klein import Klein
app = Klein()
@app.route('/')
def pg_root(request):
return 'I am the root page!'
@app.route('/about')
def pg_about(request):
return 'I am a Klein application!'
app.run("localhost", 8080)
分別打開瀏覽器訪問:localhost:8080和localhost:8080/about
2.3可變路由
這將為你的函數提供額外的參數,這些參數與你指定的路由的部分相匹配。通過使用它,可以實現依賴于此更改的頁面,例如:通過在站點上顯示用戶或在存儲庫中顯示文檔。
from klein import Klein
app = Klein()
@app.route('/user/<username>')
def pg_user(request, username):
return 'Hi %s!' % (username,)
app.run("localhost", 8080)
訪問http://localhost:8080/user/bob,你應該Hi bob!
還可以定義它應該匹配的類型。三種可用類型是string,int和float
from klein import Klein
app = Klein()
@app.route('/<string:arg>')
def pg_string(request, arg):
return 'String: %s!' % (arg,)
@app.route('/<float:arg>')
def pg_float(request, arg):
return 'Float: %s!' % (arg,)
@app.route('/<int:arg>')
def pg_int(request, arg):
return 'Int: %s!' % (arg,)
app.run("localhost", 8080)
訪問http://localhost:8080/somestring,它將被路由到pg_string方法
http://localhost:8080/1.0將被pg_float
http://localhost:8080/1將被pg_int.
3.遇到的應用
爬蟲運行在服務器中,爬取的結果存在MongoDB中,MongoDB中的數據需要對傳給客戶并更改字段信息。剛存在MongoDB中的數據is_upload字段默認為false,對傳成功后改為true。Klein可以返回給我們MongoDB中數據的統計信息
@route('/getstats')
def home(request):
client = pymongo.MongoClient(MONGO_URI)
db = client[MONGO_DATABASE]
collection = db[MONGO_COLLECTION]
response = []
for stat in collection.aggregate([{'$group':{'_id':'$is_upload','num':{'$sum':1}}},
{'$project':{'is_upload':'$_id', 'num':1, '_id':0}}]):
response.append(stat)
client.close()
return json.dumps(response)
run("0.0.0.0", 5028)
#地址和端口需要自己設置公開