简单的api实现以及动态函数调用

实现一个简单的api功能,环境python2.7

  1. 请求方法:curl http://ip:8000/?name={api中的方法名}|python -m json.tool
  2. 只需编写api的方法即可
  3. 详情参考官方文档:https://www.python.org/dev/peps/pep-0333/
#!/usr/bin/env python
#coding:utf-8
import json
import api
from wsgiref.util import setup_testing_defaults
from wsgiref.simple_server import make_server

def simple_app(environ, start_response):
    setup_testing_defaults(environ)

    status = '200 OK'
    headers = [('Content-type', 'text/plain;charset=UTF-8')]

    start_response(status, headers)
    
    params = parse_qs(environ['QUERY_STRING'])
    name = params.get('name')[0]
    #判断api中是否有name的方法,有就调用并返回
    if hasattr('api',name):
          dic = eval('api.'+name)()
    else:
          dic = {'resdec':'No method %s'%(name)}
    return [json.dumps(dic)]        
if __name__ == '__main__':
    httpd = make_server('', 8000, simple_app)
    print "Serving on port 8000..."
    httpd.serve_forever()

 来自官网 《PEP 333 -- Python Web Server Gateway Interface v1.0》的忠告,这个接口就是玩玩,不要作为生产使用!!

Note: although we refer to it as an "application" object, this should not be construed to mean that application developers will use WSGI as a web programming API! It is assumed that application developers will continue to use existing, high-level framework services to develop their applications. WSGI is a tool for framework and server developers, and is not intended to directly support application developers.

原文地址:https://www.cnblogs.com/chbo/p/10172964.html