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.
Related
I am currently running into an issue deploying a Flask app on Amazon's EB2 service. The Flask app works locally. When it is deployed, however, it only works for the first person who clicks the link. After that it throws the following error:
Internal Server Error The server encountered an internal error and was
unable to complete your request. Either the server is overloaded or
there is an error in the application.
The error it is throwing out concerns the Flask session - it becomes empty after routing from one site to another. I also noticed that the before_first_request function detailed below is ran only once, for the first user, and never again - which is even more bewildering.
Here's the minimal example:
from flask import Flask, render_template, request, session, url_for
application = Flask(__name__)
application.secret_key = "mysecretkey"
#application.before_first_request
def before_first_request():
""" these commands are run before the first request"""
# setup logging
application.logger.setLevel(logging.INFO)
application.logger.info('starting up Flask')
# clear session
session.clear()
# load in PID
session['pid'] = 123
# add parameters to the session
params = dict()
params['parameter'] = 0
session['params'] = params
application.logger.info(session) # it is printing the session as expected
return 'OK'
#application.route('/')
def main():
""" landing page """
application.logger.info(session) # empty
application.logger.info(application.secret_key) # as expected
params, results = session.pop('params'), session.pop('results') # throws out the error
return render_template('empty_template.jinja', args = session)
I am wondering if anyone might know what is going on how to resolve the issue?
I managed to solve it.
The error was that #before_first_request wrapper actually only ran once before first request ever made to the app. Hence, the session was actually only created and populated once.
I fixed that error by adding the call to before_first_request function at the top of the main function.
Flask keeps spitting out this error:
TypeError: '<=' not supported between instances of 'NoneType' and 'datetime.datetime'.
Apparently the flask-session module is trying to compare session expire with current time. I tried setting the session expire to one day to avoid its value from being None, but it doesnt seem to work. If we get the session expire to be of set value, I think it might fix the problem.
from flask import Flask
from pymongo import MongoClient
from flask_session import Session
import datetime
from flask_wtf.csrf import CSRFProtect
from dashboard import dashboard
from auth import auth
app = Flask(__name__)
app.config['SECRET_KEY'] = 'xxxxx'
app.config['SESSION_TYPE'] = 'mongodb'
mongo = MongoClient('mongodb+srv://xxxxxxxxx')
app.config['SESSION_MONGODB'] = mongo
app.config['PERMANENT_SESSION_LIFETIME'] = datetime.timedelta(days=5)
app.config['SESSION_MONGODB_DB'] = 'matjari'
app.config['SESSION_PERMANENT'] = True
Session(app)
csrf = CSRFProtect(app)
matjari = mongo.matjari
mongo_users = matjari['users']
app.register_blueprint(dashboard, url_prefix='/dashboard')
app.register_blueprint(auth, url_prefix='/auth')
#app.route('/')
def index():
return 'alive'
if __name__ == '__main__':
app.run(debug=True)
It seems like the below line has something to do with the error going away.
app.config['SESSION_PERMANENT'] = True
If I make SESSION_PERMEMNAT = True it will not give the error, but not entirely sure about the reliability
Update:
Found this issue on flask-session Github. Seems like it has something do with the database sessions table expiry column being empty.
Weird
For some magical reason the issue seems to have resolved itself. I havent changed anything in my code. If you have any explanation please let me know.
While trying to run the following code:
from flask import FLASK, render_template, request, jasonify
I am getting the following error:
ImportError: cannot import name 'FLASK' from 'flask' (C:\Users\karti\Anaconda3\envs\venv\lib\site-packages\flask\__init__.py)
Python is case sensitive. Also check your spelling on jasonify:
from flask import Flask, render_template, request, jsonify
The Flask object is written in title case, not all caps. I also suspect you meant jsonify (JSON is short for JavaScript Object Notation) instead of jasonify which is how it's pronounced. You can find the API reference here: https://flask.palletsprojects.com/en/1.1.x/api/#template-rendering
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'
The answer that I found on the web is to use request.args.get. However, I cannot manage it to work. I have the following simple example:
from flask import Flask
app = Flask(__name__)
#app.route("/hello")
def hello():
print request.args['x']
return "Hello World!"
if __name__ == "__main__":
app.run()
I go to the 127.0.0.1:5000/hello?x=2 in my browser and as a result I get:
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
What am I doing wrong?
The simple answer is you have not imported the request global object from the flask package.
from flask import Flask, request
This is easy to determine yourself by running the development server in debug mode by doing
app.run(debug=True)
This will give you a stacktrace including:
print request.args['x']
NameError: global name 'request' is not defined
http://localhost:5000/api/iterators/opel/next?n=5
For something like the case before
from flask import Flask, request
n = request.args.get("n")
Can do the trick