Python中的授权REST服务
我现在正在设计阶段,也在考虑是否选择Python作为主要编程语言来开发软件。我的任务是:
- 实现一组RESTful网络服务
- 对某些用户组授权HTTP方法,为此需要使用XACML来定义政策(或者可以用其他标准),还需要用SAML来进行信息交换
3 个回答
我同意Constantinius的看法,BaseHTTPServer
是用Python做RESTful服务的一个很不错的选择。它在Python 2.7中是自带的,比起gunicorn、flask、wsgi和gevent等其他工具,扩展性更好。而且它支持数据流,这在将来可能会用到。
下面是一个例子,展示了一个网页浏览器如何向BaseHTTPServer发起远程的POST请求,并获取数据。
JavaScript代码(放在static/hello.html中,通过Python提供服务):
<html><head><meta charset="utf-8"/></head><body>
Hello.
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "/postman", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
value: 'value'
}));
xhr.onload = function() {
console.log("HELLO")
console.log(this.responseText);
var data = JSON.parse(this.responseText);
console.log(data);
}
</script></body></html>
Python服务器(用于测试):
import time, threading, socket, SocketServer, BaseHTTPServer
import os, traceback, sys, json
log_lock = threading.Lock()
log_next_thread_id = 0
# Local log functiondef
def Log(module, msg):
with log_lock:
thread = threading.current_thread().__name__
msg = "%s %s: %s" % (module, thread, msg)
sys.stderr.write(msg + '\n')
def Log_Traceback():
t = traceback.format_exc().strip('\n').split('\n')
if ', in ' in t[-3]:
t[-3] = t[-3].replace(', in','\n***\n*** In') + '(...):'
t[-2] += '\n***'
err = '\n*** '.join(t[-3:]).replace('"','').replace(' File ', '')
err = err.replace(', line',':')
Log("Traceback", '\n'.join(t[:-3]) + '\n\n\n***\n*** ' + err + '\n***\n\n')
os._exit(4)
def Set_Thread_Label(s):
global log_next_thread_id
with log_lock:
threading.current_thread().__name__ = "%d%s" \
% (log_next_thread_id, s)
log_next_thread_id += 1
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
Set_Thread_Label(self.path + "[get]")
try:
Log("HTTP", "PATH='%s'" % self.path)
with open('static' + self.path) as f:
data = f.read()
Log("Static", "DATA='%s'" % data)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(data)
except:
Log_Traceback()
def do_POST(self):
Set_Thread_Label(self.path + "[post]")
try:
length = int(self.headers.getheader('content-length'))
req = self.rfile.read(length)
Log("HTTP", "PATH='%s'" % self.path)
Log("URL", "request data = %s" % req)
req = json.loads(req)
response = {'req': req}
response = json.dumps(response)
Log("URL", "response data = %s" % response)
self.send_response(200)
self.send_header("Content-type", "application/json")
self.send_header("content-length", str(len(response)))
self.end_headers()
self.wfile.write(response)
except:
Log_Traceback()
# Create ONE socket.
addr = ('', 8000)
sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(addr)
sock.listen(5)
# Launch 10 listener threads.
class Thread(threading.Thread):
def __init__(self, i):
threading.Thread.__init__(self)
self.i = i
self.daemon = True
self.start()
def run(self):
httpd = BaseHTTPServer.HTTPServer(addr, Handler, False)
# Prevent the HTTP server from re-binding every handler.
# https://stackoverflow.com/questions/46210672/
httpd.socket = sock
httpd.server_bind = self.server_close = lambda self: None
httpd.serve_forever()
[Thread(i) for i in range(10)]
time.sleep(9e9)
控制台日志(Chrome浏览器):
HELLO
hello.html:14 {"req": {"value": "value"}}
hello.html:16
{req: {…}}
req
:
{value: "value"}
__proto__
:
Object
控制台日志(Firefox浏览器):
GET
http://XXXXX:8000/hello.html [HTTP/1.0 200 OK 0ms]
POST
XHR
http://XXXXX:8000/postman [HTTP/1.0 200 OK 0ms]
HELLO hello.html:13:3
{"req": {"value": "value"}} hello.html:14:3
Object { req: Object }
控制台日志(Edge浏览器):
HTML1300: Navigation occurred.
hello.html
HTML1527: DOCTYPE expected. Consider adding a valid HTML5 doctype: "<!DOCTYPE html>".
hello.html (1,1)
Current window: XXXXX/hello.html
HELLO
hello.html (13,3)
{"req": {"value": "value"}}
hello.html (14,3)
[object Object]
hello.html (16,3)
{
[functions]: ,
__proto__: { },
req: {
[functions]: ,
__proto__: { },
value: "value"
}
}
Python日志:
HTTP 8/postman[post]: PATH='/postman'
URL 8/postman[post]: request data = {"value":"value"}
URL 8/postman[post]: response data = {"req": {"value": "value"}}
另外,你可以通过在将socket传给BaseHTTPServer之前给它加上SSL,来轻松实现安全连接。
使用Python时,你需要创建一个XACML请求,这个请求里要包含用户的ID(这个ID通常是在用户登录后获取的),还要添加一些关于用户要访问的网络服务的信息。比如说,这可以是服务的URI(统一资源标识符),也可以是HTTP方法等等……
最后你可能会得到类似这样的内容:
<?xml version="1.0" encoding="UTF-8"?><xacml-ctx:Request xmlns:xacml-ctx="urn:oasis:names:tc:xacml:2.0:context:schema:os">
<xacml-ctx:Subject SubjectCategory="urn:oasis:names:tc:xacml:1.0:subject-category:access-subject">
<xacml-ctx:Attribute AttributeId="urn:oasis:names:tc:xacml:1.0:subject:subject-id" DataType="http://www.w3.org/2001/XMLSchema#string">
<xacml-ctx:AttributeValue>Alice</xacml-ctx:AttributeValue>
</xacml-ctx:Attribute>
</xacml-ctx:Subject>
<xacml-ctx:Resource>
<xacml-ctx:Attribute AttributeId="urn:oasis:names:tc:xacml:1.0:resource:resource-id" DataType="http://www.w3.org/2001/XMLSchema#string">
<xacml-ctx:AttributeValue>/someuri/myapi/target.py</xacml-ctx:AttributeValue>
</xacml-ctx:Attribute>
</xacml-ctx:Resource>
<xacml-ctx:Action>
<xacml-ctx:Attribute AttributeId="urn:oasis:names:tc:xacml:1.0:action:action-id" DataType="http://www.w3.org/2001/XMLSchema#string">
<xacml-ctx:AttributeValue>GET</xacml-ctx:AttributeValue>
</xacml-ctx:Attribute>
</xacml-ctx:Action>
<xacml-ctx:Environment>
</xacml-ctx:Environment>
</xacml-ctx:Request>
你需要用Python和lxml库来构建这个请求。
返回的结果看起来会像这样:
<xacml-ctx:Response xmlns:xacml-ctx="urn:oasis:names:tc:xacml:2.0:context:schema:os">
<xacml-ctx:Result>
<xacml-ctx:Decision>Permit</xacml-ctx:Decision>
<xacml-ctx:Status>
<xacml-ctx:StatusCode Value="urn:oasis:names:tc:xacml:1.0:status:ok"/>
</xacml-ctx:Status>
</xacml-ctx:Result>
</xacml-ctx:Response>
所以你还需要解析这个XML,以提取出决策结果,比如说“允许”(Permit)。我写了一个简单的REST风格的接口,连接到一个XACML的PDP(政策决策点),你只需要发送一个HTTP GET请求到一个URI,并把变量作为GET参数传递,比如说 http://www.xacml.eu/AuthZ/?a=alice&b=/someuri/myapi/target.py&c=GET
这样解释清楚了吗?
如果你在问可以用哪些库来实现这些RESTful服务,那你可以看看标准Python库中的BaseHTTPServer模块。
下面的代码展示了实现一个简单的服务器来接受GET请求是多么简单:
class MyHandler(BaseHTTPRequestHandler):
def do_GET(self):
try:
f = open(curdir + sep + self.path) #self.path has /test.html
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(f.read())
f.close()
except IOError:
self.send_error(404,'File Not Found: %s' % self.path)
def main():
try:
server = HTTPServer(('', 80), MyHandler)
print 'Welcome to the machine...'
server.serve_forever()
except KeyboardInterrupt:
print '^C received, shutting down server'
server.socket.close()
if __name__ == '__main__':
main()
当然,这段代码不是我写的,我是在这里找到的。