对Python实现简单的API接口实例讲解

yipeiwu_com6年前Python基础

get方法

代码实现

# coding:utf-8
 
import json
from urlparse import parse_qs
from wsgiref.simple_server import make_server
 
 
# 定义函数,参数是函数的两个参数,都是python本身定义的,默认就行了。
def application(environ, start_response):
 # 定义文件请求的类型和当前请求成功的code
 start_response('200 OK', [('Content-Type', 'text/html')])
 # environ是当前请求的所有数据,包括Header和URL,body,这里只涉及到get
 # 获取当前get请求的所有数据,返回是string类型
 params = parse_qs(environ['QUERY_STRING'])
 # 获取get中key为name的值
 name = params.get('name', [''])[0]
 no = params.get('no', [''])[0]
 
 # 组成一个数组,数组中只有一个字典
 dic = {'name': name, 'no': no}
 
 return [json.dumps(dic)]
 
 
if __name__ == "__main__":
 port = 5088
 httpd = make_server("0.0.0.0", port, application)
 print "serving http on port {0}...".format(str(port))
 httpd.serve_forever()

请求实例

Python API接口

post方法

代码实现

# coding:utf-8
 
import json
from wsgiref.simple_server import make_server
 
 
# 定义函数,参数是函数的两个参数,都是python本身定义的,默认就行了。
def application(environ, start_response):
 # 定义文件请求的类型和当前请求成功的code
 start_response('200 OK', [('Content-Type', 'application/json')])
 # environ是当前请求的所有数据,包括Header和URL,body
 
 request_body = environ["wsgi.input"].read(int(environ.get("CONTENT_LENGTH", 0)))
 request_body = json.loads(request_body)
 
 name = request_body["name"]
 no = request_body["no"]
 
 # input your method here
 # for instance:
 # 增删改查
 
 dic = {'myNameIs': name, 'myNoIs': no}
 
 return [json.dumps(dic)]
 
 
if __name__ == "__main__":
 port = 6088
 httpd = make_server("0.0.0.0", port, application)
 print "serving http on port {0}...".format(str(port))
 httpd.serve_forever()

请求实例

Python API接口

疑问

怎么实现请求的路径限制?

怎么限制接口调用方的headers?

以上这篇对Python实现简单的API接口实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

关于Python中Inf与Nan的判断问题详解

大家都知道 在Python 中可以用如下方式表示正负无穷: float("inf") # 正无穷 float("-inf") # 负无穷 利用 inf(infinite) 乘以 0...

全面了解python中的类,对象,方法,属性

python中一切皆为对象,所谓对象:我自己就是一个对象,我玩的电脑就是对象,坐着的椅子就是对象,家里养的小狗也是一个对象。。。。。。 我们通过描述属性(特征)和行为来描述一个对象的。比...

Ubuntu 下 vim 搭建python 环境 配置

1. 安装完整的vim # apt-get install vim-gnome 2. 安装ctags,ctags用于支持taglist,必需! # apt-get instal...

Windows系统下PhantomJS的安装和基本用法

Windows系统下PhantomJS的安装和基本用法

1.安装 下载网址:http://phantomjs.org/download.html 选择合适的版本。然后解压即可。 环境变量的配置: 进入解压的路径: 例如我是解压在D:\Py...

python openpyxl使用方法详解

openpyxl特点 openpyxl(可读写excel表)专门处理Excel2007及以上版本产生的xlsx文件,xls和xlsx之间转换容易 注意:如果文字编码是“gb2312”...