error to save history chess into db sqlite django - python

I use django 2.1 and combine its with nodejs.
the game is ok but when game end, I want to save history into db of django. But it's not run. I'm not sure where is issue
static\main.js
winner = checkLogout !== username ? username : checkLogout;
history= game.history();
socket.emit('endgame', {'gameId':gameId,'player1':player1, 'player2':player2, 'winner': winner, 'history': history.toString(), note : checkLogout });
nodejs\index.js
var http = require('http').createServer().listen(4000);
var io = require('socket.io')(http);
var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
var xhttp = new XMLHttpRequest();
var host = 'localhost';
var port = '8000';
io.on('connection', function (socket) {
socket.on('endgame', function(msg){
var url = 'http://' + host +':' + port + '/save_game/';
xhttp.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200) {
if(xhttp.responseText === "error")
console.log("error saving game");
else if(xhttp.responseText === "success")
console.log("the message was posted successfully");
}
};
xhttp.open('POST', url, true);
xhttp.send(JSON.stringify(msg));
});
});
game\views.py
import json
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from game.models import Game
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
#login_required
def index(request):
return render(request, 'index.html')
#csrf_exempt
def save_game(request):
if request.method == 'POST':
msg_obj = json.loads(request.body.decode('utf-8'))
try:
msg = Game.objects.create(gameId=msg_obj['gameId'], player1=msg_obj['player1'], player2=msg_obj['player2'], winner = msg_obj['winner'], history = msg_obj['history'])
msg.save()
except:
print("error saving game")
return HttpResponse("error")
return HttpResponse("success")
else:
return HttpResponseRedirect('/')
update code static\main.js
socket.on('joingame', function (msg) {
gameId = msg.game.gameId;
player1 = username;
player2 = oppDict;});

Related

Issue in uploading image for prediction using a MultiPart POST Request

The call is currently happening via a Flutter application which makes a multi-part POST request.
Flutter Code
var request = http.MultipartRequest(
'POST',
Uri.parse('https://techfarmtest.herokuapp.com/upload'),
);
Map<String, String> headers = {"Content-type": "multipart/form-data"};
request.files.add(
http.MultipartFile(
widget.selectedImage.toString(),
widget.selectedImage.readAsBytes().asStream(),
widget.selectedImage.lengthSync(),
filename: widget.selectedImage.path.split('/').last,
),
);
request.headers.addAll(headers);
var res = await request.send();
http.Response response = await http.Response.fromStream(res);
var data = jsonDecode(response.body);
return data;
I intend to upload the image to the backend and then perform the prediction and retrieve the result in JSON format and the backend is scripted using Flask.
Flask Code
#app.route('/upload',methods=["POST"])
def upload_image():
if request.method == "POST":
imageFile = request.files['image']
fileName = werkzeug.utils.secure_filename(imageFile.filename)
print('\nRecieved File name : ' + imageFile.filename)
imageFile.save('./uploadedImages/' + fileName)
pred('./uploadedImages/fileName')
def pred(sampleFile):
model = load_model('./model.h5')
# model.summary()
sample_file = sampleFile
sample_img = image.load_img(sample_file,target_size = (256,256,3))
sample_img = image.img_to_array(sample_img)
sample_img = np.expand_dims(sample_img,axis=0)
prediction_arr = model.predict(sample_img)
result = {
'Sample' : str(sampleFile),
'Label' : str(class_names[prediction_arr.argmax()]),
'Confidence' : str(prediction_arr.max())
}
return jsonify(result)
The current issue I am facing is that I am making a bad request (400).This is a rough code (pseudocode) that I have figured out from various resources. Is there any way to go about it.
So, I figured it out by myself.
I will be attaching the code below for future references.
Flutter Code :
var request = http.MultipartRequest(
'POST',
Uri.parse('https://techfarmtest.herokuapp.com/upload'),
);
request.files.add(
await http.MultipartFile.fromPath('image', img.path),
);
var res = await request.send();
You can verify the POST request by using the below logs :
log('${res.statusCode}', name: 'POST-request-statusCode');
log('${res.reasonPhrase}', name: 'POST-request-status');
With respect to Flask :
#app.route('/upload',methods=["POST","PUT"])
def upload_image():
if request.method == "POST":
imageFile = request.files['image']
***you can perform any operation on the file you have recieved from the request now***
Thank you!

