我正在使用Twisted-Klein
作为服务器。这是一个简单的示例:
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 Basic Auth添加到
query
API端点?使用Flask,这很简单:http://flask.pocoo.org/snippets/8/但是我找不到在Twisted-Klein服务器上如何执行此操作的任何示例。
最佳答案
Twisted本身具有support for HTTP basic (and digest) authentication,可作为可应用于任何其他资源的资源包装器。
您的klein示例并未进行演示,但是klein可以(必须,实际上)可以create a resource from your app以便使用Twisted的Web服务器。
您可以将它们组合为:
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
运行它。