python接口自动化(2)——Django开发post接口、get接口

1、Django开发post接口

在templates文件下创建一个html文件,在views文件下处理

在提交表单时,报错:CSRF verification failed. Request aborted.

解决:注释掉settings文件下MIDDLEWARE里的'django.middleware.csrf.CsrfViewMiddleware'

序列化处理,让返回的数据为json

2、Django开发get接口

多个参数时,序列化处理,让返回的数据为json

3、代码部分

urls.py

from django.contrib import admin
from django.urls import path
from api.views import Login

urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/', Login)
]

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>login</title>
</head>
<body>
<form action="/login/" method="POST">
    <h1>用户名:<input name="username"></h1>
    <h1>密码:<input name="password"></h1>
    <input type="submit" value="登录">
</form>

</body>
</html>

views.py

import json

from django.http.response import HttpResponse
from django.shortcuts import render



# post接口请求
def Login1(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        return HttpResponse(username)
    else:
        return render(request, 'login.html')


def Login(request):
    if request.method == 'POST':
        result = {}
        username = request.POST.get('username')
        password = request.POST.get('password')
        result['user'] = username
        result['passwords'] = password
        result = json.dumps(result)
        return HttpResponse(result, content_type='application/json', charset='utf-8')
    else:
        return render(request, 'login.html')


# get接口请求
def Login2(request):
    if request.method == 'GET':
        result = {}
        username = request.GET.get('username')
        phone = request.GET.get('phone')
        data = request.GET.get('data')
        result['user'] = username
        result['phoneNum'] = phone
        result['data'] = data
        result = json.dumps(result)
        return HttpResponse(result, content_type='application/json', charset='utf-8')
    else:
        return render(request, 'login.html')

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Django 项目中,可以使用第三方库 `django-rest-swagger` 自动生成接口文档。 以下是具体的步骤: 1. 安装 `django-rest-swagger` ```bash pip install django-rest-swagger ``` 2. 将 `rest_framework` 和 `rest_framework_swagger` 添加到 Django 项目的 `INSTALLED_APPS` 中: ```python INSTALLED_APPS = [ # ... 'rest_framework', 'rest_framework_swagger', # ... ] ``` 3. 在 Django 项目的 `urls.py` 中添加 Swagger API URL: ```python from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='API 文档') urlpatterns = [ # ... url(r'^api-docs/$', schema_view), # ... ] ``` 4. 在需要生成文档的 API 视图中添加 `swagger_auto_schema` 装饰器: ```python from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from rest_framework_swagger import swagger_auto_schema @api_view(['GET']) @swagger_auto_schema( operation_description='获取用户信息', responses={ status.HTTP_200_OK: '返回用户信息', status.HTTP_404_NOT_FOUND: '用户不存在' } ) def get_user(request, user_id): try: user = User.objects.get(id=user_id) except User.DoesNotExist: return Response({'error': 'User does not exist'}, status=status.HTTP_404_NOT_FOUND) return Response({ 'id': user.id, 'username': user.username, 'email': user.email }, status=status.HTTP_200_OK) ``` 5. 运行 Django 项目,在浏览器中访问 Swagger API URL:`http://localhost:8000/api-docs/`,即可查看生成的接口文档。 注意事项: - 如果需要在文档中显示请求参数、响应数据的数据类型和描述信息,需要在对应的 API 视图中使用 `serializer_class` 属性指定序列化器。例如: ```python @api_view(['POST']) @swagger_auto_schema( operation_description='创建用户', request_body=UserSerializer, responses={ status.HTTP_201_CREATED: '用户创建成功', status.HTTP_400_BAD_REQUEST: '请求参数不合法' } ) def create_user(request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) ``` - `swagger_auto_schema` 装饰器还支持其他参数,例如 `tags`、`operation_id` 等,可以根据实际需求进行设置。详细文档可以参考 `django-rest-swagger` 的官方文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值