How can I seperate data by sessions/requests - javascript

I am doing a song search engine as a project and everything works fine except when I run the program from 2 different computers the data sent to each computer is mixed with the data sent to the other computer
I've tried separating the users with variables in sessions but the variable is much bigger than the max value a session variable can hold.
I've tried also making a different URL based on the request but for some reason it sends a 404 error.
This is the python code relevant
#app.route("/", methods=['GET','POST'])
def index():
global str_request
global search_done
global songs
global already_requested
already_requested=False
api_connection=connected_to_internet()
print(api_connection)
if api_connection:
if request.method == 'POST':
search_request = request.form.getlist('search[]')
str_request=turn_list_to_str(search_request)
str_request=str_request.replace(' ','%20')
print ("/result/"+str_request)
search_request=arrange_request(search_request)
print(search_request)
songs=[]
data=search_api(search_request)
search_done=False
if data!=None:
for hit in data:
songs.append(Song(hit['result']['full_title'],hit['result']['primary_artist']['name'],hit['result']['url'],hit['result']['song_art_image_thumbnail_url']))
return render_template('layout.html')
else:
return render_template('connection.html')
#app.route("/result/"+str_request)
def result():
global songs
return render_template("result.html",songs=songs)
this is the js code relevant
$(document).ready(function(){
$("#search_button").click(function(){
btn=document.getElementById("search_button");
btn.disabled=true;
var $loader = $("<div />");
$loader.addClass('loader');
$loader.appendTo("body");
var search_result=arrangeTag();
//post https://lyritag.xyz/
$.post("http://localhost/",
{
"search":search_result
},function(){
//var user_request = '<%=Session["user_request"]%>';
//alert(user_request);
for(var i = 0; i < search_result.length; i++){
console.log(search_result[i])
}
location.replace("/result/"+search_result);
})
});
});
Both the URL and the app.route of the result are the same but It returns a 404 error.
Any other solution will be great as well.

Related

How update data in JavaScript when flask send a josinify response

I am making a project with raspberry Pi, is a control and monitoring data through internet.
Finally I can make the communication with flask-html-JavaScript
In summary I want to update my chart js graph when the flask function response with jsonify data
I am using Ajax method with getjson but I am executing with setinterval and I don’t want to use setinterval, I want that the getjson function execute when flask function response with jsonify data
Exist any method that can make it?
this is my code in flask:
#app.route('/start', methods=['GET', 'POST'])
def start():
n = request.form['number']
print(int(n))
for i in range(int(n)):
GPIO.output(19, GPIO.LOW)
while gt.read_sensor() == 0:
pass
now0 = datetime.now()
for j in range(1):
value = adc.read( channel = 0 )
volt = (value/1023)*3.3
presure = ((volt/3.3)-0.1)*3/2
p1.append(presure)
global pon
pon = presure
time.sleep(0.25)
pon = -100
Here I capture the value sensor and I call update with global variable the function presson:
#app.route('/pon')
def presson():
return jsonify(result = presson)
and this is my javascript code:
var pon = 0;
var test = 0;
function sendData() {
$.ajax({
type: "POST",
url: "{{ url_for('start') }}",
data: { number : $('#number').val() }
});
setInterval(update_values,100);
}
function update_values() {
$.getJSON('/pon',
function(data) {
$('#result').text(data.result);
pon = data.result;
console.log(data)
});
currently that work good, but sometimes the value is not update, then I want that the function getJSON() run only when recieve a correct value (without setInterval method), what recommend me?

Sending Array Using Ajax to Django App

So I have some jquery and ajax that collects data from checkbox values. This part is working, I used alert to debug the array to see if the appropriate values are being collected when the checkboxes are ticked.
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type:'POST',
url:'createEvent/',
data:{
name: name,
myCheckboxes: myCheckboxes,
}
});
However on my receiving end I have:
def createEvent(request):
if request.method == "POST":
member = request.POST.getlist('myCheckboxes')
print(member)
Member is an empty array. What am I doing wrong? I can't seem to find the answer.

How to send JSON data created by Python to JavaScript?

I am using Python cherrypy and Jinja to serve my web pages. I have two Python files: Main.py (handle web pages) and search.py (server-side functions).
I create a dynamic dropdown list (using JavaScript) based on a local JSON file called component.json(created by function componentSelectBar inside search.py).
I want to ask how can my JavaScript retrieve JSON data without physically storing the JSON data into my local website root's folder and still fulfil the function of dynamic dropdown list.
The componentSelectBar function inside search.py:
def componentSelectBar(self, brand, category):
args = [brand, category]
self.myCursor.callproc('findComponent', args)
for result in self.myCursor.stored_results():
component = result.fetchall()
if (len(component) == 0):
print "component not found"
return "no"
components = []
for com in component:
t = unicodedata.normalize('NFKD', com[0]).encode('ascii', 'ignore')
components.append(t)
j = json.dumps(components)
rowarraysFile = 'public/json/component.json'
f = open(rowarraysFile, 'w')
print >> f, j
print "finish component bar"
return "ok"
The selectBar.js:
$.getJSON("static/json/component.json", function (result) {
console.log("retrieve component list");
console.log("where am i");
$.each(result, function (i, word) {
$("#component").append("<option>"+word+"</option>");
});
});
store results from componentSelectBar into database
expose new api to get results from database and return json to browser
demo here:
#cherrypy.expose
def codeSearch(self, modelNumber, category, brand):
...
result = self.search.componentSelectBar(cherrypy.session['brand'], cherrypy.session['category'])
# here store result into a database, for example, brand_category_search_result
...
#cherrypy.expose
#cherrypy.tools.json_out()
def getSearchResult(self, category, brand):
# load json from that database, here is brand_category_search_result
a_json = loadSearchResult(category, brand)
return a_json
document on CherryPy, hope helps:
Encoding response
In your broswer, you need to GET /getSearchResult for json:
$.getJSON("/getSearchResult/<arguments here>", function (result) {
console.log("retrieve component list");
console.log("where am i");
$.each(result, function (i, word) {
$("#component").append("<option>"+word+"</option>");
});
});
To use that json data directly into javascript you can use
var response = JSON.parse(component);
console.log(component); //prints
OR
You already created json file.If that file is in right format then you can read json data from that file using jQuery jQuery.getJSON() For more: http://api.jquery.com/jQuery.getJSON/
You are rendering a HTML and sending it as response. If you wish to do with JSON, this has to change. You should return JSON in your main.py, whereas you will send a HTML(GET or POST) from Javascript and render it back.
def componentSelectBar(self, brand, category):
/* Your code goes here */
j = json.dumps(components)
// Code to add a persistent store here
rowarraysFile = 'public/json/component.json'
f = open(rowarraysFile, 'w')
print >> f, j
// Better to use append mode and append the contents to the file in python
return j //Instead of string ok
#cherrypy.expose
def codeSearch(self):
json_request = cherrypy.request.body.read()
import json # This should go to the top of the file
input_dict = json.loads(json_request)
modelNumber = input_dict.get("modelNumber", "")
category = input_dict.get("category", "")
brand = input_dict.get("brand", "")
/* Your code goes here */
json_response = self.search.componentSelectBar(cherrypy.session['brand'], cherrypy.session['category'])
return json_response
Here, I added only for the successful scenario. However, you should manage the failure scenarios(a JSON error response that could give as much detail as possible) in the componentSelectBar function. That will help you keep the codeSearch function as plain as possible and help in a long run(read maintaining the code).
And I would suggest you to read PEP 8 and apply it to the code as it is kind of norm for all python programmers and help any one else who touches your code.
EDIT: This is a sample javascript function that will make a post request and get the JSON response:
searchResponse: function(){
$.ajax({
url: 'http://localhost:8080/codeSearch', // Add your URL here
data: {"brand" : "Levis", "category" : "pants"}
async: False,
success: function(search_response) {
response_json = JSON.parse(search_response)
alert(response_json)
// Do what you have to do here;
// In this specific case, you have to generate table or any structure based on the response received
}
})
}

Django + Angular method PUT and POST not allowed

I refactoring a project with Django/Django-Rest and AngularJS 1.4.9. All my GET requests are working fine, but PUT and POST requests don't. I receive a "405 (METHOD NOT ALLOWED)" error.
All my http requests were Ajax and worked fine, but I'm changing to $http now and having this trouble. What is wrong?
app.js
'use strict';
angular.module('myapp', [], function($interpolateProvider, $httpProvider) {
$interpolateProvider.startSymbol('{[{');
$interpolateProvider.endSymbol('}]}');
$httpProvider.defaults.xsrfCookieName = 'jxcsrf';
$httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}).run(function($http) {
$http.defaults.headers.common['Content-Type'] = "application/json";
});
UPDATE showing the django view (but I think is not a django problem, because worked with ajax)
The view
class MusicAction(APIView):
"""
Create a music instance or update the vote field in a music instance.
"""
permission_classes = (IsAllowedOrAdminOrReadOnly,)
def get_playlist(self, station, playlist_id):
try:
return Playlist.objects.get(station=station, pk=playlist_id, playing="1")
except Playlist.DoesNotExist:
raise ValidationError(u'Essa playlist não está em uso.')
def get_music(self, music_id, playlist_id):
try:
obj = Music.objects.get(music_id=music_id, playlist_id=playlist_id)
return obj
except Music.DoesNotExist:
raise ValidationError(u'Essa música já tocou ou não existe.')
def get_object(self, station_id):
try:
obj = Station.objects.get(pk=station_id, is_active=True)
self.check_object_permissions(self.request, obj)
return obj
except Station.DoesNotExist:
return Response(status=404)
def put(self, request, format=None):
station_id = request.data.get("sid")
station = self.get_object(station_id)
playlist_id = request.data.get("pid")
playlist = self.get_playlist(station, playlist_id)
music_id = request.data.get('mid')
music = self.get_music(music_id, playlist_id)
vote = int(request.data.get("vote"))
with transaction.atomic():
total = music.vote
music.vote = total + vote
music.save()
station.last_update = timezone.now()
station.save()
if vote > 0:
Voting.objects.create(voted_by=request.user, music=music)
else:
vote = Voting.objects.get(voted_by=request.user, music=music)
vote.delete()
serializer = MusicSerializer(music)
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
This is the header.
Try using one of the generic views of django rest framework:
http://www.django-rest-framework.org/api-guide/generic-views/
for example, if you'd like to accept get and put use the RetrieveUpdateAPIView:
from rest_framework import generics
class MusicAction(generics.RetrieveUpdateAPIView):
#code...

How do I send data from JS to Python with Flask?

I'm making a website with Flask and I'd like to be able to execute python code using data from the page. I know that I can simply use forms but it's a single page that is continually updated as it receives user input and it'd be a massive pain in the ass to have it reload the page every time something happens. I know I can do {{ function() }} inside the javascript but how do I do {{ function(args) }} inside the javascript using js variables? So far the only thing I can think of is to update an external database like MongoDB with the js then use Python to read from that, but this process will slow down the website quite a lot.
The jQuery needs to get a list of dictionary objects from the Python function which can then be used in the html. So I need to be able to do something like:
JS:
var dictlist = { getDictList(args) };
dictlist.each(function() {
$("<.Class>").text($(this)['Value']).appendTo("#element");
});
Python:
def getDictList(args):
return dictlistMadeFromArgs
To get data from Javascript to Python with Flask, you either make an AJAX POST request or AJAX GET request with your data.
Flask has six HTTP methods available, of which we only need the GET and POST. Both will take jsdata as a parameter, but get it in different ways. That's how two completely different languages in two different environments like Python and Javascript exchange data.
First, instantiate a GET route in Flask:
#app.route('/getmethod/<jsdata>')
def get_javascript_data(jsdata):
return jsdata
or a POST one:
#app.route('/postmethod', methods = ['POST'])
def get_post_javascript_data():
jsdata = request.form['javascript_data']
return jsdata
The first one is accessed by /getmethod/<javascript_data> with an AJAX GET as follows:
$.get( "/getmethod/<javascript_data>" );
The second one by using an AJAX POST request:
$.post( "/postmethod", {
javascript_data: data
});
Where javascript_data is either a JSON dict or a simple value.
In case you choose JSON, make sure you convert it to a dict in Python:
json.loads(jsdata)[0]
Eg.
GET:
#app.route('/getmethod/<jsdata>')
def get_javascript_data(jsdata):
return json.loads(jsdata)[0]
POST:
#app.route('/postmethod', methods = ['POST'])
def get_post_javascript_data():
jsdata = request.form['javascript_data']
return json.loads(jsdata)[0]
If you need to do it the other way around, pushing Python data down to Javascript, create a simple GET route without parameters that returns a JSON encoded dict:
#app.route('/getpythondata')
def get_python_data():
return json.dumps(pythondata)
Retrieve it from JQuery and decode it:
$.get("/getpythondata", function(data) {
console.log($.parseJSON(data))
})
The [0] in json.loads(jsdata)[0] is there because when you decode a JSON encoded dict in Python, you get a list with the single dict inside, stored at index 0, so your JSON decoded data looks like this:
[{'foo':'bar','baz':'jazz'}] #[0: {'foo':'bar','baz':'jazz'}]
Since what we need is the just the dict inside and not the list, we get the item stored at index 0 which is the dict.
Also, import json.
.html
... id="clickMe" onclick="doFunction();">
.js
function doFunction()
{
const name = document.getElementById("name_").innerHTML
$.ajax({
url: '{{ url_for('view.path') }}',
type: 'POST',
data: {
name: name
},
success: function (response) {
},
error: function (response) {
}
});
};
.py
#app.route("path", methods=['GET', 'POST'])
def view():
name = request.form.get('name')
...
im new in coding, but you can try this:
index.html
<script>
var w = window.innerWidth;
var h = window.innerHeight;
document.getElementById("width").value = w;
document.getElementById("height").value = h;
</script>
<html>
<head>
<!---Your Head--->
</head>
<body>
<form method = "POST" action = "/data">
<input type = "text" id = "InputType" name = "Text">
<input type = "hidden" id = "width" name = "Width">
<input type = "hidden" id = "height" name = "Height">
<input type = "button" onclick = "myFunction()">
</form>
</body>
</html>
.py
from flask import Flask, request
app = Flask(__name__)
html = open("index.html").read()
#app.route("/")
def hello():
return html
#app.route("/data", methods=["POST", "GET"])
def data():
if request.method == "GET":
return "The URL /data is accessed directly. Try going to '/form' to submit form"
if request.method == "POST":
text = request.form["Text"]
w = request.form["Width"]
h = request.form["Height"]
//process your code
return //value of your code

Categories

Resources