How to send result of function from Django Server to React Native App? - ios

I am study React Native and Django Development and I create an app which recognize a text from image. I realized POST method from React Native to Django Server but I don't understand how to send the result of recognition back to React.
How I can resolve this problem?
Django Server:
views.py:
from .serializers import PostSerializer
from .models import Ocr
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.response import Response
from rest_framework import status
# Create your views here.
from django.http.response import JsonResponse
# Create your views here.
# import pytesseract to convert text in image to string
import pytesseract
# import summarize to summarize the ocred text
from .forms import ImageUpload
import os
# import Image from PIL to read image
from PIL import Image
from django.conf import settings
# Create your views here.
class PostView(APIView):
parser_classes = (MultiPartParser, FormParser)
def get(self, request, *args, **kwargs):
posts = Ocr.objects.all()
serializer = PostSerializer(posts, many=True)
print(serializer.data)
return Response(serializer.data)
def post(self, request, *args, **kwargs):
posts_serializer = PostSerializer(data=request.data)
if posts_serializer.is_valid():
text = ""
message = ""
posts_serializer.save()
try:
posts_serializer.save()
image = request.FILES['image']
image = image.name
path = settings.MEDIA_ROOT
pathz = path + "/images/" + image
text = pytesseract.image_to_string(Image.open(pathz), lang='rus+eng')
os.remove(pathz)
except Exception:
message = "check your filename and ensure it doesn't have any space or check if it has any text"
context = {
'text': text,
'message': message
}
print(context)
return Response(posts_serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(posts_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
React-Native:
CameraScreen.js:
const postToServer = (img) => {
const formData = new FormData();
formData.append('image', {
uri: img.uri,
type: 'image/jpeg',
name: 'test.jpg',
})
formData.append('title', 'title');
fetch('http://192.168.0.149:8000/api/textocr/', {
method: 'POST',
body: formData,
// If you add this, upload won't work
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
}
});
}

Related

12200 - Schema validation warning twilio

Hi team i need to fix the 12200 - Schema validation warning twilio.
everything is working but i dont receive the whatsapp respond back .
enter image description here
here is the app.py code:
from helper.openai_api import text_complition
from helper.twilio_api import send_message
from twilio.twiml.messaging_response import MessagingResponse
from flask import Flask, request
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)
#app.route('/')
def home():
return 'All is well...'
#app.route('/twilio/receiveMessage', methods=['POST'])
def receiveMessage():
try:
message = request.form['Body']
sender_id = request.form['From']
# Placeholder code
result = {}
result['status'] = 1
result['response'] = "Hi, I'm CODAI, I have received your message."
send_message(sender_id, result['response'])
except:
pass
return 'OK', 200
here is the openai.py code:
import os
import openai
from dotenv import load_dotenv
from twilio.twiml.messaging_response import MessagingResponse
load_dotenv()
openai.api_key = os.getenv('OPENAI_API_KEY')
def text_complition(prompt: str) -> dict:
'''
Call Openai API for text completion
Parameters:
- prompt: user query (str)
Returns:
- dict
'''
try:
response = openai.Completion.create(
model='text-davinci-003',
prompt=f'Human: {prompt}\nAI: ',
temperature=0.9,
max_tokens=150,
top_p=1,
frequency_penalty=0,
presence_penalty=0.6,
stop=['Human:', 'AI:']
)
return {
'status': 1,
'response': response['choices'][0]['text']
}
except:
return {
'status': 0,
'response': ''
}
here is the twilio.py code:
import os
from twilio.twiml.messaging_response import MessagingResponse
from twilio.rest import Client
from dotenv import load_dotenv
load_dotenv()
account_sid = os.getenv('TWILIO_ACCOUNT_SID')
auth_token = os.getenv('TWILIO_AUTH_TOKEN')
client = Client(account_sid, auth_token)
def send_message(to: str, message: str) -> None:
'''
Send message through Twilio's WhatsApp API.
Parameters:
- to(str): recipient's phone number in the format of "whatsapp:+[country code][phone number]"
- message(str): text message to send
Returns:
- None
'''
_ = client.messages.create(
from_=os.getenv('FROM'),
body=message,
to="whatsapp:" + to
)
i need help to fix the error 12200 - Schema validation warning twilio

