Server Error in Android Volley Request Status Code 500 - python

I have deployed an Flask API in Heroku. Trying to hit the Flask API through Android Volley POST request. But the log file shows NetworkUtility.shouldRetryException: Unexpected response code 500.
I have Tested on Postman.it works perfect.I don't know what is the problem, stuck here for 2 days.
My URL for the Heroku app is correct.
In my Heroku app log file : also shows an error "TypeError: expected string or bytes-like object".
Here is my MainActivity.java :
public class MainActivity extends AppCompatActivity {
EditText question;
Button btn;
TextView textView;
Button reset;
String url = "https://krishokbot.herokuapp.com/chatbot";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
question = (EditText) findViewById(R.id.question);
btn = (Button) findViewById(R.id.btn);
textView = (TextView) findViewById(R.id.textView);
reset = (Button) findViewById(R.id.reset);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
StringRequest stringRequest = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String data = jsonObject.getString("response");
textView.setText(data);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
Log.e("Volley", "Error. HTTP Status Code:" + networkResponse.statusCode);
}
if (error instanceof TimeoutError) {
Log.e("Volley", "TimeoutError");
} else if (error instanceof NoConnectionError) {
Log.e("Volley", "NoConnectionError");
} else if (error instanceof AuthFailureError) {
Log.e("Volley", "AuthFailureError");
} else if (error instanceof ServerError) {
Log.e("Volley", "ServerError");
} else if (error instanceof NetworkError) {
Log.e("Volley", "NetworkError");
} else if (error instanceof ParseError) {
Log.e("Volley", "ParseError");
}
Log.d("Maps:", " Error: " + error.getMessage());
}
}) {
#Override
protected Map<String,String> getParams() {
Map<String,String> params = new HashMap<String, String>();
params.put("question", question.getText().toString());
return params;
}
};
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
queue.add(stringRequest);
}
});
}
}
from flask import Flask, render_template, jsonify, request
import chatbot_response
app = Flask(__name__)
#app.route('/')
def index():
return "hello_world"
ar
#app.route('/chatbot', methods=['POST'])
def chatbotResponse():
question = request.args.get('question')
response = chatbot_response.chatbot_response(question)
return jsonify({"response": str(response)})
if __name__ == '__main__':
app.run()
Heroku log Image link : [https://ibb.co/jRtBfN4]

Related

Newtonsoft.Json.JsonSerializationException: 'Error converting value "Could not parse auth token." to type 'valuesClass' in using FireBase and WinForms

I'm trying to pass data from a Raspberry Pi device to a firebase database. I've been successful on making the Pi side of things workout. But so far I've been unsuccessful on making the data flow to my pc using WinForms and C#.
The expected result would be the data inside the database flow to the GUI in WinForms.
Firebase profile has a parent and that parent has 2 children. The parent is named values and the two children named gyroData and sarjData. One equal to "10" and the other equal to "5". I have had a suspicion that the string values could be the issue but it was not. I've tried changing them to integer values which resulted in another error.
Here is my C# program:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using FireSharp;
using FireSharp.Config;
using FireSharp.Response;
using FireSharp.Interfaces;
namespace databaseGUI
{
public partial class Form1 : Form
{
IFirebaseConfig config = new FirebaseConfig
{
// double checked these in my program, all proper.
BasePath = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
AuthSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
};
IFirebaseClient client;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
client = new FireSharp.FirebaseClient(config);
if (client != null)
{
MessageBox.Show("Connected");
}
}
private void RTBButton_Click(object sender, EventArgs e)
{
FirebaseResponse response = client.Get(#"values");
Dictionary<string, valuesClass> data = JsonConvert.DeserializeObject<Dictionary<string, valuesClass>>(response.Body.ToString());
PopulateRTB(data);
}
private void dataView_Click(object sender, EventArgs e)
{
FirebaseResponse response = client.Get(#"values");
Dictionary<string, valuesClass> data = JsonConvert.DeserializeObject<Dictionary<string, valuesClass>>(response.Body.ToString());
PopulateDataView(data);
}
private void PopulateRTB(Dictionary<string, valuesClass> record)
{
richTextBox1.Clear();
foreach (var item in record)
{
richTextBox1.Text += item.Key + "\n";
richTextBox1.Text += item.Value.gyroData + "\n";
richTextBox1.Text += item.Value.sarjData + "\n";
}
}
private void PopulateDataView(Dictionary<string, valuesClass> record)
{
dataGridView1.Rows.Clear();
dataGridView1.Columns.Clear();
dataGridView1.Columns.Add("gyrodata", "Gyro");
dataGridView1.Columns.Add("sarjdata", "Sarj");
foreach (var item in record)
{
dataGridView1.Rows.Add(item.Key, item.Value.gyroData, item.Value.sarjData);
}
}
}
}
My data class:
namespace databaseGUI
{
class degerlerClass
{
public string gyroData { get; set; }
public string sarjData { get; set; }
}
}
And my python program:
import smbus
import time
from pyrebase import pyrebase
import sys
config = {
"apiKey": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"authDomain": "xxxxxxxxxxxxxxxxxxxxxxx.com",
"databaseURL": "https://xxxxxxxxxxxxxxx.firebaseio.com",
"storageBucket":""
}
firebase = pyrebase.initialize_app(config)
db = firebase.database()
data = {"sarj": str(10), "gyro": str(5) }
db.child("values").set(data)
print(data)

Socketio implementation with FastApi and React

I have the following techstack
FastApi - backend
React - frontend
and want to implement socketio(not Websockets provided by FastApi). It lacks documentation in both FastApi and Socketio
As needed we are using python-socketio for backend socket server and on react we will be using socket.io-client.
After installation we need to setup a socket server.
Backend Implementation
# socket.py
def handle_connect(sid, environ):
logger.info(f"Socket connected with sid {sid}")
class SocketManager:
def __init__(self, origins: List[str]):
self.server = socketio.AsyncServer(
cors_allowed_origins=origins,
async_mode="asgi",
logger=True,
engineio_logger=True,
)
self.app = socketio.ASGIApp(self.server)
#property
def on(self):
return self.server.on
#property
def send(self):
return self.server.send
def mount_to(self, path: str, app: ASGIApp):
app.mount(path, self.app)
socket_manager = SocketManager(settings.origins)
socket_manager.on("connect", handler=handle_connect)
Double check your cors origins. Also you can add other handlers as well using socket_manager.on.
#main.py
from socket import
app = FastAPI(...)
socket_manager.mount_to("/ws", app)
Frontend Implementation
Basic code for integration is as simple as
import { io } from "socket.io-client";
const socket = io("ws://localhost:8000", {{ path: "/ws/socket.io/", transports: ['websocket', 'polling'] }});
socket.on("connect", () => { console.log("Connected", socket.id) });
socket.on("response", () => { console.log("Response", socket.id) });
socket.on("message", data => { console.log(data) });
For my project i created a context for this as follows
import React, { createContext, useContext, useEffect, useState } from 'react';
import { io } from "socket.io-client";
import { useToastContext } from './ToastContext';
export const SocketContext = createContext()
export const SocketProvider = ({ children, uri, options }) => {
const [socketIo, setSocketIo] = useState()
const { sendToast } = useToastContext();
useEffect(() => {
const socket = io(uri, options);
socket.on("connect", () => { console.log("Connected", socket.id) });
socket.on("response", () => { console.log("Response", socket.id) });
socket.on("message", data => {
sendToast(data)
});
setSocketIo(socket)
}, [])
return (
<SocketContext.Provider value={socketIo}>
{children}
</SocketContext.Provider>
)
}
export const useSocket = () => {
return useContext(SocketContext)
}
Now to finally send a message from your server to client you can do
socket_manager.send("Hello World")
Points worth noting
CORS origin should be exactly same if it is http://localhost:3000 from frontend then it should be http://localhost:3000 and not http://localhost:3000/. Look for the backslash
Also the socketio documentation says transports: ['websocket', 'polling'] is default but when i remove this. It gives me cors error. Documentation might be out of date.

How to upload Files using Flutter Web (Python Server)

I am trying to upload multiple files through a Flutter frontend, possibly to a Python server. I have not found any working code on how to upload files through Flutter Web. My frontend code is according an answer here: How to Pick files and Images for upload with flutter web
import 'package:http/http.dart' as http;
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
void main() {
/// your app lunch from here
runApp(new MaterialApp(
//// remove debug logo top left AppBar
debugShowCheckedModeBanner: false,
// application title
title: 'Hello World',
// whole content
home: TabsExample(),
));
}
class TabsExample extends StatefulWidget {
#override
State<StatefulWidget> createState() {
// TODO: implement createState
return TabsState();
}
}
class TabsState extends State<TabsExample> {
#override
Widget build(BuildContext context) {
// TODO: implement build
return DefaultTabController(
length: 1,
child: new Scaffold(
appBar: AppBar(
title: Text('Test Tab'),
bottom: TabBar(tabs: [
Tab(
icon: Text(
'Test',
),
),
]),
),
body: TabBarView(children: [
new FileUploadWithHttp(),
]),
));
}
}
class FileUploadWithHttp extends StatefulWidget {
#override
_FileUploadWithHttpState createState() => _FileUploadWithHttpState();
}
class _FileUploadWithHttpState extends State<FileUploadWithHttp> {
PlatformFile objFile;
PlatformFile result;
void chooseFileUsingFilePicker() async {
//-----pick file by file picker,
var result = await FilePicker.platform.pickFiles(
withReadStream:
true, // this will return PlatformFile object with read stream
allowMultiple: true);
print(result.files.length);
print(result.names);
// print(result.files.first.path); //not supported on web
if (result != null) {
setState(() {
objFile = result.files[0];
//print(objFile.readStream);
});
}
}
void uploadSelectedFile() async {
//---Create http package multipart request object
final request = http.MultipartRequest(
"POST",
Uri.parse("http://localhost:8000"), // e.g. localhost
);
//-----add other fields if needed
//request.fields["id"] = "abc";
//-----add selected file with request
request.files.add(new http.MultipartFile(
"file", objFile.readStream, objFile.size,
filename: objFile.name));
//-------Send request
var resp = await request.send();
//------Read response
String result = await resp.stream.bytesToString();
//-------Your response
print(result);
print('Upload successfull!');
}
#override
Widget build(BuildContext context) {
return Container(
child: Column(
children: [
//------Button to choose file using file picker plugin
ElevatedButton(
child: Text("Choose File"),
onPressed: () => chooseFileUsingFilePicker()),
//------Show file name when file is selected
if (objFile != null) Text("File name : ${objFile.name}"),
//------Show file size when file is selected
if (objFile != null) Text("File size : ${objFile.size} bytes"),
//------Show upload utton when file is selected
ElevatedButton(
child: Text("Upload"), onPressed: () => uploadSelectedFile()),
],
),
);
}
}
Running this on a python server according to this suggestion: https://gist.github.com/UniIsland/3346170
Or any other one that i've tried does not work, the server is not able to recieve the file properly. The error message is:
(False, "Can't find out file name...", 'by: ', ('::1', 62868, 0, 0))
Is there any straighforward way (possibly with code) on how to upload the file? Or do you have an idea why this error is coming?
Any help would be greatly appreciated!
follow this, it might help you.
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:io';
import 'package:path/path.dart';
import 'package:dio/dio.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
File _image;
final GlobalKey<ScaffoldState> _scaffoldstate =
new GlobalKey<ScaffoldState>();
Future getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.camera);
_uploadFile(image);
setState(() {
_image = image;
});
}
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
// Methode for file upload
void _uploadFile(filePath) async {
// Get base file name
String fileName = basename(filePath.path);
print("File base name: $fileName");
try {
FormData formData =
new FormData.from({"file": new UploadFileInfo(filePath, fileName)});
Response response =
await Dio().post("http://192.168.0.101/saveFile.php", data: formData);
print("File upload response: $response");
// Show the incoming message in snakbar
_showSnakBarMsg(response.data['message']);
} catch (e) {
print("Exception Caught: $e");
}
}
// Method for showing snak bar message
void _showSnakBarMsg(String msg) {
_scaffoldstate.currentState
.showSnackBar(new SnackBar(content: new Text(msg)));
}
#override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
key: _scaffoldstate,
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: _image == null ? Text('No image selected.') : Image.file(_image),
),
floatingActionButton: FloatingActionButton(
onPressed: getImage,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}

Can't send/receive a header with axios and python

I`m trying to send custom headers in a post request with axios in the following way:
const onSubmit = async (data) => {
const token = await getAccessTokenSilently();
console.log(token);
const header = {
headers: {
'Authorization': `Bearer ${token}`
}
};
const body = {
source: "website",
user_id: user.sub,
message_category: "crypto",
message_text: data,
};
console.log(body);
axios
.post(serverUrl + "messages/post_message", body, header)
.then((res) => {
// setPosts(res.data.messages);
console.log(res);
})
.catch(function (error) {
// handle error
console.error(error);
});
};
But in my python cherrypy server I`m not getting the custom headers at all. although I do receive it in Acess-Control-Request-Headers as titles without the data.
debugging: auth = cherrypy.request.headers in python:
PS: Sending headers via postman works normally.
Considering that your API is working correctly (you might recheck that as well). See if this works for you:
const onSubmit = async (data) => {
const token = await getAccessTokenSilently();
const options = {
headers: {
'Authorization': `Bearer ${token}`
},
body: {
source: "website",
user_id: user.sub,
message_category: "crypto",
message_text: data,
}
};
axios
.post(serverUrl + "messages/post_message", options)
.then((res) => {
// setPosts(res.data.messages);
console.log(res);
})
.catch(function (error) {
// handle error
console.error(error);
});
};

