TwistedKlein上的HTTP基本身份验证

2024-06-16 11:52:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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)

如何向queryAPI端点添加HTTP基本身份验证?对于烧瓶,这很简单:http://flask.pocoo.org/snippets/8/

但我找不到任何关于如何在Twisted Klein服务器上做到这一点的例子。在


Tags: from服务器appgetreturnrequestdeftwisted
1条回答
网友
1楼 · 发布于 2024-06-16 11:52:38

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 ^{}运行此程序。在

相关问题 更多 >