使用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運行項目:

訪問地址:

接口抓包返回信息:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM