julixw
julixw

Reputation: 43

404 when try to post some text into my webserver with python and flask

I am still very new to Python, just know some basic stuff bout it. I have built a small web application that takes input from a web server and sends it to the backend, which stores everything in a database. Everything is already running so far (via Docker), but when I want to make an entry, I get the following error message back (i guess my webserver got some issues):

[![404 post issue][1]][1]

i went through frontend to backend and looked over my post method - but it seems ok for me. Or am i blind to see the issue?

I will post the Code below, so u can see what i mean :)

<body>
<h1>Willkommen in der Test App</h1>
<form action="/api/data" method="POST">
  <label for="inputText">Text eingeben:</label>
  <input
    type="text"
    id="inputText"
    name="inputText"
    placeholder="z.B. Hallo Welt"
  />
  <button type="submit">Absenden</button>
</form>

Middleware Code:

from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/categorize', methods=['POST'])
def categorize():
  data = request.get_json()
  input_text = data.get("inputText", "").lower()
  if "error" in input_text:
      category = "Error"
  else:
      category = "General"

return jsonify({"category": category}), 200

if __name__ == '__main__':
  app.run(host='0.0.0.0', port=6000, debug=True)

And the POST method in my Backend Code:

@app.route('/api/data', methods=['POST'])
def receive_data():
input_text = request.form.get('inputText')
if not input_text:
    return "Fehlender 'inputText' im Formular.", 400

try:
    # An Middleware schicken zur Kategorisierung
    response = requests.post("http://middleware:6000/categorize", 
json={
        "inputText": input_text
    })
    if response.status_code != 200:
        return "Fehler in Middleware-Antwort", 500

    category = response.json().get("category", "Unkown")

    conn = psycopg2.connect(**db_config)
    cur = conn.cursor()
    insert_query = "INSERT INTO requests (text, category) VALUES 
    (%s, %s);"
    cur.execute(insert_query, (input_text, category))
    conn.commit()
    cur.close()
    conn.close()

    return f"Eingegangen und gespeichert: '{input_text}' mit 
    Kategorie '{category}'", 200

except Exception as e:
    return f"Fehler bei der Verarbeitung: {str(e)}", 500

This is my default.conf file:

server {
listen 80;
server_name localhost;

# Statische Dateien (HTML, CSS, JS)
location / {
    root /usr/share/nginx/html;
    index index.html;
}

# Proxy für alle API-Aufrufe => Backend
location /api/ {
   proxy_pass http://backend:5000/;
   proxy_http_version 1.1;
   proxy_set_header Host $host;
}

}

my url after the post is: http://localhost/api/data

Hope someone can give a nice hint to fix it :)

Upvotes: 0

Views: 59

Answers (2)

efeakaroz13
efeakaroz13

Reputation: 143

It is about the way you run the flask application. Try using gunicorn with this command to run

gunicorn -w 3 app:app

In a production setup, you can use Gunicorn, supervisorctl, and nginx and set them up relatively easily.

Upvotes: -2

malyshchyk
malyshchyk

Reputation: 103

The problem might be in the URL you use in the HTML form. I don't know your exact setup, but depending on the place where you host your backend you may try http://service_name:6000/api/data (for docker-compose) or http://localhost:6000/api/data (if running everything locally), instead of just /api/data. 404 means that the page is not found, so fixing the URL should resolve the communication issue

Upvotes: 0

Related Questions