zoukankan      html  css  js  c++  java
  • Django请求参数小驼峰和下划线转换的中间件

    小驼峰和下划线转换函数

    # coding:utf-8
    import re


    def hump2underline(hunp_str):
    p = re.compile(r'([a-z]|d)([A-Z])')
    sub = re.sub(p, r'1_2', hunp_str).lower()
    return sub


    def underline2hump(underline_str):
    sub = re.sub(r'(_w)', lambda x: x.group(1)[1].upper(), underline_str)
    return sub


    def underline_dict(params):
    new_params = params
    if isinstance(params, dict):
    new_params = {}
    for k, v in params.items():
    new_params[hump2underline(k)] = underline_dict(params[k])
    elif isinstance(params, list):
    new_params = []
    for param in params:
    new_params.append(underline_dict(param))
    return new_params


    def camel_dict(params):
    new_params = params
    if isinstance(params, dict):
    new_params = {}
    for k, v in params.items():
    new_params[underline2hump(k)] = camel_dict(params[k])
    elif isinstance(params, list):
    new_params = []
    for param in params:
    new_params.append(camel_dict(param))
    return new_params


    中间件

    from django.utils.deprecation import MiddlewareMixin
    import json

    from utils import format_conversion


    class FormatMiddleware(MiddlewareMixin):
    def process_request(self, request):
    if request.method == "GET":
    request_data = format_conversion.underline_dict(request.GET)
    request.GET = request_data
    elif request.method == "POST" or request.method == "DELETE":
    req_body = json.loads(request.body.decode('utf-8'))
    request_data = format_conversion.underline_dict(req_body)
    request._body = json.dumps(request_data).encode('utf-8')
    return None

    def process_response(self, request, response):
    if response.status_code == 200:
    try:
    response_data = format_conversion.camel_dict(response.data.get('result'))
    response.data['result'] = response_data
    response._is_rendered = False
    response.render()
    except Exception as e:
    print(e)
    return response
  • 相关阅读:
    Java实现 LeetCode 640 求解方程(计算器的加减法计算)
    PHP zip_entry_compressedsize() 函数
    PHP zip_entry_close() 函数
    PHP zip_close() 函数
    PHP xml_set_unparsed_entity_decl_handler() 函数
    PHP xml_set_processing_instruction_handler() 函数
    格列隙 | grid-row-gap (Grid Layout)
    格列隙 | grid-column-gap (Grid Layout)
    格列端 | grid-column-end (Grid Layout)
    格列开始 | grid-column-start (Grid Layout)
  • 原文地址:https://www.cnblogs.com/ykugb/p/11870977.html
Copyright © 2011-2022 走看看