python+django开发带auth接口

发布于:2025-07-07 ⋅ 阅读:(18) ⋅ 点赞:(0)

python+django开发带auth接口

# coding = utf-8
import base64
from django.contrib import auth as django_auth

from django.core.exceptions import ObjectDoesNotExist
from django.http import JsonResponse

from sign.models import Event


def user_auth(request):
    """用户认证"""
    # request.META是一个Python字典,包含了所有本次HTTP请求的Header信息,比如用户认证、IP地址和用户Agent(通常是浏览器的名称和版本号)等。
    # HTTP_AUTHORIZATION用于获取HTTP authorization。
    get_http_auth = request.META.get('HTTP_AUTHORIZATION', b'')
    # 通过split()方法将其拆分成list列表。拆分后的数据是这样的:['', '']
    auth = get_http_auth.split()
    try:
        # 取出list中的加密串,通过base64对加密串进行解码,得到的数据是元组
        auth_parts = base64.b64decode(auth[1]).decode('utf-8').partition(':')
    except IndexError:
        return 'null'
    # 取出元组中对应的用户id和密码
    userid, password = auth_parts[0], auth_parts[2]
    # 调用django的认证模块,对得到Auth信息进行认证
    user = django_auth.authenticate(username=userid, password=password)
    if user is not None and user.is_active:
        django_auth.login(request, user)
        return 'success'
    else:
        return 'fail'


def get_event_list(request):
    """示例:查询接口---增加用户认证"""
    auth_result = user_auth(request)    # 调用认证函数
    if auth_result == 'null':
        return JsonResponse({'status': 10011, 'message': 'user auth null'})

    if auth_result == 'fail':
        return JsonResponse({'status': 10012, 'message': 'user auth fail'})

    eid = request.GET.get('eid', '')
    name = request.GET.get('name', '')

    if eid == '' and name == '':
        return JsonResponse({'status': 10021, 'message': 'parameter error'})

    if eid != '':
        event = {}
        try:
            result = Event.objects.get(id=eid)
        except ObjectDoesNotExist:
            return JsonResponse({'status': 10022, 'message': 'query result is empty'})
        else:
            event['name'] = result.name
            event['limit'] = result.limit
            event['status'] = result.status
            event['address'] = result.address
            event['start_time'] = result.start_time
            return JsonResponse({'status': 200, 'message': 'success', 'data': event})

使用postman运行,结果如下:
不填写auth:
在这里插入图片描述

填写auth:
在这里插入图片描述