S
S
Sergey Sorochinsky2020-02-21 18:59:48
Angular
Sergey Sorochinsky, 2020-02-21 18:59:48

How to handle an arbitrary request to Django Rest Framework?

The task is to receive data from Angular and process it in some way (let's say send a message to telegram. The problem is that either HttpClient does not send a request, or Django does not return it.
Angular's request sending code:

sendMessage(){
    if(this.reCaptchaRes!=null){
      alert("Сообщение отправлено в телеграм!")
      this.http.get('http://127.0.0.1:8000/api/v1/sendMessage/')
      .subscribe((responce)=>{
        console.log('Responce:')
        console.log(responce)
      })
    }
    else{
      alert("Вы должны пройти проверку reCaptcha")
    }
  }

Django request handling code:
from django.shortcuts import render
from django.http import JsonResponse
from rest_framework.response import Response
from rest_framework.views import APIView

class MessageView(APIView):
    def get(self, request):
        data=request.POST
        responce=dict(error=0, message="Message send", success=True)
        return Response(responce)

The funny thing is that through Url 127.0.0.1:8000/api/v1/sendMessage and through Postman there is an answer:
5e4ffe63a662a388590971.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sorochinsky, 2020-02-27
@Achill

Maybe someone needs it. The problem was in the csrf token. Solved the problem but as for me it's a crutch.
1 included csrf_exempt in the url file Api/ urlls.py :

from django.urls import path, include
from django.views.decorators.csrf import csrf_exempt

from Sites.views import SiteListView
from .views import messagePost

app_name= 'Sites'
urlpatterns = [
    path('Site/all/', SiteListView.as_view()),
    path('sendMessage/', csrf_exempt(messagePost)),
]

In the Api/views.py file, to process the request, I made a regular function that receives data from request.body in json format and also returns json after processing:
from django.shortcuts import render
import json
import requests

from django.http import JsonResponse
from rest_framework.response import Response

def messagePost(request):
    data = json.loads(request.body.decode())
    responce=dict(error=0, message="Message send", success=True)

    token = "TELEGRAM_TOKEN"
    url = "https://api.telegram.org/bot"
    channel_id = "CHAT_ID"
    url += token
    method = url + "/sendMessage"
    text="Имя: \n "+str(data.get('name'))+"\n Email: \n "+str(data.get('email'))+"\n Телефон:\n "+str(data.get('phone'))+"\n Сообщение:\n "+str(data.get('message'))

    r = requests.post(method, data={
         "chat_id": channel_id,
         "text": text
          })

    if r.status_code != 200:
        responce['error'] = 5
        responce['message']="Возникла ошибка"

    return JsonResponse(responce)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question