测试开发框架django基础之response开发

引入相关包

from django.http import HttpResponse
了解HttpResponse类的初始化函数
content_type:响应正文
status:响应状态码
reason:响应状态码的解释短语
charset:响应编码格式
需求:get请求允许,post手动返回405

def hello(request):
    if request.method == "GET":
return HttpResponse("hello world user")
else:
return HttpResponse(status=405,reason="method not allow")
需求2:返回json
第一个方法:直接传字符串
def hello(request):
res =HttpResponse(status=200, content='{"code":0,"msg":"hello world"}',content_type="application/json")
return res
第二个方法:转化字符串后
def hello(request):
result = {"code":0,"msg":"hello world"}
res =HttpResponse(status=200, content=json.dumps(result),content_type="application/json")
return res
第三个方法:JsonResponse
from django.http import HttpResponse,JsonResponse
def hello(request):
res = JsonResponse(data={"code":0,"msg":"hello world"})#自动转成字符串
return res
作业:
# 开发一个接口, post请求。入参:pname--项目名称(非必填)
# 返回  对应项目的bug总数。 {"total": xxx, "name": "yyy"} 
# 如果项目名称不填,默认返回全部项目bug总数, name字段=all
source = {
    "business_autoFans_J": [14, 15, 9],
    "autoAX": [7, 32, 0],
    "autoAX_admin": [5, 13, 2],

猜你喜欢

转载自www.cnblogs.com/qd1228/p/12920364.html