Django Redirect: No errors, but no redirect [duplicate]

This question already has answers here:
Redirecting after AJAX post in Django
(3 answers)
Closed 1 year ago.
I POST some data via an HTML form using AJAX to modify data in my database. The data is successfully modified by executing stored procedures on the DB. Final line of the view.py function call is return redirect('Home').
The redirect is successfully executing, but I am not being redirected. I can overcome this by adding window.location.href = 'http://127.0.0.1:8000/ in the success function of the AJAX call. The problem is, I want to use messages.success(request, 'Data Successfully Updated'), which only appears after refreshing the AJAX-originating redirect.
Is there a reason why return redirect('Home') is not working here, and is there a way to overcome this?
Home is the name of my path in urls.py
[06/May/2021 17:23:52] "POST /search/ HTTP/1.1" 302 0 // submitting changes to database
[06/May/2021 17:23:55] "GET / HTTP/1.1" 200 4750 // The page I am intending to redirect to
Ajax Call
function updateCards(){
ajaxUpdCard().done()
function ajaxUpdCard() {
return $.ajax({
type: 'POST',
url: '',
data: {csrfmiddlewaretoken: window.CSRF_TOKEN, Action: 'Card', CardID: $('#currentCardID').val(),
BCard: $('#sr-bad_card').val(), CNum: $('#sr-card_number').val(), CPin: $('#sr-pin_number').val(),
Bal: $('#sr-balance').val()}
})
}
}
views.py
if request.method == 'POST' and request.POST['Action'] == 'Card':
cardID = request.POST['CardID']
Bcard = int(request.POST['BCard'])
CNum = int(request.POST['CNum'])
CPin = int(request.POST['CPin']) if request.POST['CPin'] != '' and request.POST['CPin'] != 'XXXX' else 'Null'
print(CPin)
Bal = request.POST['Bal']
update_card_transaction(entityID, userID, cardID, Bcard, CNum, CPin, Bal)
messages.success(request, 'Data Successfully Updated')
return redirect('Home')
You shood return some data from backend side, and redirect on your clinet side
views.py
if request.method == 'POST' and request.POST['Action'] == 'Card':
cardID = request.POST['CardID']
Bcard = int(request.POST['BCard'])
CNum = int(request.POST['CNum'])
CPin = int(request.POST['CPin']) if request.POST['CPin'] != '' and request.POST['CPin'] != 'XXXX' else 'Null'
print(CPin)
Bal = request.POST['Bal']
update_card_transaction(entityID, userID, cardID, Bcard, CNum, CPin, Bal)
messages.success(request, 'Data Successfully Updated')
return JsonResponse({'foo':'bar'})
Ajax Call
function updateCards() {
ajaxUpdCard().done()
function ajaxUpdCard() {
return $.ajax({
type: 'POST',
url: '',
data: {
csrfmiddlewaretoken: window.CSRF_TOKEN, Action: 'Card', CardID: $('#currentCardID').val(),
BCard: $('#sr-bad_card').val(), CNum: $('#sr-card_number').val(), CPin: $('#sr-pin_number').val(),
Bal: $('#sr-balance').val()
},
success:function(response) {
window.location.href='/home'
}
})
}
}
redirect take as argument the full path as string or view name :
if request.method == 'POST' and request.POST['Action'] == 'Card':
cardID = request.POST['CardID']
Bcard = int(request.POST['BCard'])
CNum = int(request.POST['CNum'])
CPin = int(request.POST['CPin']) if request.POST['CPin'] != '' and request.POST['CPin'] != 'XXXX' else 'Null'
print(CPin)
Bal = request.POST['Bal']
update_card_transaction(entityID, userID, cardID, Bcard, CNum, CPin, Bal)
messages.success(request, 'Data Successfully Updated')
return redirect(Home)
or you can use reverse :
if request.method == 'POST' and request.POST['Action'] == 'Card':
cardID = request.POST['CardID']
Bcard = int(request.POST['BCard'])
CNum = int(request.POST['CNum'])
CPin = int(request.POST['CPin']) if request.POST['CPin'] != '' and request.POST['CPin'] != 'XXXX' else 'Null'
print(CPin)
Bal = request.POST['Bal']
update_card_transaction(entityID, userID, cardID, Bcard, CNum, CPin, Bal)
messages.success(request, 'Data Successfully Updated')
return redirect(reverse('Home'))

