AJAX POST Receives 404 Error - python

Trying to use AJAX to POST to my Python script testing.py. Whenever I try the POST, I receive the following error.
POST http://localhost:5000/testing.py 404 (NOT FOUND)
I'm using Flask to serve up my website. Why is this a 404 error, and how do I get localhost to serve my python script?

somewhere you should have a file called app.py,(but you can call it testing.py if you want) inside should be at least:
from flask import Flask, request
app = Flask(__name__)
#app.route('/testing') # you can probably even put testing.py here
def testing():
vars = request.args
return ','.join(map(str,vars))
if __name__ == "__main__":
app.run()
then
python app.py # or testing.py
then you can send your POST to http://localhost:5000/testing
and it will print any posted parameters to the browser

Related

Web server in python for responding to GET and POST

I want to create web server, and listen now.
Server must have different functions for each endpoint (and method).
I want to get (e.g. to variable) parameters (and data if POST)
Respond to get (and POST if its possible)
Respond in JSON
Someone can help me with this?
PS: I will be run it on Heroku, and send requests to it via Roblox's HttpService
Below see examples of each of your requirements using the Flask lightweight web framework.
After that is a link to a short description of how to deploy to Heroku.
# app.py
from flask import Flask
from flask import request, render_template
app = Flask(__name__)
#app.route('/test-get-request-parameters')
def test_get_request_parameters():
# 1. different function per endpoint
# 2. GET parameter to variable
# 3. respond to GET
var = request.args.get('some_request_variable')
return render_template('hello_world.html')
#app.route('/test-post-method',methods=['POST'])
def test_post_method():
# 2. receive POST data
# 3. respond to POST
print(request.get_json())
return 'hello, world!'
#app.route('/test-get-or-post', methods=['GET','POST'])
def test_get_or_post():
# 4. respond in JSON
if request.method == 'POST':
d = {'hello':'world'}
return d # this will be JSON response
return render_template('test.html')
To deploy to Heroku you need a Procfile with something like this in it:
web: gunicorn app:app
And you can follow these instructions: https://devcenter.heroku.com/articles/getting-started-with-python

Python flask error code 400, message Bad request version

The code of the website
from flask import *
app = Flask(__name__)
#app.route("/<name>")
def user(name):
return f"Hello {name}!"
#app.route("/")
def home():
return render_template("index.html")
#app.route("/admin")
def admin():
return redirect(url_for("home"))
if __name__ == "__main__":
app.run()
If I go to http://127.0.0.1:5000/ there are not issues but when I go to https://127.0.0.1:5000/ (https not http this time) I get the following error
127.0.0.1 - - [17/Nov/2019 17:43:25] code 400, message Bad request version ('y\x03Ðã\x80¨R¾3\x8eܽ\x90Ïñ\x95®¢Ò\x97\x90<Ù¦\x00$\x13\x01\x13\x03\x13\x02À+À/̨̩À,À0À')
The error code 400, message Bad request version is basically what I expected since I have not set up SSL nor have I declared what the website should do when getting a https request. What I am curious to find out is what the weird symbols mean (y\x03Ð.... and so on). This goes out to multiple questions such as: Where do they come from? Have the python code attempted to access a random memory location with no specific data? Is the data just in a format that the console cannot handle? What does it mean? You get the idea.
You're missing the ssl_context in app.run() which configures Flask to run with HTTPS support.
See the this article about it
If this is just for testing, you can use adhoc mode.
if __name__ == "__main__":
app.run(ssl_context="adhoc")

Unable to request the status code of localhost

I am using python and flask to create a web API. However I am getting trouble in requesting the HTTP status code of my localhost.
My code:
import requests
import flask
app = flask.Flask(__name__)
app.config["DEBUG"] = True
#app.route('/home', methods=['GET'])
def home():
r = requests.get(url="http://localhost:5000/home")
print(r.status_code)
return "Welcome!"
app.run()
Before adding the line for requesting status code, it works fine in my browser (Chrome) and the command prompt show something like this:
127.0.0.1 - - [19/Sep/2019 01:03:54] "GET /home HTTP/1.1" 200 -
After adding the line for requesting, it keeps loading (forever) in my browser and no response in the command prompt.
I have no idea about this problem because it did not show any error and I have read some of the solutions mentioned in other similar problems (like disabling proxy) but it seems not working for me.
Thanks!
Look at it from the point of view of the app. It gets a request for /home and routes it to home(). While servicing that request, the app makes a request for /home, which routes to home(). During the servicing of that request... and so on until some resource is exhausted.
If you intent is to prove that you can make a request to the app from within the app, target a different endpoint.

Execute . python script from Angular JS using Flask

I am trying to execute a python script from flask. I understand I need to run it on a server. I am creating this for chrome extension, so I am wondering if that's even possible to run a server everytime we need it. Furthermore, this is my code to send the request:
var url = './app.py';
$http.get(
url,
{
params: {'id': "eminem"}
})
.success(function (data) {
console.log("data");
})
.error(function (error) {
console.log("error");
});
and the python code would be:
from flask import Flask, render_template, Response, request, redirect, url_for
app = Flask(__name__)
#app.route('/data', methods=['POST'])
def getData():
return "db"
if __name__ == "__main__":
app.run()
Any ideas what I might be doing wrong? The error I am getting is that the server cannot locate the file.
In your Flask server you are declaring the method route as /data so you should be able to call it by localhost:5000/data (I am assuming that you are running the server in your computer with the default Flask port).
For doing that you should change your first line in your JS code like:
var url = 'localhost:5000/data';
Remember that you are requesting an url not a python file, it works different in php for example.

Heroku - Python simple POST api, only can do GET (cannot do POST)

I want to do a web API which consist only POST. Currently I need to run python script on the web, so I am building a python web server from flask in Heroku. However, my issue is, whenever I send POST request from POSTMAN, what I will receive is the return data which is actually from GET request. Below is my code:
from flask import Flask
from flask import request
import os
app = Flask(__name__)
#app.route("/", methods=['GET', 'POST'])
def api_grab_key():
if request.method == 'POST':
if request.headers['Content-Type'] == 'application/json':
return request.json["imgUrl"]
else:
return "Request must be in JSON"
if request.method == 'GET':
return "Hello World! GET request"
if __name__ == "__main__":
port = int(os.environ.get('PORT', 33507))
app.run(host='0.0.0.0', port=port)
It works when I run locally, but not on Heroku. On Heroku, the output is always "Hello World! GET request" Thanks!
Sorry, apparently my issue is in the URL. So in Heroku, it has xxx.heroku.com and xxx.herokuapp.com.
I don't know why, requests sent to xxx.heroku.com turns into GET request. So, I had to change it to xxx.herokuapp.com for POST request.
I don't see anything jumping out, have you tried enabling debugging mode in Flask?
app.run(debug=True)
Then:
heroku logs --tail

Categories

Resources