flask endpoint which is defined returns 404 - python

from flask import Flask, jsonify, request
app = Flask(__name__)
app.users = {}
app.id_count = 1
#app.route("/ping", methods = ['GET'])
def ping():
return "pong"
#app.route("/sign-up",methods = ['POST'])
def sign_up():
new_user = request.json
new_user["id"] = app.id_count
app.users[app.id_count]= new_user
app.id_count = app.id_count +1
return jsonify(new_user)
if __name__ =='__main__':
app.run()
I tried to send a HTTP request to endpoint /sign-up which is defined as above,
127.0.0.1 - - [22/Nov/2021 22:02:02] "POST /sign-up HTTP/1.1" 404 -
It seems like a really simple problem and I don't see it.

I was running these on WSL2 ubuntu. (both server and client)
and I eventually tried running this on my Windows Pycharm which is not a virtual machine, and it worked fine.
I wonder why /ping works fine tho, will be finishing this course on ordinary windows from now on for sure

Related

Flask - The browser (or proxy) sent a request that this server could not understand

Yesterday I started getting this error and just can't figure out what it might be. I cut my Flask API down to the bare minimum and it is still not working.
Here is my file structure (excluding requirements.txt and .ebextensions/python.config):
modules/
test.py
application.py
Here is application.py
from flask import Flask
from flask_restful import Resource, Api, reqparse
import modules.test
application = Flask(__name__)
api = Api(application)
class test(Resource):
def get(self):
parser = reqparse.RequestParser()
parser.add_argument('string', required=True)
args = parser.parse_args()
try:
response = modules.test.run(args['string'])
return response
except Exception as e:
return "400 | " + str(e)
pass
api.add_resource(test, '/test')
if __name__ == '__main__':
application.run(host="0.0.0.0", port="8080", debug=True)
Here is test.py
def run(string):
return string
When I try on my local system, everything is working fine. When I deploy this to my AWS Elastic Beanstalk enviroment and make a request like:
https://example.com/test?string=hello
I get this response:
{
"message": "The browser (or proxy) sent a request that this server could not understand."
}
I cannot figure out what might be causing this issue. I have also tried deploying on DigitalOcean but it is the same. This has been working fine forever and suddenly it breaks.
Any help is greatly appreciated!

IIS returning 500 Internal Server Error for POST but working for GET- Flask

I am facing an issue with my flask program.
I hosted a flask application on IIS running on Win 11. But from Postman I am Getting Get response but 500 error when Methos = POST.
But there is no error when running the same code from VS Code.
My Flask code:
import decodedata
import Call_printer
from flask import Flask, request, render_template,jsonify
app = Flask(__name__)
#app.route('/print',methods = ['GET','POST'])
def printer():
if request.method == 'POST':
req_data = request.json
print(req_data)
data = req_data['data']
printername= req_data['printername']
xml = decodedata.decode_xml(data)
msg = Call_printer.sendprintjob(printername,xml)
status={"Status":msg}
return jsonify(status)
if request.method == 'GET':
return "Hello World."
if __name__ == '__main__':
app.debug = True
app.run()
Below is an error when running from IIS.
Error in IIS
Below is the correct POST Response from VS CODE
Success in VS Code
But I am receiving responses in GET method from IIS. Only for POST, I am receiving 500 error?
Can it be because I am calling other py files for POST?
Any idea how can I fix it?
Regards,
Mayank Pande

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.

Route doesn't exist

I have the following code on my service and when requested the return is always 404.
#app.route('/v1/auth/service', methods=['POST'])
def verifyAuthService():
data = request.get_json()
But in the log file, the service returns 404.
127.0.0.1 - - [TIMEVALUE] "POST /v1/auth/service HTTP/1.1" 404 -
But it works when I use other route. I have checked if the route path or method name are duplicated and didn't find anything.
I request the service method with the following code:
r = requests.post("http://myservice.com:5001/v1/auth/service", json=jPayload)
Maybe was a newbie error, in my init.py file, I haven't imported auth_services.py.
The /v1/auth/service route wasn't interpreted by python so, the route was inaccessible.
Can you try building the URL with below code and match if the route is pointing to exactly same URL which you have called.
from flask import Flask, url_for
app = Flask(__name__)
#app.route('/v1/auth/service', methods=['POST'])
def verifyAuthService():
data = request.get_json()
with app.test_request_context():
print url_for('verifyAuthService')
Hope this helps!

Python Requests package hits url twice

I am trying to create a synonym list for words by hitting a synonyms api. I am using Flask and the requests package.
I am calling this function only once after grabbing information from a webform via a flask route.
Code:
import requests
from flask import Flask, request, render_template, flash
import environment
app = Flask(__name__)
#app.route("/", methods=["GET", "POST"])
def index():
if request.method == "POST":
keywords = request.form["key1"]
synonyms = syn_look(keywords)
return render_template("index.html", syns=synonyms)
return render_template("index.html")
def syn_look(word):
URL = "http://words.bighugelabs.com/api/2/%s/%s/json"
request_url = URL %(environment.thesaurus_api_key, word)
r = requests.get(request_url)
print r.status_code
if __name__ == "__main__":
app.debug = False
app.run()
The status prints twice
output:
* Restarting with reloader
* Detected change in 'server.py', reloading
* Restarting with reloader
127.0.0.1 - - [10/Jan/2014 17:22:03] "GET / HTTP/1.1" 200 -
200
404
Are you certain you're formatting request_url correctly?
You can see in the GET request, a 404 is printed on the last line. This is the HTTP 404 Error, file not found. I'm betting this is why you see the 'reloading' messages in the console output.

Categories

Resources