使用django开发一个简单的post接口

第1步:创建django项目和app

创建成功后如图:

第2步:注册app,这里用pycharm创建项目的可以忽略,pycharm已经自动帮你注册了。

第3步,定义视图函数:

函数如下:

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

# Create your views here.
def login(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        return HttpResponse(username)
    else:
        return render_to_response('login.html')

  

第4步,在templates下创建html文件:

html文件如下:

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

</body>
</html>

第5步,在urls里面添加url映射:

第6步,注释掉csrf验证:

不注释访问会报错403:

第6步,进入项目目录,python manage.py runserver运行项目:

访问地址:

接口抓包返回信息:

猜你喜欢

转载自www.cnblogs.com/xiamaojjie/p/12124390.html