Cloud 9 and Flask: Attempting to submit at '/' URL redirects to /localhost

flask
python

#1

Hello, everyone!

I’m trying to use Cloud 9 to put together a demo project that has two text fields. One is for the user’s name and the other for their age. There are two buttons, ‘add’ and ‘retrieve’ that add the name/age to the database and retrieve a name/age from the database randomly.

I have my project routed to /, so it appears at the default project-username.c9users.io:8080 directory. When I type something in and hit submit/add, it redirects to project-username.c9users.io:8080/localhost/?name=blah&age=2398&submit=add for inputs 'blah' and 2398. Thus, it goes to a 404 page. I don’t understand why it is doing this.


Here is my code in its entirety.

import os
import sqlite3

from flask import Flask
from flask import request
from flask import render_template
from flask import g

app = Flask(__name__)

@app.route('/', methods=['POST', 'GET'])
def people():
    error = None
    if request.form.get('submit', None) == "add":
        if request.method == 'POST':
            if request.form['name'] and request.form['age']:
                name = request.form['name']
                age = request.form['age']
        
                database = connect_db()
                cursor = database.cursor()
                sql = "INSERT INTO person (name, age) VALUES ({0}, {1});".format(name, age)
        
                cursor.execute(sql)
                database.commit()
        
                return render_template("index.html")
            else:
                error = "Name or age not provided."
                return render_template('index.html', error=error)
    elif request.form.get('submit', None) == "retrieve":
        if request.method == 'GET':
            database = connect_db()
            cursor = database.cursor()
            sql = "SELECT * FROM person ORDER BY RANDOM() LIMIT 1;"
    
            cursor.execute(sql)
            result = cursor.fetchone()

            return render_template("index.html")
    return render_template("index.html")

def connect_db():
    db = getattr(g, '_database', None)
    if db is None:
        connection = sqlite3.connect("./people.db")
        db = g._database = connection
    return db
    
@app.teardown_appcontext
def close_connection(exception):
    db = getattr(g, '_database', None)
    if db is not None:
        return db.close()


if __name__ == "__main__":
    app.run(host=os.getenv('IP', '0.0.0.0'),port=int(os.getenv('PORT', 8080)))

It’s SUPPOSED to enter this information into the database and then return back to this page to allow the user to do it again. How do I do that?

Thank you very much!