NestJS req.body from POST method is empty/undefined when awaiting ArrayBuffer

I am trying to send file from Client (Angular) to the NestJS same way like it is working now with Java-springboot API.
I am using POST method in NestJS but, unfortunatelly I am not able to got any data from the body :
here is the code :
#Post('/uploadExportFile')
uploadAttachment(#Req() req: Request, #Body() attachment: ArrayBuffer): any {
console.log(attachment);
return {};
}
content-type is set in header on Client side, I am not sure if I need to set content-types there ? Content type depends on file mimetype it should be (application/pdf/png/jpeg)..not multiform or what I need to do to achieve that attachment object will not return empty {} .
req.body is undefined
What I need to do with that file is to again change it back to Base64 (in angular it is in Base64) but Java API consumes only byte[] so I need to keep that like it is on FE.
any suggestions what is wrong in this "simple" code?
** EDIT **
====↓ EDIT ↓====
Solution: request.body is undefined is:
NestJS use as default body jsonBody, so in that case you have to override for specific routes that you want to use raw-body, and if raw-body is used insted of jsonBody, then the body from request is not undefined and it contain ArrayBuffer.
What you need to do is something like this;
Create rawBody middleware raw-body.middleware.ts
import { Injectable, NestMiddleware } from '#nestjs/common';
import { Request, Response } from 'express';
import * as bodyParser from 'body-parser';
#Injectable()
export class RawBodyMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: () => any) {
bodyParser.raw({type: '*/*'})(req, res, next);
}
}
app.module.ts
export class AppModule implements NestModule {
public configure(consumer: MiddlewareConsumer): void {
consumer
.apply(RawBodyMiddleware)
.forRoutes({
path: '/uploadExportFile',
method: RequestMethod.POST,
})
.apply(JsonBodyMiddleware)
.forRoutes('*');
}
}
and you need to disable bodyparser in main.ts
const app = await NestFactory.create(AppModule, { bodyParser: false })
in new version of NestJS is introduced new option raw-body but I have no possibility to test that https://docs.nestjs.com/faq/raw-body#raw-body
frist thing send the content-type application/x-www-form-urlencoded
and sure you have add UseInterceptors Like FileInterceptor
you can import FileInterceptor
if you need to get buffer try use file.buffer
import {FileInterceptor} from "#nestjs/platform-express";
#Post('upload')
#UseInterceptors(FileInterceptor('file'))
async upload(#Req() request: RequestWithUser, #UploadedFile() file) {
if (!file) {
throw new HttpException('File is required', HttpStatus.BAD_REQUEST);
}
// you have file
return await this.storageService.upload(file, request.user);
}

How to send and receive image as part of http form-data using requests and flask

