接口
一.编程语言里面的接口
1.Interface
接口在编程语言中指的是一个抽象类型,是抽象方法的集合;
它的特点如下:
-
接口包含类要实现的方法,但是接口自己无法被实例化
-
接口里的定义函数没有过程,且必须被继承的子类重写
-
类通过继承接口的方式,来继承接口的抽象方法;
-
类描述对象的属性和方法(实现接口的类,必须实现接口内所描述的所有方法,否则必须声明为抽象类);
总结:接口只定义规范,不负责具体实现(具体实现由具体的实现者完成)!
相当于一个接口有很多方法,这些方法都在这个接口里面被定义,但是这些方法的实现方式是另外的
2.Python中的Interface
python中的接口概念是借助第三方库来实现的,一般是Zope.interface
pip install zope.interface
- demo
from zope.interface import Interface
from zope.interface.declarations import implementer
# 定义接口
class IHost(Interface):
def goodmorning(self,host):
"""Say good morning to host"""
#继承接口
@implementer(IHost)
class Host:
def goodmorning(self, guest):
"""Say good morning to guest"""
return "Good morning, %s!" % guest
if __name__ == '__main__':
p = Host()
hi = p.goodmorning('Tom')
print(hi)
二.开发系统的Web 接口
1.发布会添加接口
from django.http import JsonResponse
from blog.models import Event
from django.core.exceptions import ValidationError
# 添加发布会接口
def add_event(request):
#接口入参
eid = request.POST.get('eid', '') # 发布会id
name = request.POST.get('name', '') # 发布会标题
limit = request.POST.get('limit', '') # 限制人数
status = request.POST.get('status', '') # 状态
address = request.POST.get('address', '') # 地址
start_time = request.POST.get('start_time', '') # 发布会时间
# 参数为空校验
if eid == ''or name == ''or limit == ''or status == ''or address == '' or start_time == '':
return JsonResponse({'status': 10021, 'message': 'parameter error'})
# id存在校验
result = Event.objects.filter(id=eid)
if result:
return JsonResponse({'status': 10022, 'message': 'event id already exists'})
#name存在校验
result = Event.objects.filter(name=name)
if result:
return JsonResponse({'status': 10023, 'message': 'event