Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.3k views
in Technique[技术] by (71.8m points)

Django View层公共类调用的问题?

目标:
我依据项目规范封装了一个HTTP返回类,在每个函数返回时,调用返回类response返回相应的内容。
问题:
Django每次请求并不会重新实例化我的返回类,这导致多次请求有时会返回相同的内容。然而我为类的一些属性设置了默认值,在不改变默认值的情况下,返回应当是默认值才对。

代码:
Response类(代码非真实代码,逻辑大体相同,请勿吐槽此类的作用)

from django.http import JsonResponse
class ApiResponse:
    def __init__(self):
        self.status_code = 200

    def set_status_code(self, status_code):
        self.status_code = status_code

    def get_status_code(self):
        return self.status_code

    def __error(message="Internal Error"):
        return JsonResponse({"status": "error", "message": message, "status_code":self.get_status_code()})

    def fail(self, message):
        self.set_status_code(400)
        return self.__error(message)

    def success(self, message):
        return JsonResponse({"status": "ok", "message": message})

View层:

from api_response.api_response import ApiResponse

response = ApiResponse()

def login(request):
    if request.method == "POST"
    #code....
        return response.success("登录成功")
    else:
        return response.fail("不支持的方法")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

全局变量对于单进程http服务器来说只实例化一次没毛病.你放到login里面就好了

from api_response.api_response import ApiResponse

def login(request):
    response = ApiResponse()
    if request.method == "POST"
    #code....
        return response.success("登录成功")
    else:
        return response.fail("不支持的方法")

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...