klein基本使用

2018-06-11  本文已影响0人  meetliuxin

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)
#地址和端口需要自己设置公开
上一篇下一篇

猜你喜欢

热点阅读