Cannot retrieve data from endpoint

I have installed Chatterbot for Django integration. I followed the easy tutorial with every step and made it so that the endpoint was: http://127.0.0.1:8000/chatterbot/ What I did next was try to communicate with that endpoint to see if I would get back any results. So I made an Ajax request as follows:
var query = {"text": "My input statement"};
$.ajax({
type: 'POST',
url: "http://127.0.0.1:8000/chatterbot/",
data: JSON.stringify(query),
contentType: 'application/json',
success: function (data) {
console.log(data);
}
});
However, what returns in console is: POST http://127.0.0.1:8000/chatterbot/ 403 (Forbidden) and what returns in the cmd prompt when I run my server is:
csrf: WARNING - Forbidden (CSRF token missing or incorrect.):
/chatterbot/ [29/Mar/2018 02:16:43] "POST /chatterbot/ HTTP/1.1" 403
2502
Why am I getting this error? How can I fix it so I receive the call back from the endpoint?
View for this page:
def IndexView(request):
latest_questions = Questions.objects.all().order_by("-date_published")[:5]
popular_questions = Questions.objects.all().order_by("-num_replies")[:5]
return render(request, 'core/index.html',
{'latest_questions': latest_questions, 'popular_questions': popular_questions
})
Try this code
// using jQuery
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
var query = {
"text": "My input statement",
"csrfmiddlewaretoken": csrftoken
};
$.ajax({
type: 'POST',
url: "http://127.0.0.1:8000/chatterbot/",
data: query,
contentType: 'application/json',
success: function (data) {
console.log(data);
}
});
one way is to send the csrfmiddlewaretoken like below
var query = {
"text": "My input statement",
'csrfmiddlewaretoken': "{{csrf_token }}"
};
other way is to use #csrf_exempt decorator
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def IndexView(request):
# .... code.....
other is to add a script
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
Reference: https://docs.djangoproject.com/en/2.0/ref/csrf/
If you dont want to use CSRF tokens just add this above your code.
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def IndexView(request):
# your code

Categories

Resources