Forums

Flask route "/test" fails when clicking html form submit button

This is my homepage which is produced using render_template This is for "/" produced using welcome.html render template which uses the URL:

<form action="http://smspython.pythonanywhere/test" method="POST">
    <input type="submit" value="Download a .xlsx copy to your machine" name="submit">
</form>

I get the error "Site can't be reached when I click the button". Note I have updated my website URL to replace localhost when I was testing flask.

import pyodbc
import pandas as pd
from flask import render_template,request, make_response,Flask
from io import BytesIO

app = Flask(__name__)

@app.route('/')
def sms_page():
    return render_template('welcome.html') #this isn't showing logo

@app.route('/test')
def test():
    return "<h1>You have met your endpoint i.e test :)</h1>" #this route is really failing me, i am confused

if __name__ == '__main__':
    app.run(debug=True)

Not sure what I am really missing for /test to not work?

Second issue: my logo is not being displayed. Pretty sure this is the correct path /home/SMSPython/mysite/static/my_logo.jpg :?

<img src="/home/SMSPython/mysite/static/my_logo.jpg" alt="logo" width="155" height="70">

Thanks for your guidance and helping me on journey of learning web dev :)

For the form submission problem, you have http://smspython.pythonanywhere/test in the action, which is missing the ".com". It should be http://smspython.pythonanywhere.com/test.

For the logo problem, you'll need to set up a static file mapping to make that file be accessible for people browsing your website.

Thank you so much, it worked for simple string (silly me, missing ".com"). However, when I try to do this with dataframe i get internal error 500. Why is this the case now?

@app.route('/get_data',methods=['GET','POST'])
def product_df():
    if request.method == 'POST':


        #as html listbox

        df = pd.DataFrame({"x":[1,2],"y":[1,2]})

        output = BytesIO()
        writer = pd.ExcelWriter(output, engine='xlsxwriter')
        df.to_excel(writer)
        writer.close()
        resp = make_response(output.getvalue())
        resp.headers["Content-Disposition"] = "attachment; filename=my_file.xlsx"
        resp.headers["Content-Type"] = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        return resp

Maybe .xlsx not supported and csv is?

Are you making a POST or GET request?

Hi, sorry for getting back to you late.

POST request. Otherwise, i don't believe request.method == 'POST' will work even on localhost.

Look in your error log to see what the exception traceback is so you can work out what is actually failing and how.

I was using Dataframe instead of pascal casing DataFrame ...

Glad you found the problem!