I would like to make an http POST request, and include an image as part of the multipart/form-data. I'd like to avoid encoding this image as base64, and just send it as a binary blob, which I know that http can handle.
Here is my code on the client side:
from __future__ import print_function
import requests
import json
import cv2
def post_encoded_image(url, headers):
img = open("cyrus.jpg", 'rb').read()
payload = {'image': img, 'identity': 'cyrus'}
r = requests.post(url + "encoded-image", data=payload)
print(r)
url = "http://localhost:8080/"
content_type = 'multipart/form-data'
headers = {'content-type': content_type}
post_encoded_image(url, headers)
On the server side, my code looks like this:
from flask import Flask, request
import flask
import tfsdk
import numpy as np
from colorama import Fore
from colorama import Style
import os
import cv2
#app.route('/encoded-image', methods=['POST'])
def test():
image = request.form.get("image")
nparr = np.fromstring(image, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
print(type(img))
return "success"
if __name__ == '__main__':
app.run()
When I make the request, the server prints the type of img as NoneType, meaning the call to imdecode didn't work, meaning something strange is going on the server side with the encoded image.
What is the proper way to do this?
Edit
I was able to achieve the desired functionality by doing the following:
client:
from __future__ import print_function
import requests
import json
import cv2
def post_encoded_image(url, headers):
img = open("cyrus.jpg", 'rb').read()
file = {'image': img}
data = {'identity': 'cyrus'}
r = requests.post(url + "encoded-image", data=data, files=file)
print(r)
url = "http://localhost:8080/"
content_type = 'multipart/form-data'
headers = {'content-type': content_type}
post_encoded_image(url, headers)
Server:
#app.route('/encoded-image', methods=['POST'])
def test():
ID = request.form.get("identity")
image = request.files['image'].read()
nparr = np.fromstring(image, np.uint8)
Is this the proper way of doing it?
I was able to achieve the desired functionality as follows:
Client:
from __future__ import print_function
import requests
import json
import cv2
def post_encoded_image(url, headers):
img = open("cyrus.jpg", 'rb').read()
file = {'image': img}
data = {'identity': 'cyrus'}
r = requests.post(url + "encoded-image", data=data, files=file)
print(r)
url = "http://localhost:8080/"
content_type = 'multipart/form-data'
headers = {'content-type': content_type}
post_encoded_image(url, headers)
Server:
#app.route('/encoded-image', methods=['POST'])
def test():
ID = request.form.get("identity")
image = request.files['image'].read()
nparr = np.fromstring(image, np.uint8)

Google Apps Script - Failed to send a request

I need a help.
I have a Flask API running like this:
from flask import Flask
from flask import jsonify
app = Flask(__name__)
#app.route('/rules/<payload>', methods=['GET', 'POST'])
def add_none(payload):
return jsonify({'result': payload})
if __name__ == '__main__':
app.run(debug=False)
My Google code is trying to send a post request, but always I got an invalid request.
I ran the same request using Postman and I didn't get the error. I don't understand what's happening.
rulesArray = [{'column_a': 35.0, 'column_b': 100.0, 'column_c': 105.0}, {'column_a': 38.0, 'column_b': 50.0, 'column_c': 80.0}];
var payload = {'content': rulesArray};
var params = { method: "POST", payload: payload, muteHttpExceptions: true, contentType: "application/json" };
var URL = 'http://127.0.0.1:5000/rules';
var response = UrlFetchApp.fetch(URL, params);
Any ideas what I can do to fix this? Thanks.

JIRA do I have a way to get the list all ID of my transition steps?

I want to synchronize between two systems. However, to update the transition status of the bug I have to send a JSON file with my arguments (new status) something like this:
{
"update": {
"comment": [
{
"add": {
"body": "Comment added when resolving issue"
}
}
]
},
"transition": {
"id": "5"
}
}
To set a new status I have to set it's id, How can I get the list of all the IDs and the description of each one.
You can get a list of the transitions possible for this issue by the current user, along with fields that are required and their types by url /rest/api/2/issue/{issueIdOrKey}/transitions (get request)
You can use the following python script to get the information you want.
#!/usr/bin/env python
from __future__ import print_function
import ConfigParser
import requests
import json
import base64
import sys
def print_error(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
def get_issue(user,password,search_url):
user_auth = base64.b64encode(user+':'+password)
headers = {'Authorization': 'Basic ' + user_auth}
return requests.get(search_url, headers=headers)
def main():
if len(sys.argv) < 2:
usage_message = 'Usage: ' + sys.argv[0] + ' issue_number'
print_error(usage_message)
sys.exit(1)
config = ConfigParser.RawConfigParser()
config.read('config.properties')
jira_user = config.get('Global', 'jira_user')
jira_pass = config.get('Global', 'jira_pass')
jira_base_url = config.get('Global', 'jira_base_url')
issue_url = config.get('Global', 'issue_url')
issue = sys.argv[1]
issue_search_url = jira_base_url + issue_url + issue + '/transitions'
response = get_issue(jira_user,jira_pass,issue_search_url)
if response.status_code == 404:
print_error(issue + ' NOT FOUND!')
sys.exit(1)
data = response.json()
for transition in data['transitions']:
print("%s %s" % (transition['id'], transition['name']))
main()
You need to have a configuration file (config.properties) in the same directory as the script with the following content:
[Global]
jira_user=username
jira_pass=pass
jira_base_url=http://your_jira_url.com
issue_url=/rest/api/2/issue/
Then you call the script like this:
./get_transitions.py your_ticket_number

Resources