1:返回操作成功的json数据

def response_success(message, data=None, data_list=[]):
return HttpResponse(json.dumps({
'code': 2000,#code由前后端配合指定
'message': message,#提示信息
'data': data,#返回单个对象
'dataList': data_list#返回对象数组
}), 'application/json')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2:返回操作失败的json数据

def response_failure(message, data=None, data_list=[]):
return HttpResponse(json.dumps({
'code': 4000,
'message': message,
'data': data,
'dataList': data_list
}), 'application/json')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

3:拦截非get请求

def get(func):
def in_fun(request):
if request.method == 'GET':
return func(request)
else:
return response_failure('not get request') return in_fun
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

4:拦截非post请求

def post(func):
def in_fun(request):
if request.method == 'POST':
return func(request)
else:
return response_failure('not post request') return in_fun
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

5:参数检查

def params(*args):#接收传入的字段
def check_params(func):
def in_fun(request):
p = []
for val in args:#遍历客户端请求是否包含字段
param = request.POST.get(val, 100)
if param == 100:#若不包含则返回错误
return response_failure('need param %s' % val)
else:
p.append(param)#若包含则传入数组返回给被装饰的函数
return func(request, p) return in_fun return check_params
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

6:md5加密

def md5(s):
m = hashlib.md5(s.encode('utf8'))
return m.hexdigest()
  • 1
  • 2
  • 3

7:保存文件

def save_file(file, save_path='photo'):
destination = open(os.path.join(save_path, file.name), 'wb+')
for chunk in destination:
destination.write(chunk)
destination.close()
  • 1
  • 2
  • 3
  • 4
  • 5

这里传入的file是request.FILES对象,save_path是图片保存路径


@get和@post使用

1:在views模板下编写测试函数(记得在urls.py文件中进行相应配置) 
2:将刚刚封装的函数所在模板引入views.py 
3:使用@get进行拦截

@get
def test(request):
return response_success('test')#返回json
  • 1
  • 2
  • 3

4:使用postman进行测试 
post请求 

get请求 

@post的用法如上

@params,response_success,response_failure使用

@post
@params('account', 'password')
def login(request, args):
user = BUser.objects.filter(account=args[0], password=md5(args[1]))
if len(user) == 0:
return response_failure('account or password error')
u = model_to_dict(user[0])
u['password'] = ''
request.session[config.LOGIN] = config.TAG_LOGIN
return response_success('login success', u)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

1:@params中传入你所需的字段 
2:args是一个list,list里面的数据按字段顺序排列 
3:如上面的例子args[0]为account字段的值args[1]是password字段的值 
4:从数据库查询出来的结果要用model_to_dict方法才能返回json格式字符串

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_35055467/article/details/77450117

基于django封装的常用装饰器和函数的更多相关文章

  1. django类视图的装饰器验证

    django类视图的装饰器验证 django类视图的get和post方法是由View内部调用dispatch方法来分发,最后调用as_view来完成一个视图的流程. 函数视图可以直接使用对应的装饰器 ...

  2. 给django视图类添加装饰器

    要将login_required装饰到view class的dispatch方法上, 因为dispatch方法为类方法,不是单个的函数,所以需要将装饰函数的装饰器 login_required转化为装 ...

  3. 面向对象(三)——组合、多态、封装、property装饰器

    组合.多态.封装.property装饰器 一.组合 1.什么是组合 组合指的是某一个对象拥有一个属性,该属性的值是另外一个类的对象 class Foo(): pass class Bar(): pas ...

  4. 基于linux信号的timeout装饰器

    在做基于ray的分布式任务处理时,偶尔遇到由于ray集群不稳定导致的长时间连接不上,进而导致程序卡死,无法向后端返回任务状态的情况.但是ray的初始化函数本身未实现超时机制,因此设计基于多线程+信号的 ...

  5. Day11 Python基础之装饰器(高级函数)(九)

    在python中,装饰器.生成器和迭代器是特别重要的高级函数   https://www.cnblogs.com/yuanchenqi/articles/5830025.html 装饰器 1.如果说装 ...

  6. python通过装饰器检查函数参数的数据类型的代码

    把内容过程中比较常用的一些内容记录起来,下面内容段是关于python通过装饰器检查函数参数的数据类型的内容. def check_accepts(f): assert len(types) == f. ...

  7. python:带参数的装饰器,函数的有用信息

    一.带参数的装饰器,函数的有用信息 def func1(): '''此函数的功能是完成的登陆的功能 return: 返回值是登陆成功与否(true,false) ''' print(333) func ...

  8. 关于Python装饰器内层函数为什么要return目标函数的一些个人见解

    https://blog.csdn.net/try_test_python/article/details/80802199 前几天在学装饰器的时候,关于装饰器内层函数调用目标函数时是否return目 ...

  9. diango中让装了装饰器的函数的名字不是inner,而是原来的名字

    让装了装饰器的函数的名字不是inner,而是原来的名字 from functools import wraps def wrapper(func): @wraps(func) # 复制了原来函数的名字 ...

随机推荐

  1. 开发ActiveX控件调用另一个ActiveX系列3——ActiveX调用另一个ActiveX

    终于进入正题了,怎样在ActiveX中调用另一个ActiveX.我们的项目需要调用华视电子身份证识别仪的ActiveX控件 在这里有很多识别仪ActiveX插件下载:http://www.idukaq ...

  2. 【TensorFlow-windows】(六) CNN之Alex-net的测试

    主要内容: 1.CNN之Alex-net的测试 2.该实现中的函数总结 平台: 1.windows 10 64位 2.Anaconda3-4.2.0-Windows-x86_64.exe (当时TF还 ...

  3. python使用模板手记

    1.首先是$符号 在webpy中,模板html里面可以写python代码,但要用$开始.但如果网页代码本来就有$符号(javascript或者正则表达式),我们需要对其进行转意.用$$代替$ 给jqu ...

  4. python opener代理

    链接:http://www.jb51.net/article/46495.htm https://www.cnblogs.com/cunyusup/p/7341829.html

  5. UITextView的一些技巧

      1.在指定位置插入字符串:   NSMutableString *TextViewStr=[[NSMutableString alloc] initWithString:TextView.text ...

  6. __str__ 和 __unicode__ 的区别和用法

    转自:https://www.cnblogs.com/painberg/p/8514860.html 简而言之,就是__str__和__unicode__都是为了再管理站点中加载这个表时想显示什么属性 ...

  7. animate和scrollTop的使用

    // 平滑滚动到ola结果位置 var scrollHeight = $("#wrap_div")[0].scrollHeight; var curDivHeight = $(&q ...

  8. Django创建模型_模型层

    1.在项目Mysite下创建应用bms 2.在bms下的models.py文件中创建模型 from django.db import models # Create your models here. ...

  9. (图解)Description Resource Path Location Type Java compiler level does not match the version of

    Description Resource Path Location Type Java compiler level does not match the version of project 编译 ...

  10. ABAP upload file(*.txt *.csv *.xls)

    转自:http://blog.csdn.net/jy00873757/article/details/8534492 在SAP我们经常会用到*.txt, *.csv, *.xls三种文件格式 *.TX ...