Flask 500/404 errors - flask

I'm experiencing an error with Flask. If I call the #app.route with the function, I retrieve 404 Not Found:
from flask import Flask, request
import requests
app = Flask(__name__)
#app.route('/webhook', methods=['GET', 'POST'])
def webhook():
return 'Hello!'
if __name__ == '__main__':
app.run("0.0.0.0", port=10101, debug=False)
However, if the function is not mentioned, I retrieve the 500 Internal Server Error:
from flask import Flask, request
import requests
app = Flask(__name__)
#app.route('/', methods=['GET', 'POST'])
def webhook():
return 'Hello!'
if __name__ == '__main__':
app.run("0.0.0.0", port=10101, debug=False)
Any help, please?

Your code runs fine. I just copy-pasted your original example and did a curl request to it with:
curl -X GET http://localhost:10101/webhook
curl -X POST --data "test=true" http://localhost:10101/webhook
Both return Hello!%
As suggested by #Sebastian Speitel - try enabling debug mode - that will give you an idea of what fails and why:
app.run("0.0.0.0", port=10101, debug=True)

Related

Getting 400 Bad Request from Open AI API using Python Flask

I want to get response using Flask from OpenAI API. Whether I am getting Status 400 Bad Request from Browser through http://127.0.0.1:5000/chat
Bad Request
The browser (or proxy) sent a request that this server could not understand.
Also I am checking this from Postman
from flask import Flask, request, render_template
import requests
app = Flask(__name__)
#app.route('/')
def index():
return 'Welcome to ChatGPT app!'
#app.route('/chat', methods=['GET', 'POST'])
def chat():
user_input = request.form['text']
# Use OpenAI's API to generate a response from ChatGPT
response = generate_response_from_chatgpt(user_input)
return response
def generate_response_from_chatgpt(user_input):
api_key = "YOUR_API_KEY"
url = "https://api.openai.com/v1/engines/davinci/completions"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
data = {
"prompt": user_input,
"engine": "davinci"
}
response = requests.post(url, headers=headers, json=data)
return response.json()["choices"][0]["text"]
if __name__ == '__main__':
app.run()
It would be best if you check the openai documentation to make sure you are using the correct endpoint and data format in your request.
Also, you should check your API key, if it is correct and if you have reached the limit of requests.
Also, it's worth noting that the code you provided is missing the import statement for Flask. You will need to add the following line at the top of your file:
from flask import Flask, request
Also, I see that you're using request.form['text'] but you should check if the request is a GET or POST request.
if request.method == 'POST':
user_input = request.form['text']
else:
user_input = request.args.get('text')
This is to avoid a KeyError being raised when the request is a GET request.

Telebot not responding to requests with FLask server

I am trying to deploy my telegram bot to Heroku using Flask. ALthough I followed the tutorials and set up everything the same I am not getting any result and my bot is not responding.
import requests
import pandas as pd
import telebot
from telebot import types
import random
import os
from flask import Flask, request
from requests.models import MissingSchema
URL_HEROKU = f"some_url"
TOKEN = os.environ['TOKEN']
bot = telebot.TeleBot(TOKEN, parse_mode=None)
app = Flask(__name__)
#bot.message_handler(commands=['start'])
def start(message):
#Init keyboard markup
msg = ''' Hello, how are you?'''
bot.reply_to(message, msg)
#bot.message_handler(commands=['random'])
#bot.message_handler(regexp=r'random')
def send_some(message):
bot.send_message(message.chat.id, text='Hello')
#app.route('/' + TOKEN, methods=['GET'])
def getMessage():
bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode("utf-8"))])
return "!", 200
#app.route("/")
def webhook():
bot.remove_webhook()
bot.set_webhook(url= URL_HEROKU + TOKEN)
return "!", 200
if __name__ == "__main__":
app.run(host="0.0.0.0", port=int(os.environ.get('PORT', 5000)))
My Procfile is:
web: python telebreed.py
and my requirements.txt:
Flask==2.0.2
gunicorn==20.1.0
pandas==1.2.2
pyTelegramBotAPI==4.6.0
requests==2.26.0
do you see any mistake ? When I open my app in Heroku I only see "!" which is the character defined in getMessage() method.

Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again

When I run this, 404 error is been shown. Please help me solving this:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "<h1> Hello Puppy! </h1>"
#app.route("/information")
def info():
return "<h1> Puppies are Cute </h1>"
#app.route("/Puppy/<name>")
def puppy(name):
return "<h1> This is a page for {} </h1>".format(name)
if __name__ == '__main__':
app.run()

requests.get does not response in python?

I have the following script which I tried to get response status from request.get(url)
from flask import *
import requests
app = Flask(__name__)
#app.route('/')
def home():
r = requests.get('http://127.0.0.1:5000/welcome')
print r
return render_template('home.html')
#app.route('/welcome')
def wecome():
print "welcome page"
return "welcome to my page"
if __name__=='__main__':
app.run(debug=True)
When I access endpoint http://127.0.0.1:5000/ the browser keeps spinning none stop without any output result in terminal console as I expected even the error message.
However, if I change the requests url to something else externally as below, the response is showing up the status <Response [200]> in terminal and the page is loaded as normal.
from flask import *
import requests
app = Flask(__name__)
#app.route('/')
def home():
r = requests.get('https://api.github.com/emojis')
print r
return render_template('home.html')
#app.route('/welcome')
def wecome():
print "welcome page"
return "welcome to my page"
if __name__=='__main__':
app.run(debug=True)
what's going on with that?
How can I get response from internal url as I need it badly for my current work?

Invalid request block size when using SocketIO with Flask and uWSGI

I'm trying to run a Flask application with SocketIO using uWSGI and gevent.
uwsgi --gevent 10 --socket :5000 --module run
However, I get the following error:
invalid request block size: 21573 (max 4096)...skip
This is my code:
from gevent import monkey
monkey.patch_all()
from flask import Flask, render_template, session, request
from flask.ext.socketio import SocketIO, emit, disconnect
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
application = app
socketio = SocketIO(app)
#app.route('/')
def index():
session['user'] = '1'
return render_template('index.html', name='simon')
#socketio.on('my event', namespace='/test')
def test_message(message):
emit('my response', {'data': message['data']})
#socketio.on('connect', namespace='/test')
def test_connect():
emit('my response', {'data': 'Connected %s' % session['user']})
#socketio.on('disconnect', namespace='/test')
def test_disconnect():
print('Client disconnected')
if __name__ == '__main__':
app.debug = True
socketio.run(app)
The problem is that you are using binary uwsgi protocol but accessing your server via http protocol. Try replacing --socket with --http-socket. See also https://stackoverflow.com/a/32894820/179581
My understanding is that the gevent support in uWSGI does not allow a custom gevent server class to be used, uWSGI provides its own. Unfortunately gevent-socketio needs its own server, which is subclassed from gevent's, so I think it is currently not possible to use uWSGI with Flask-SocketIO or gevent-socketio.
See the Flask-SocketIO documentation for alternatives.