Issue
Hello I am having a hard time trying to get my survey app to work. Run I run the flask app it gives me a couple of errors.
Failed to load resource: the server responded with a status of 404 (NOT FOUND) :5000/favicon.ico:1
Failed to load resource: the server responded with a status of 500 (Internal Server Error) :5000/test:1
This is the error in the terminal
Traceback (most recent call last):
File "/Users/tannerormanoski/opt/anaconda3/lib/python3.9/site-packages/flask/app.py", line 2447, in wsgi_app
response = self.full_dispatch_request()
File "/Users/tannerormanoski/opt/anaconda3/lib/python3.9/site-packages/flask/app.py", line 1952, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/Users/tannerormanoski/opt/anaconda3/lib/python3.9/site-packages/flask/app.py", line 1821, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "/Users/tannerormanoski/opt/anaconda3/lib/python3.9/site-packages/flask/_compat.py", line 39, in reraise
raise value
File "/Users/tannerormanoski/opt/anaconda3/lib/python3.9/site-packages/flask/app.py", line 1950, in full_dispatch_request
rv = self.dispatch_request()
File "/Users/tannerormanoski/opt/anaconda3/lib/python3.9/site-packages/flask/app.py", line 1936, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/Users/tannerormanoski/Documents/Survey_2/Input_Saving_Test/app.py", line 21, in test
result = json.load(output) # This converts the json output to a python dictionary
File "/Users/tannerormanoski/opt/anaconda3/lib/python3.9/json/__init__.py", line 293, in load
return loads(fp.read(),
AttributeError: 'list' object has no attribute 'read'
127.0.0.1 - - [20/Sep/2022 08:45:15] "POST /test HTTP/1.1" 500 -
127.0.0.1 - - [20/Sep/2022 08:45:45] "GET /test HTTP/1.1" 405 -
This is my app.py
import json
from flask import request
from flask import Flask, render_template
app = Flask(__name__,
static_folder='static',
template_folder='templates')
@app.route('/')
def index():
return render_template('index.html')
@app.route('/test', methods=['POST'])
def test():
output = request.get_json()
print(output) # This is the output that was stored in the JSON within the browser
print(type(output))
result = json.load(output) # This converts the json output to a python dictionary
print(result) # Printing the new dictionary
print(type(result)) # This shows the json converted as a pyhthon dictionary
return result
if __name__ == "__main__":
app.run(debug=True)
This is the snippet from my app.js file
let persons = [];
const addPerson = (ev)=>{
ev.preventDefault(); //stop form from submitting
let person = {
name: document.getElementById("name").value,
title: document.getElementById("title").value,
role: document.getElementById("role").value,
reports: document.getElementById("reportsTo").value,
fact: document.getElementById("funFact").value
}
persons.push(person);
document.forms[0].reset(); // to clear the form for the next entries
//for display purposes only
console.warn('added' , {persons} );
let pre = document.querySelector('#msg pre');
pre.textContent = '\n' + JSON.stringify(persons, '\t', 2);
$.ajax({
url: '/test',
type: "POST",
contentType: "application/json",
data: JSON.stringify(persons)
});
It seems to be where '/test' app route, as in the url in the app.js file it does not underline the link as it normally would. I am newer to coding and very new with flask, so I am having trouble diagnosing the problem myself.
If it helps my file structure is
>static
app.js
style.css
>Images
>templates
index.html
app.py
Solution
Your templates folder is expecting only template files (.html files). It's standard to have your app.py file in the root of your project. Your structure should look like this. Same w/ your app.js file.
>static
style.css
>Images
>templates
index.html
app.py
app.js
https://flask.palletsprojects.com/en/2.2.x/tutorial/layout/
Edit1: Also, it may not be valid to return the python dictionary like that. Try creating a response before returning, I've had to use this when returning pdf files, etc.
from flask import json
@app.route('/test', methods=['POST','GET])
def test():
output = request.get_json()
print(f'output: {output}, output type: {type(output)}')
response = app.response_class(
response=json.dumps(output),
status=200,
mimetype='application/json'
)
return response
reference material: Return JSON response from Flask view
Answered By - Andrew Clark
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.