简体   繁体   English

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

[英]Simple example of restful web service Python and client basic authentication

For study purposes I'd like to know if there is a simple dummy example of how to handle a http request with basic authentication using python. 出于研究目的,我想知道是否有一个简单的虚拟示例,说明如何使用python处理带有基本身份验证的http请求。 I'd like to follow the same pattern from a example I've found and adapted, as follows: 我想从我发现并改编的示例中遵循相同的模式,如下所示:

'''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()

A list of databases appears when reach http://localhost:8888/ , which is the purpose of the script. 到达http:// localhost:8888 /时 ,将显示数据库列表,这是脚本的目的。 This can be accessed by browser and a tester script like: 可以通过浏览器和测试器脚本(例如:

'''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()

Here is simplest basic-auth example. 这是最简单的basic-auth示例。 Of course, it can be improved in many ways, it is just a demonstration how it usually works. 当然,可以通过许多方式对其进行改进,这只是它通常如何工作的演示。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM