Python-Requests, how to dynamically receive the url? - javascript

I have looked all over Stack Overflow but I have not found an answer to this question.
How can a python script dynamically receive a url based on a javascript function call?
For example, in this Stack Overflow question (Code reproduced below) how could I dynamically receive the url (which is hardcoded in this case) if the name of the python file was abc.py and I called
xhttp = new XMLHttpRequest(); and then
xhttp.open("GET", "abc.py?token=123", true); in some html file with javascript?
from urllib.parse import urlparse
from urllib.parse import parse_qs
from urllib.parse import urlencode
url = 'http://example.com?param1=a&token=TOKEN_TO_REPLACE&param2=c'
o = urlparse(url)
query = parse_qs(o.query)
if query.get('token'):
query['token'] = ['NEW_TOKEN', ]
new_query = urlencode(query, doseq=True)
url.split('?')[0] + '?' + new_query
>>> http://example.com?param2=c&param1=a&token=NEW_TOKEN

You need to use framework to do this, python script alone with no networking/socket functionality could not communicate with the front-end (js side), below is a simple backend to received your javascript request using bottle.py
Here is a simple implementation that receives a POST request from client and do the logic you need, updated url is returned to the calling code.
Note the request is POST and the data is json with the token and url
from bottle import post, run, request
import json
from urllib.parse import urlparse
from urllib.parse import parse_qs
from urllib.parse import urlencode
def replace_token(data):
url = data['url']
token = data['token']
o = urlparse(url)
query = parse_qs(o.query)
if query.get('token'):
query['token'] = [token]
new_query = urlencode(query, doseq=True)
return url.split('?')[0] + '?' + new_query
#post('/token')
def index():
data = json.load(request.body)
return replace_token(data)
run(host='localhost', port=8080, debug=True)
Then you can test it by simple using a curl
curl -X POST http://localhost:8080/token -d '{"token":"NEW_TOKEN", "url":"http://example.com?param1=a&token=TOKEN_TO_REPLACE&param2=c"}'

Related

http GET request from python echo server using React