Google Maps Directions API Calculating Incorrect Route

I'm creating a web application using Flask and the Google Maps Directions API, where I ask the user to enter a starting point, waypoints, and a destination, and pass this data to the Google API to render a map illustrating the user's route. No matter what these data points are, however, the API keeps interpreting all 3 data points as a single location, and renders the map accordingly. The rendered map is
here, where you can also see what this exact wrong address is.
The relevant source files are as follows:
run.py (where I call my template to render the Google Map in the "/finalize_new_trip" route):
from os.path import abspath, dirname, join
from flask import flash, Flask, Markup, redirect, render_template, url_for, request
from flask.ext.sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms.validators import DataRequired
import os
import googlemaps
from datetime import datetime
import json
_cwd = dirname(abspath(__file__))
SECRET_KEY = 'flask-session-insecure-secret-key'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + join(_cwd, 'TripLogger.db')
SQLALCHEMY_ECHO = True
WTF_CSRF_SECRET_KEY = 'this-should-be-more-random' #TODO: RANDOMIZE THIS KEY
app = Flask(__name__)
app.config.from_object(__name__)
db = SQLAlchemy(app)
class Trip(db.Model):
__tablename__ = 'trips'
id = db.Column(db.Integer, primary_key=True)
trip_name = db.Column(db.String, unique=True)
origin = db.Column(db.String)
destination = db.Column(db.String)
waypoints = db.Column(db.String) #SEE IF ANOTHER DATA TYPE IS BETTER- IDEALLY WANT TO STORE LIST OF STRINGS
def __init__(self, trip_name, origin, destination, waypoints):
self.trip_name = trip_name
self.origin = origin
self.destination = destination
self.waypoints = waypoints
def __repr__(self):
return '<Trip %r(name = %r, origin = %r, destination = %r)>' % (self.id, self.trip_name, self.origin, self.destination)
def __str__(self):
return self.trip_name
#CONSIDER CUSTOM VALIDATORS TO ENSURE THAT TRIP_NAME IS UNIQUE FOR A SPECIFIC USER/ACCOUNT
class TripForm(FlaskForm):
trip_name = StringField('Trip Name', validators=[DataRequired()])
origin = StringField('Origin', validators=[DataRequired()])
destination = StringField('Destination', validators=[DataRequired()])
waypoints = StringField('Waypoint')
#app.route("/", methods = ["GET", "POST"])
def index():
trip_form = TripForm(request.form)
if trip_form.validate_on_submit():
flash("Submitted new trip form, now redirecting to /finalize_new_trip to render map...")
return redirect(url_for("complete_trip", trip_name = trip_form.trip_name.data, origin = trip_form.origin.data, destination = trip_form.destination.data, waypoints = trip_form.waypoints.data))
return render_template("index.html", trip_form = trip_form)
# Route to display trip on map (in future, to modify trip details, e.g. waypoints)
#app.route("/finalize_new_trip", methods=["POST"])
def complete_trip():
return render_template("finish_new_trip.html", trip_name = request.args.get("trip_name"), origin = request.args.get("origin"), destination = request.args.get("destination"), waypoints = request.args.get("waypoints"))
# Store new trip data in database
#app.route("/store_trip", methods=["POST"])
def store_trip():
trip_data = request.form("trip_data")
return json.loads(trip_data)[0]
def query_to_list(query, include_field_names=True):
"""Turns a SQLAlchemy query into a list of data values."""
column_names = []
for i, obj in enumerate(query.all()):
if i == 0:
column_names = [c.name for c in obj.__table__.columns]
if include_field_names:
yield column_names
yield obj_to_list(obj, column_names)
def obj_to_list(sa_obj, field_order):
"""Takes a SQLAlchemy object - returns a list of all its data"""
return [getattr(sa_obj, field_name, None) for field_name in field_order]
if __name__ == "__main__":
app.debug = True
db.create_all()
app.run()
finish_new_trip.html (the template using the Google Maps API to render the map):
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script async defer
src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=<MY_API_KEY>&callback=getOriginCoordinates" type="text/javascript">
</script>
<title>Finish New Trip</title>
</head>
<body>
<div id="trip_name">
<h1> {{ trip_name }} </h1>
</div>
<div id="map"></div>
<div id="right-panel">
<div>
<form>
<input type="submit" id="finish-new-trip-button" value="Add My Trip!">
</form>
</div>
<div id="directions-panel"></div>
</div>
<script>
//Wrapper function to AJAX POST request that passes data back to server.
/*function passTripData() {
document.getElementById("finish-new-trip-button").onclick = function() {
// Retrieve data from displayed map (after user makes changes) after testing
$.post( "{{ url_for('store_trip') }}", {
trip_data: {
"trip_name": "{{ trip_name }}",
"origin": "{{ origin }}",
"destination": "{{ destination }}",
"waypoints": [
"{{ waypoints }}"
]
}
});
}
}*/
//Use Geocoding API to get coordinates for origin, destination, and waypoints.
function getOriginCoordinates() {
//passTripData(); // function that sets onClick event for "Submit" button
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': "{{ origin }}"}, function(results, status) {
if (status == 'OK') {
originCoordinates = results[0].geometry.location;
console.log("Origin coords: " + "lat = " + originCoordinates.lat() + ", lng = " + originCoordinates.lng());
getDestCoordinates(originCoordinates);
} else {
alert('Geocode of origin was not successful for the following reason: ' + status);
}
});
}
function getDestCoordinates(originCoords) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': "{{ destination }}"}, function(results, status) {
if (status == 'OK') {
destCoordinates = results[0].geometry.location;
console.log("Dest coords: " + "lat = " + destCoordinates.lat() + ", lng = " + destCoordinates.lng());
getWaypointCoordinates(originCoords, destCoordinates);
} else {
alert('Geocode of destination was not successful for the following reason: ' + status);
}
});
}
function getWaypointCoordinates(originCoords, destCoords) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': "{{ waypoints }}"}, function(results, status) {
if (status == 'OK') {
waypointCoordinates = results[0].geometry.location;
console.log("Waypoint coords: " + "lat = " + waypointCoordinates.lat() + ", lng = " + waypointCoordinates.lng());
initMap(originCoords, destCoords, waypointCoordinates);
} else {
alert('Geocode of waypoints was not successful for the following reason: ' + status);
}
});
}
function initMap(originCoords, destCoords, waypointCoords) {
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
//Center map between origin and destination.
//TEST LATLNG OBJECTS FIRST
console.log("Origin: lat=" + originCoords.lat() + ", lng=" + originCoords.lng());
console.log("Destination: lat=" + destCoords.lat() + ", lng=" + destCoords.lng());
var mapLatitudeCenter = (originCoords.lat() + destCoords.lat())/2;
var mapLongitudeCenter = (originCoords.lng() + destCoords.lng())/2;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: mapLatitudeCenter, lng: mapLongitudeCenter}
});
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay, originCoords, destCoords, waypointCoords);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay, originCoords, destCoords, waypointCoords) {
var waypts = [];
waypts.push({
location: waypointCoords,
stopover: true
});
directionsService.route({
origin: originCoords,
destination: destCoords,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions-panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment +
'</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
</script>
</body>
</html>
When I test my app locally, the console displays the latitude/longitude coordinates of each data point (origin, destination, and waypoints), and they all correspond to this incorrect address in Italy. I also previously received a "404" error message, but I am not receiving that now.
I attempted to regenerate my API key and use this new key, but this didn't fix the problem. How can I go about resolving this issue?
When I change complete_trip(): to
#app.route("/finalize_new_trip", methods=["GET"])
def complete_trip():
return render_template("finish_new_trip.html", trip_name ='new trip', origin='new york, ny', destination='los angeles, california', waypoints='topeka, kansas')
and request the page, the results are perfect (a trip from NY to LA that goes through Topeka). You've got a lot of commented out code everywhere. I have a feeling that somewhere you're not getting the data you expect (for example, we can't see the form HTML used to post this data).

request through ajax render to a page not working django

After making an ajax request data is being sent successfully to view. But the render function is not working. Render function should render to dashboard.html with data. I have imported all files needed to render. Is it because of an ajax request. Thanks in advance...
My ajax request from template
$("#campaign").click(function () {
alert("hey main")
alert($("#campaign").val());
var id = $("#campaign").val()
$.ajax({
type: "POST",
url: "{% url 'appdata' %}",
data: {
userid: id
}
}).done(function () {
alert("Data Sent: ");
}).fail(function () {
alert("error");
});
/* location.reload()*/
});
My urls.py
url(r'^publisher/appdata/?$', 'appdata', name='appdata'),
My views.py
def appdata(request):
print 'hi i am appdata, fetch me after select id'
print request
userid = request.POST['userid']
# print 'userid: %s'%userid
impressions = Impressions.objects.get(id=userid)
# print 'impressionid: %s'%impressions.id
clicks = Clicks.objects.get(id=userid)
revenues = Revenue.objects.get(id=userid)
ecpm = App.objects.get(id=userid)
member = Member.objects.get(id=userid)
campaigns_id = Campaign.objects.get(id=userid)
# print campaigns_id
# print type(campaigns_id)
apps = App.objects.all()
# print apps
# for i in apps:
# print i.name
# print len(camps)
# dict = {'i':impressions, 'c':clicks, 'r':revenues, 'e':ecpm, 'apps': apps, 'member':member, 'c_id':campaigns_id }
# print dict['i'].impressions
return render(request, 'dashboard.html', {'i':impressions, 'c':clicks, 'r':revenues, 'e':ecpm, 'apps': apps, 'member':member, 'c_id':campaigns_id })

Channel API Presence not triggering

I'm trying to handle disconnect / connect states using Presence in the Channel API.
Here are some of my code.
app.yaml
handlers:
- url: /(.*\.(gif|png|jpg|ico|js|css))
static_files: \1
upload: (.*\.(gif|png|jpg|ico|js|css))
- url: .*
script: main.py
inbound_services:
- channel_presence
main.py
class onConnect(webapp.RequestHandler):
def post(self):
for user in users:
users = User.all().fetch(1000)
client = client_id = self.request.get('from')
channel.send_message(user.channel,' connected');
class onDisconnect(webapp.RequestHandler):
def post(self):
Mainpage()
for user in users:
users = User.all().fetch(1000)
client = client_id = self.request.get('from')
channel.send_message(user.channel, ' disconnected');
application = webapp.WSGIApplication(
[('/', MainPage),
('/_ah/channel/connected/',onConnect),
('/_ah/channel/disconnected/',onDisconnect),
('/chat',handleChat)],
debug=True)
Javascript
<script>
openChannel = function(){
var token = '{{ token }}';
var channel = new goog.appengine.Channel(token);
var handler = {
'onopen': onOpened,
'onmessage': onMessage,
'onerror': function() {},
'onclose': function() {}
};
var socket = channel.open(handler);
socket.onopen = onOpened;
socket.onmessage = onMessage;
var chat = document.getElementById('chatinput');
chat.onkeyup = function(e){
if(e.keyCode == 13){
sendChat(this.value);
this.value = '';
}
}
}
sendMessage = function(path, opt_param) {
if (opt_param) {
path += '?' + opt_param;
}
var xhr = new XMLHttpRequest();
xhr.open('POST', path, true);
xhr.send();
};
onOpened = function(){
console.log('Channel Opened');
var chatlog = document.getElementById('chatlog');
var msg = document.createElement('div');
msg.innerHTML = 'Channel Opened';
chatlog.appendChild(msg);
sendMessage('/chat','m='+'A User Joined.');
}
onMessage = function(m){
console.log('Message Recieved');
var chatlog = document.getElementById('chatlog');
var msg = document.createElement('div');
var d = new Date();
msg.innerHTML = d.toLocaleTimeString() + ': ' + m.data;
chatlog.appendChild(msg);
}
sendChat = function(msg){
console.log(msg);
sendMessage('/chat','m='+msg);
}
openChannel();
</script>
Using this code, connnect and disconnect is not triggering when a user closes their browser or whatever.
Are there anything wrong with this code?
Yes, route list is wrong. Put ('/', MainPage) in the end of the routes list. From webapp2 URI routing guide:
When the application receives a request, it tries to match each one in order until one matches, and then call the corresponding handler.

Categories