Python flask error code 400, message Bad request version - python

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")

Related

In Flask ignore all webhooks but one

I have a python script with flask incorporated running on a RaspberryPi. This is set to trigger a wakeonlan script when IFTTT sends the appropriate POST webhook. Since I've turned it on I've been getting a LOT of random webhooks from random IPs. Obviously, they all get a 404 error as nothing else is active, but it still concerns me a bit.
Is there a way to make flask ignore (just completely not respond) to any webhooks that aren't the specific one (a POST to /post) I'm looking for? I've tried screwing with the return line, but then flask throws an error saying "View function did not return a response" and returns an error 500.
Is this even possible?
#!/usr/bin/env python3
from flask import Flask, request
from wakeonlan import send_magic_packet
from datetime import datetime
app = Flask(__name__)
dt = datetime.now()
print("WakeOnLan started at: ", dt)
#app.route('/post', methods= ["POST"])
def post():
print("POST received at: ", dt)
body = request.get_data(as_text=True)
if body == "desktop":
send_magic_packet('XX.XX.XX.XX.XX.XX')
print("Magic Packet sent to", body, "at:", dt)
return ''
#Router forwards port 80 to 30000 on the pi
app.run(host='0.0.0.0', port = 30000)

Fastapi returns 404 when accessing URL in the browser

I am learning fastapi and created the sample following application
from fastapi import FastAPI
import uvicorn
app = FastAPI()
#app.get("/hello")
async def hello_world():
return {"message": "hello_world"}
if __name__== "__main__":
uvicorn.run(app, host="127.0.0.1", port=8080)
The server starts fine but when I test the url in browser I am getting the following error:
{"detail": "Not Found"}
and this error in the log:
"GET / HTTP /" 404 Not Found
I noticed another weird problem, when I make some error its not detecting the error and still starting the server. For example if I change the function like the following
#app.get("/hello")
async def hello_world():
print (sample)
return {"message": "hello_world"}
It should have thrown the error NameError: "sample" not defined but it still is starting the server. Any suggestions will be helpful
always add the trailing slash after the path, had the same issue, took me hours to debug
Question 1: It doesn't work. You code a handler for path /hello. But you are testing path / which is not configured.
Question 2: You didn't define the variable sample.

Python (Flask) print unwanted line at the end of output

I want to use a perfecely simple flask (v=1.0.2) app to subscribe to a PubSub hub, where the hub would send a GET request containing a challenge string, and my flask app is suppose to return the string and do nothing more. However, it keeps outputting a messy line at the end, which I assume to be info on the GET request itself, and I am having difficulty understanding how it comes about. Could anyone explain how I can get rid of it please? My codes and the output are below. Thanks a lot.
from flask import Flask, request
app = Flask(__name__)
#app.route('/', methods=["GET", "POST"])
def index():
# get request used to subscribe to webhook
if request.method == 'GET':
print(datetime.datetime.now())
challenge = request.args['hub.challenge']
return challenge
if __name__ == '__main__':
app.run(host='0.0.0.0', port="80")
The output lines are below, and I would like to get rid of the 2nd line please:
2020-06-08 15:38:30.135647
198.12.103.36 - - [08/Jun/2020 15:38:30] "[37mGET /?hub.mode=subscribe&hub.topic=https%3A%2F%2Fblog.xxx.com%2Ffeed&hub.challenge=u9bs6yja251eeraa714i&hub.lease_seconds=1296000 HTTP/1.1[0m" 200 -

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

AJAX POST Receives 404 Error

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

Categories

Resources