2017-02-10 28 views
1

我使用Twisted-Klein作爲服務器。這裏有一個簡單的例子:Twisted-Klein服務器上的HTTP基本驗證

from klein import Klein 


app = Klein() 


@app.route('/health', methods=['GET']) 
def health_check(request): 
    return '' 


@app.route('/query/<path:expression>', methods=['GET']) 
def query(request, expression): 
    return 'Expression: {0}'.format(expression) 


if __name__ == '__main__': 
    app.run(host='0.0.0.0', port=8000) 

如何添加HTTP基本身份驗證到query API端點?有了Flask,這很簡單:http://flask.pocoo.org/snippets/8/

但我找不到任何有關如何在Twisted-Klein服務器上執行此操作的示例。

回答

2

扭曲本身有support for HTTP basic (and digest) authentication,作爲資源包裝可以應用於任何其他資源。

你的克萊恩例子並沒有證明它,但克萊因可以(必須,真的)create a resource from your app爲了使用Twisted的網絡服務器。

您可以將它們組合起來是這樣的:

import attr 
from zope.interface import implementer 
from twisted.cred.portal import IRealm 
from twisted.internet.defer import succeed 
from twisted.cred.portal import Portal 
from twisted.web.resource import IResource 
from twisted.web.guard import HTTPAuthSessionWrapper, BasicCredentialFactory 
from klein import Klein 

app = Klein() 
# ... define your klein app 

@implementer(IRealm) 
@attr.s 
class TrivialRealm(object): 
    resource = attr.ib() 

    def requestAvatar(self, avatarId, mind, *interfaces): 
     # You could have some more complicated logic here, but ... 
     return succeed((IResource, self.resource, lambda: None)) 

def resource(): 
    realm = TrivialRealm(resource=app.resource()) 
    portal = Portal(realm, [<some credentials checkers>]) 
    credentialFactory = BasicCredentialFactory(b"http auth realm") 
    return HTTPAuthSessionWrapper(portal, [credentialFactory]) 

您可以根據the klein docs for using twistd web運行此。

+0

謝謝!我會盡力實施這個明天。 –

+0

當我嘗試使用'twistd'運行服務器時,出現以下錯誤:'沒有名爲'application'的模塊。我必須創建'setup.py'文件,以及如何?如果我打開另一個關於這個問題的SO問題,可能會更好。 –

+0

你使用了什麼扭曲的命令行?有關「應用程序」的錯誤類似於您試圖使用其WSGI功能的聲音,但我鏈接的klein文檔建議使用「--class」參數,而不是WSGI。 –