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&gt;
<html lang="en"&gt;
<head&gt;
    <meta charset="UTF-8"&gt;
    <title&gt;login</title&gt;
</head&gt;
<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')

原文地址:https://blog.csdn.net/yuan_ahui/article/details/125709136

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_31446.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注