I have a Python echo server that sends a continuous stream of data when a client sends a GET request, as follows:
GET request for /?value=30
GET request for /?value=30
GET request for /?value=30
GET request for /?value=37
GET request for /?value=37
GET request for /?value=37
The snippet of the Python echo server, which uses the http.server library:
from http.server import BaseHTTPRequestHandler, HTTPServer
import logging
class S(BaseHTTPRequestHandler):
def _set_response(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
logging.info("GET request,\nPath: %s\nHeaders:\n%s\n", str(text), str(self.headers))
self._set_response()
self.wfile.write("get_value: GET request for {}".format(text).encode('utf-8'))
Node.js code that logged the data response above:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
function httpGet(theUrl) {
let xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.open("GET", theUrl, false);
xmlHttpReq.send(null);
return xmlHttpReq.responseText;
}
var i = 1
while (i ==1) {
console.log(httpGet('http://localhost:8080'));
}
I have successfully retrieved the data using a Node.js code however I wasn't successful in implementing it in React. How should I write a simple GET/fetch request in React? I'm very new to React and thanks for your guidance.
You can use the fetch-api to create HTTP request, here is react example:
componentDidMount() {
fetch('http://localhost:8080')
.then((res) => res.json() {
console.log(res)
})
}

How to write data to iframe via Flask POST method

I have an old application based on Python SimpleHTTPServer that I'm trying to convert to Flask.
In the old application, I had an HTML form that was submitting a POST request to the SimpleHTTPServer. The form also had an iframe. There, I had a do_POST method that was reading the values in the text boxes and producing some results. I then wrapped the results into a JSON object and wrote to the wfile method of SIMPLEHTTPServer. This caused the result to get populated into the iframe. The iframe had an onload method on the JS side and here, the results would be read from it and populated into various text-boxes.
I now want to convert this to Flask from SimpleHTTPServer. What is the best way to translate the logic I have in place to Flask? Basically, what is the equivalent of writing to the wfile object?
Also, on the Flask side, I also have some #app.route methods where I can form a URL with input parameters and get the results as JSON objects (example: http://localhost/calculate?input1=3&input2=5). Is it possible to leverage these URLs instead of the POST request to get the result into JavaScript?
Here is hello world of flask to get the data from URL parameters and do the stuff and return a json
from flask import Flask, jsonify, request
app = Flask(__name__)
#app.route('/')
def hello_world():
param1 = request.args.get('param1')
param2 = request.args.get('param2')
res = param1 + param2
return jsonify({
"result": res
})
if __name__ == '__main__':
app.run()
example request
GET http://127.0.0.1:5000/?param1=hi&param2=there
Example response
{
"result": "hithere"
}

XMLHttpRequest not being able to make a request to Flask server

I have setup a simple flask server using the following code:
from flask import Flask
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
#app.route("/")
def helloWorld():
return "Hello, cross-origin-world!"
if __name__ == '__main__':
app.run(host = '0.0.0.0', port='5000')
From js I am making a request to the address using the follwing code
const theUrl="<myip>:5000/";
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false);
xmlHttp.send();
console.log(xmlHttp.response);
The console shows
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>404 Not Found</title> <h1>Not Found</h1> <p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>
When I try to access the same url from the browser, it returns
Hello, cross-origin-world!
Is there something wrong I am doing with the server? I have tried the js code on a dummy address and I am able to get the contents of that website. There is something wrong with the Flask server.
Just wrote something for file uploads.
Hope this helps.
$('.custom-file-input').change(function () {
console.log($(this)[0].files[0].name);
$('.custom-file-label').text($(this)[0].files[0].name);
var formData = new FormData();
formData.append('file', $(this)[0].files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/', true);
xhr.send(formData)
I don't understand why one would use XHR for get requests, couldn't you just use Ajax instead?
The last parameter is whether the connection is asynchronous. Perhaps that's what wrong?
Also, don't use Flask built-in webserver for production environment, it just isn't made to cope with more than one user testing for example.
Furthermore, perhaps someone can tell me why not, however, I think you would be better off simply having url as the section of the url after the port declaration, in my example, notice that I only tell jquery or js to post data to / and this is because that means local server, or is interpreted to mean itself, so by default is prepended with your server IP and in this case the port 5000 aswell

Sending data with XMLHttpRequest

I have a website that should send a name to a python script (on a third-party website) when a button is pressed. This python script will then make the name uppercase and return it back to the website.
Right now an XMLHttpRequest is correctly being sent when the button is pressed, but I'm unsure how I correctly send the data with the XMLHttpRequest, and then how this data is accessed in the python script.
XMLHttpRequest:
document.getElementById("myButton").addEventListener("click",
function() {
var myRequest = new XMLHttpRequest();
myRequest.open('GET', 'https://example.com/');
myRequest.onreadystatechange = function () {
if (myRequest.readyState === 4) {
alert(myRequest.responseText);
}
}
myRequest.send("Bob"});
}
);
Python script:
from flask import Flask, jsonify
from flask_cors import CORS
from requests import request
app = Flask(__name__)
CORS(app)
#app.route("/", methods=["GET"])
def hello_world():
return jsonify(name = (name_sent_by_XMLHttpRequest).upper()) # Should return "BOB"
if __name__ == '__main__':
app.run()
I know nothing about javascripts' XMLHTTPRequest but at some point, you need to send the name to the python server, right? HOW to do that is up to you, but a GET based option:
GET request with args: https://example.com/?name=your_name_goes_here
in your flask app, the function listening on route "/" will now have access to that arg, something like
name = request.args.get('name', '')
then you can uppercase() it, and return it in some format - probably XML ?
return Response(my_xml, mimetype='text/xml')
Update based on your comment: usually in a flask function, you would use the flask request object to get your URL parameters. In your example, you're importing the requests module as request, not using it, but clobbering the flask.request namesspace. Change your imports to something like this, and it should work normally:
from flask import Flask, jsonify, request
from flask_cors import CORS
import requests

Request post pasing JSON using cherrypy python

I am trying send json in request post to python using cherrypy. When I send the request, the response is (400 bad request, Invalid JSON document), nevertheless using postman i make the same request and the server return the result withou errors.
My python code:
import time, sys, cherrypy, os
import json
import ML_Training
import ML_Unsup_Predictor_Results
class Application(object):
#cherrypy.expose
#cherrypy.tools.json_in()
def predict(self):
try:
cherrypy.response.headers["Access-Control-Allow-Origin"] = "*"
cherrypy.response.headers['Content-Type'] = "application/json"
input_json = cherrypy.request.json
r = ML_Unsup_Predictor_Results.Predict_New_Values(input_json["model"], input_json["value"])
return json.dumps(r)
except Exception as e:
print e.message
return e.message
In javascript my request post using angularjs
$http.post(mlService.getMlMultitenancyOrigin() + '/python/predict',
{"model":$scope.params[2], "value": arr}).then(function(result){
console.log(result);
})
note: the structure of arr is arr = [1,2,3,4] (array of integers)
My question is why "invalid JSON"
attached image of postmant, when the result is ok

Categories

Resources