我使用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服务器上执行此操作的示例。
答案 0 :(得分:2)
Twisted本身有support for HTTP basic (and digest) authentication,作为资源包装计算,可以应用于任何其他资源。
你的klein示例没有展示它,但klein可以(必须,真的)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
运行此内容。