Django 从 NodeMCU ESP8266HTTPClient 接收 POST 数据

Django receive POST data from NodeMCU ESP8266HTTPClient

你好,我是 Django 框架的新手,我正在使用 Django 框架将 http.POST 数据从 NodeMCU 发送到 Web 应用程序,发送的数据是 RFID 的字符串 ID卡.

我想将 NodeMCU 发送的 POST 数据渲染到下面模板中的文本区域。我不知道如何使用 Django 框架处理 NodeMCU 发送的 http.POST。

我测试了视图函数并将数据呈现给模板。如果数据发送或接收成功,我不会。

Arduino 版本 1.8.13

Django 版本 3.1.4

如有任何帮助,我们将不胜感激

views.py

 from django.shortcuts import render


# Create your views here.

def card_reg(request):
    id = request.POST.get('UIDresult', 'whatever')
    context = {
        'id': id
    }
    return render(request, 'nodemcuapp/card_reg.html', context)

templates/card_reg.html

 ''' 
      {% extends 'nodemcuapp/main.html' %}

{%block content%}
 <div class="container">
      <br>
      <div class="center" style="margin: 0 auto; width:495px; border-style: solid; border-color: #f2f2f2;">
        <h3 align="center" class="text-primary">Registration Form</h3>
        <br>
        <form action=" " method="POST" >
            {%csrf_token%}
          <div class="form-group">
            <label class="text-primary">ID</label>
            <div>
              <textarea class="form-control" name="id" id="getUID" placeholder="Please Tag your Card to display ID" rows="1" cols="1" required>{{id}}</textarea>
            </div>
          </div>

          <div>
            <label class="text-primary">Name</label>
            <div>
              <input class="form-control" id="div_refresh" name="name" type="text"  placeholder="" required>
            </div>
          </div>

          <div class="form-group">
            <label class="text-primary">Email Address</label>
            <div>
              <input class="form-control" name="email" type="text" placeholder="" required>
            </div>
          </div>
            <div class="row">
              <div class="col-md-7">
                <label class="text-primary">Mobile Number</label>
                <div>
                  <input class="form-control" name="mobile" type="text"  placeholder="" required>
                </div>
              </div>

                <div class="col-md-5">
                    <label class="text-primary">Select</label>
                  <select class="custom-select mr-sm-2" id="inlineFormCustomSelect">
                    <option selected>Gender</option>
                    <option value="Male">Male</option>
                    <option value="Female">Female</option>
                  </select>
                </div>
            </div>
          <div class="form-group">
            <button type="submit" class="btn btn-primary form-control">Save</button>
          </div>
        </form>
      </div>
    </div>
{%endblock%}
'''

nodemcuapp/urls.py

from django.urls import path
from . import views


urlpatterns = [
    path('', views.home, name='home'),
    path('user_data', views.user_data, name='user_data'),
    path('card_registration/', views.card_reg, name='card_reg'),
    path('read_card', views.card_read, name='card_read'),
]

Arduino_code.ino

#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN D2  //--> SDA / SS is connected to pinout D2
#define RST_PIN D1  //--> RST is connected to pinout D1
MFRC522 mfrc522(SS_PIN, RST_PIN);  //--> Create MFRC522 instance.

#define ON_Board_LED 2  //--> Defining an On Board LED, used for indicators when the process of connecting to a wifi router


const char* ssid = "my_ssid";
const char* password = "my_password";


ESP8266WebServer server(80);  //--> Server on port 80

int readsuccess;
byte readcard[4];
char str[32] = "";
String StrUID;


void setup() {
  Serial.begin(115200); //--> Initialize serial communications with the PC
  SPI.begin();      //--> Init SPI bus
  mfrc522.PCD_Init(); //--> Init MFRC522 card

  delay(500);

  WiFi.begin(ssid, password); //--> Connect to your WiFi router
  Serial.println("");
    
  pinMode(ON_Board_LED,OUTPUT); 
  digitalWrite(ON_Board_LED, HIGH); //--> Turn off Led On Board

 
  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    digitalWrite(ON_Board_LED, LOW);
    delay(250);
    digitalWrite(ON_Board_LED, HIGH);
    delay(250);
  }
  digitalWrite(ON_Board_LED, HIGH); 
  Serial.println("");
  Serial.print("Successfully connected to : ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());

  Serial.println("Please tag a card to display UID !");
  Serial.println("");
}

void loop() {
  // put your main code here, to run repeatedly
  readsuccess = getid();
 
  if(readsuccess) {  
  digitalWrite(ON_Board_LED, LOW);
    HTTPClient http;    //Declare object of class HTTPClient
 
    String UIDresultSend, postData;
    UIDresultSend = StrUID;
    Serial.println(UIDresultSend);
    //Post Data
    postData = "UIDresult=" + UIDresultSend;
  
    http.begin("http://192.168.1.8:8080/card_registration/");  //Specify request destination
    http.addHeader("Content-Type", "application/x-www-form-urlencoded"); //Specify content-type header
   
    int httpCode = http.POST(postData);   //Send the request
    String payload = http.getString();    //Get the response payload
    Serial.println("");
    Serial.println(httpCode);   //Print HTTP return code
    Serial.println(payload);    //Print request response payload
    
    http.end();  //Close connection
    delay(1000);
  digitalWrite(ON_Board_LED, HIGH);
  }
}

int getid() {  
  if(!mfrc522.PICC_IsNewCardPresent()) {
    return 0;
  }
  if(!mfrc522.PICC_ReadCardSerial()) {
    return 0;
  }
 
  
  
  for(int i=0;i<4;i++){
    readcard[i]=mfrc522.uid.uidByte[i]; //storing the UID of the tag in readcard
    array_to_string(readcard, 4, str);
    StrUID = str;
  }
  Serial.println("");
  Serial.print("THE UID OF THE SCANNED CARD IS : ");
  mfrc522.PICC_HaltA();
  return 1;
}

void array_to_string(byte array[], unsigned int len, char buffer[]) {
    for (unsigned int i = 0; i < len; i++)
    {
        byte nib1 = (array[i] >> 4) & 0x0F;
        byte nib2 = (array[i] >> 0) & 0x0F;
        buffer[i*2+0] = nib1  < 0xA ? '0' + nib1  : 'A' + nib1  - 0xA;
        buffer[i*2+1] = nib2  < 0xA ? '0' + nib2  : 'A' + nib2  - 0xA;
    }
    buffer[len*2] = '[=14=]';
}

您需要创建一个 forms.py 以使其在您的 views.py 上运行,然后按照以下说明进行操作。

forms.py

from django import forms

class SaveForm(forms.Form):
    UIDresult = forms.CharField(label='UIDresult', max_length=200)

views.py

from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
# Note please import forms.py here ....

@csrf_exempt
def card_registrations(request):
    form = SaveForm(request.POST)
    context = {
        id: form.cleaned_data.get('UIDresult'),
    }
    return render(request, 'nodemcuapp/card_reg.html', context)