This question already has answers here:
Flask view raises TypeError: 'bool' object is not callable
(1 answer)
Return JSON response from Flask view
(15 answers)
Closed 5 years ago.
I'm trying to using Flask Blueprint to make routes from another file. This is my "catalog.py file:
from flask import Blueprint, make_response, render_template
from models.catalog import Catalog
catalog_url = Blueprint('catalog_url', __name__)
#catalog_url.route("/")
#catalog_url.route("/catalog")
def show_all_catalogs():
try:
catalogs = Catalog.find_all_catalogs()
return render_template('publiccatalogs.html', catalogs=catalogs)
except:
return {'message': 'Internal Server Error'}, 500
This is my "app.py" file:
from catalog import catalog_url
app = Flask(__name__)
app.register_blueprint(catalog_url)
But when I enter "localhost:5000/catalog", it returns this error:
TypeError: 'dict' object is not callable
I tried returning plain text and even JSON, they worked just fine. But when I try to use "render_template", I keep getting the same error.
There is try except, your code return render_template('publiccatalogs.html', catalogs=catalogs) is correct. However, I suspect the html template cannot be found, and then this exception happen, it goes to except return {'message': 'Internal Server Error'}, 500 this part format is not correct.
In Flask, a view must return one of the following:
a string
a Response object (or subclass)
a tuple of (string, status,headers) or (string, status)
a valid WSGI application
Related
This question already has answers here:
How to run a flask application?
(6 answers)
Closed 2 years ago.
I am following the flask quickstart to create a python server so that I can send data from postman to the server. However, when I run the code using "python main.py", nothing happens in the command line. What am I doing wrong?
Code:
from flask import Flask, request
from flask_restful import Resource, Api
from server import analyzeWeaknesses
app = Flask(__name__)
api = Api(app)
#app.route('/analyzeWeaknesses', methods=['POST'])
def WeaknessAnalysis():
if request.method == 'POST':
analyzeWeaknesses(request.data)
return {"status":"success"}
else:
error = 'Unable to access data!'
analyzeWeaknesses simply takes in an input and does an analysis of it and outputs integers. I would like this output to be also returned to postman. Desired outcome Postman to for python input and then receive its output
You're missing the main function. Add this at the bottom of your code-
if __name__ == '__main__':
app.run()
I am working on Flask App that uses MongoDb and I am getting this: "NoneType' object has no attribute 'isatty'". I have been researching and saw that some people resolved this by installing Anaconda 64 bit. However I am already running 64bit version on window 10.
The code for my flask app is:
from flask import Flask, render_template, jsonify, redirect
from flask_pymongo import PyMongo
import scrape_mars
# create instance of Flask app
app = Flask(__name__)
app.config["MONGO_URI"] = "mongodb://localhost:27017/mars_app"
mongo = PyMongo(app)
# create route that renders index.html template
#app.route("/")
def index():
mars = mongo.db.mars.find_one()
return render_template("index.html", mars=mars)
#app.route("/scrape")
def scrape():
mars = mongo.db.mars
mars_data = scrape_mars.scrape()
mars.update(
{},
mars_data,
upsert=True
)
return redirect("http://localhost:5000/", code=302)
if __name__ == "__main__":
app.run()
The error I get is on last line app.run() and its:
Exception has occurred: AttributeError 'NoneType' object has no
attribute 'isatty'
I have tried running this in pycharm but I`m getting same message. Any idea what to try next?
Maybe you can hava a try with the method as below by Mr Josh Rosen,
ConsoleBuffer' object has no attribute 'isatty'
This question already has an answer here:
Flask view raises TypeError: 'bool' object is not callable
(1 answer)
Closed 6 years ago.
Edit: This is not a duplicate question. I am not asking what is wrong with the code. I very clearly said I know it's throwing an error because a view must return something. I'm asking why would the tutorial provide code that is going to throw an error and then neither prepare the user for that error or use that error to teach a lesson. The answer is, the tutorial is not perfect.
Original post: I'm following the Flask quickstart tutorial at http://flask.pocoo.org/docs/0.12/quickstart/. I'm roughly 2/5 down the page when it has me do URL building. The below code is directly from the tutorial, but it throws the titular ValueError when I try to visit localhost:5000/. I know that a view must return something and that's why it's throwing the error.
My primary question is, am I missing something in the tutorial? A tutorial shouldn't result in an error unless it's trying to teach you something by that error, but there's no mention of expecting an error. Rather, it seems to indicate it should work with the below code. I don't want to push ahead on the tutorial if I've missed something basic.
from flask import Flask, url_for
app = Flask(__name__)
#app.route('/')
def index(): pass
#app.route('/login')
def login(): pass
#app.route('/user/<username>')
def profile(username): pass
with app.test_request_context():
print url_for('index')
print url_for('login')
print url_for('login', next='/')
print url_for('profile', username='John Doe')
As you can see it is on python shell and docs says:
test_request_context(): It tells Flask to behave as though it is handling a request, even though we are interacting with it through a Python shell.
Tutorial does not say write this code to a file. If you do something like this:
#test.py
from flask import Flask, url_for
app = Flask(__name__)
#app.route('/')
def index(): pass
...
if __name__ == '__main__':
app.run()
$ python test.py
/
/login
/login?next=%2F
/user/John%20Doe
So when you hit localhost:5000 on browser you will get error View function did not return a response.
My primary question is, am I missing something in the tutorial? Yes probably you are missing to see it is on python shell.
The view function in Flask should always return Response object, otherwise the View function did not return a response error occures. It seems that the code in the example is given just for refenence and is not supposed to work out of the box.
See http://flask.pocoo.org/docs/0.12/quickstart/#about-responses for more details about responses.
You will get an error accessing localhost:5000 because you are not running the app. And you are right, it should also return something.
The goal of this block:
with app.test_request_context():
print url_for('index')
print url_for('login')
print url_for('login', next='/')
print url_for('profile', username='John Doe')
is only to show what urls generated by url_for would look like.
So you can run your file with python your_file.py and see the output in the shell.
This question already has an answer here:
Flask view raises TypeError: 'bool' object is not callable
(1 answer)
Closed 6 years ago.
I am trying to transition my workflow into Flask to write a simple web interface for a Python script.
However, doing the following, raises a type error constantly:
from flask import Flask, render_template, request
import sqlite3
app = Flask(__name__)
#app.route('/restart/<int:id>')
def restart(id):
return id
if __name__ == '__main__':
app.run()
I would basically just like to show the id that is passed in the URL.
Am I missing something? This is exactly how I would do this in Django for example and all the examples on the Net have pointed to this approach in Flask.
Your route function should be returning a string but you're returning the integer you're passing into it. Cast it to a string instead:
from flask import Flask, render_template, request
import sqlite3
app = Flask(__name__)
#app.route('/restart/<int:id>')
def restart(id):
return str(id)
if __name__ == '__main__':
app.run()
I am trying to follow this tutorial...
http://flask.pocoo.org/docs/tutorial/setup/#tutorial-setup
Trying to get a simple flask app to run. I think I have followed their code almost exactly, yet I am having problems. My code is....
from flask import Flask, request, session, g, redirect, url_for, \
abort, render_template, flash
# configuration
DATABASE = ''
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'default'
sandra_source= Flask(__name__)
sandra_source.config.from_object(__name__)
def main():
sandra_source.run()
main()
I recognize the DB is not the same, but other than that, it is pretty spot on. However, I keep getting the error
AttributeError: 'module' object has no attribute 'sandra_service'
My module is named sandra_service, so I'm not sure how this error is happening.
Stack trace
AttributeError: 'module' object has no attribute 'sandra_service'
0 SandraImporter.load_module() c:\working\qzpkgs\quartz-14324978\win32_vc9\pylib\sandra\sandra_import.py:208
1 <module>() /playground/nbkiq0w/rester_app_root/services/sandra_service.py:20
2 Config.from_object() D:\quartz\WINSLA~1\WIN32-~1\build\ext\noarch\lib\python2.6\flask\config.py:146
3 --> import_string() D:\quartz\WINSLA~1\WIN32-~1\build\ext\noarch\lib\python2.6\werkzeug\utils.py:529
Not sure if this is a great answer or not, but I removed
sandra_source.config.from_object(__name__)
this line, and now the code seems to be at least compiling/running. Hopefully more issues won't present themselves later on.