1. 程式人生 > >簡單的api實現以及動態函式呼叫

簡單的api實現以及動態函式呼叫

實現一個簡單的api功能,環境python2.7

  1. 請求方法:curl http://ip:8000/?name={api中的方法名}|python -m json.tool
  2. 只需編寫api的方法即可
#!/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()