Restful Web服务Python和客户端基本身份验证的简单示例

时间:2015-05-18 19:33:17

标签: python web-services tornado restful-authentication

出于学习目的,我想知道是否有一个简单的虚拟示例,说明如何使用python进行基本身份验证的http请求。 我想从我发现和改编的例子中遵循相同的模式,如下:

'''webservice.py'''
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.auth
from tornado.web import HTTPError

from tornado.escape import json_encode as dumps
from tornado.escape import json_decode as loads

import db
import settings

class MainHandler(tornado.web.RequestHandler):
    """Main Handler... list all databases"""

    def get(self):
        self.write(dumps(db.list_databases()))

application = tornado.web.Application([
    (r"/", MainHandler),
],
    cookie_secret='PUT_SOME_CODE',
)

if __name__ == "__main__":
    http_server = tornado.httpserver.HTTPServer(application)
    http_server.listen(settings.port)
    tornado.ioloop.IOLoop.instance().start()

达到http://localhost:8888/时会显示数据库列表,这是脚本的用途。这可以通过浏览器和测试器脚本访问,如:

'''tester.py'''
from tornado.httpclient import HTTPClient
from tornado.escape import json_decode as loads

url='http://localhost:8888/'

http_client=HTTPClient()
response=http_client.fetch(url)
listResponse=loads(response.body)


print(listResponse)

http_client.close()

1 个答案:

答案 0 :(得分:0)

这是最简单的基本身份验证示例。当然,它可以通过多种方式进行改进,它只是演示它通常如何运作。

import httplib


class MainHandler(tornado.web.RequestHandler):
    """Main Handler... list all databases"""

    def get(self):
        self.check_basic_auth()
        do_stuff()

    def check_basic_auth(self):
        if not self.test_auth_credentials():
            raise HTTPError(httplib.UNAUTHORIZED, 
                            headers={'WWW-Authenticate': 'Basic realm="Auth realm"'})

    def test_auth_credentials(self):
        auth_header = self.request.headers.get('Authorization')

        if auth_header and auth_header.startswith('Basic '):
            method, auth_b64 = auth_header.split(' ')
            try:
                decoded_value = auth_b64.decode('base64')
            except ValueError:
                return False
            given_login, _, given_passwd = decoded_value.partition(':')
            return <YOUR_LOGIN> == given_login and <YOUR_PASSWORD> == given_passwd
        return False