I am new to flask tryin to run first application .. here is my code and what turns back in terminal .. any suggestions? - flask

code
from flask import Flask, render_template, session, request
from flask_session import Session
app = Flask(__name__)
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"]= "filesystem"
Session(app)
#app.route("/", methods=["GET", "POST"])
def index():
if session.get("comments") is None:
session["comments"] = []
if request.method == "POST":
comment = request.form.get("comment")
session["comments"].append(comment)
CMD
(env) E:\COURSES\CS50W\lec2\exersice>set FLASK_APP=application.py
(env) E:\COURSES\CS50W\lec2\exersice>python -m flask run
E:\COURSES\CS50W\lec2\exersice\env\Scripts\python.exe: No module named flask

Check this out.
If you are not sure whether you have installed flask or not, try running only flask in the cmd or any terminal.If you get any commands about flask then you can be sure that it is installed or you can install by using
pip install flask
If you are concerned about the versions of the libraries you use for your application, then follow the above mentioned link!

Related

already install flask-sqlalchemy in virtual environment but unresolved import error is showing in flask app

from flask-sqlalchemy import SQLAlchemy showing unresolved import error. But i already install flask sqlalchemy in cmd using pip install flask-sqlalchemy command.In python shell in command line sqlalchemy is importing normally there is no problem but in flask app its showing import error
from flask import Flask, render_template
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'
all_post=[
{
'title':'post1',
'content':'content of post1',
'author':'dipanjan'
},
{
'title':'post2',
'content':'content of post2'
}
]
#app.route('/posts')
def posts():
return render_template('posts.html', posts=all_post)
#app.route('/')
def home():
return render_template('index.html')
if __name__ =="__main__":
app.run(debug=True)
İf you use venv and you cant see your packages, go ypur venv path and run this code below:
pip freeze
and check your package you want

Basic Flask views questions app not found

Hi I don't know why "app" is not defined. I have a very simple app and try to run it:
run.py:
from flask import Flask
app = Flask(__name__)
import views
if __name__ == "__main__":
app.run(debug=True)
views.py:
#app.route('/')
def hello():
return 'Hello, World!'
If I try to run the server via "python run.py" I get the following error:
File "XXX\a\views.py", line 1, in <module>
#app.route('/')
NameError: name 'app' is not defined
You need to put all your routes in run.py.
This is because, you have declared app in run.py and in views.py you are trying to access it.
Following works for me:
run.py
from flask import Flask
app = Flask(__name__)
import view
view.py
from run import app
#app.route('/')
def hello():
return 'Hello, World!'
On terminal execute
export FLASK_ENV=development
export FLASK_APP=run.py
then finally flask run or python -m flask run.
Also, its a good idea to switch to flask run from app.run. See this

Cannot import module to begin basic Flask app

So I'm following a beginners tutorial on Flask and for whatever reason am getting an error on what is essentially the very first step.
I first created an "app" directory where I created a python file for "init.py" which contains the following code:
from flask import Flask
app = Flask(__name__)
from app import routes
I then created a "routes.py" python file in the same directory:
from app import app
#app.route('/')
#app.route('/index')
def index():
return "Hello, World!"
Finally (and this is where the problem stems from), I created a python file named "microblog.py" which is located in the same folder as the "app" directory:
from app import app
I then go to my virtual environment and run (using cmd windows):
set FLASK_APP=microblog.py
So far so good, however when I try to run the following code in cmd:
flask run
I get the following error:
ImportError: cannot import name 'app' from 'app' (C:\Users\Grae_\microblog\app\__init__.py)
If any further clarification is needed, here are my file locations:
C:\Users\Grae_\microblog
C:\Users\Grae_\microblog\app
C:\Users\Grae_\microblog\__init__.py
C:\Users\Grae_\microblog\routes.py
C:\Users\Grae_\microblog\venv
C:\Users\Grae_\microblog\microblog.py
Apologies if this is really obvious, I'm just obviously very new to Flask and have been stuck on this for a while.
Thanks
The issue here is on python package "app". The directory should have a file named __init__.py instead of init.py.
For example, you rename the file init.py to __init__.py and replace content with below code it should work
from flask import Flask
app = Flask(__name__)
def start():
from app import routes
start()
You can do something like this:-
test.py
from flask import Flask
app = Flask(__name__)
#app.route("/")
def index():
return "Index!"
#app.route("/hello")
def hello():
return "Hello World!"
#app.route("/members")
def members():
return "Members"
#app.route("/members/<string:name>/")
def getMember(name):
return name</string:name>
if __name__ == "__main__":
app.run()
In command prompt, run the command-
python test.py
Try the URLs in your browser:
http://127.0.0.1:5000/
http://127.0.0.1:5000/hello
http://127.0.0.1:5000/members
http://127.0.0.1:5000/members/Karan/

How to start Flask and Flask-SocketIO via the command line flask run

I started with an application that has several webservices defined. I was able to start the application via flask run on the command line. Afterwards, I integrated flask-sckoetio (i.e. I added the lines from flask_socketio import SocketIO, emit and socketio = SocketIO(app)) and now I'm not able anymore to start the server via flask run.
from flask import Flask, request, abort
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app)
#app.route('/do_sth', methods=['POST'])
def do_sth():
return ""
I get the following message on the console:
* Serving Flask-SocketIO app "webservices.py"
* Forcing debug mode off
WebSocket transport not available. Install eventlet or gevent and gevent-websocket for improved perform
ance.
c:\program files\python36\lib\site-packages\flask_socketio\__init__.py:496: Warning: Silently ignoring
app.run() because the application is run from the flask command line executable. Consider putting app.
run() behind an if __name__ == "__main__" guard to silence this warning.
use_reloader=use_reloader, **kwargs)
So I updated my code to this:
from flask import Flask, request, abort
from flask_socketio import SocketIO, emit
app = Flask(__name__)
socketio = SocketIO(app)
#app.route('/do_sth', methods=['POST'])
def do_sth():
return ""
if __name__ == '__main__':
socketio.run(app)
But I still get the same error message and the server doesn't start. However, if I just execute the script everything works. But why is flask run not possible anymore?
It happens because of variable __name__ is equal to "__main__" only when the file called directly with a command like python file.py. But your file was imported and his __name__ variable is setted to name of a module which import them.
Solution:
Just delete string if __name__ == "__main__":
Did you install eventlet or gevent, which are mentioned in the error message?
They are also listed under requirements in flask-socketIO documentation.
Try installing them first.
After installing one of them, you can just use flask run to start your application.

flask: code in app factory does not get executed

I am using the standard flask app factoty setup as stated here:
http://flask.pocoo.org/docs/1.0/tutorial/factory/
flaskr/init.py
import os
from flask import Flask
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(
SECRET_KEY='dev',
DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
)
print('Hello World')
...
return app
I run this app with:
export FLASK_APP=flaskr
export FLASK_ENV=development
flask run
All very standard. But why is the code print("hello world") never executed?
edit
After reboot of my dev sytem the issue is gone. I am sorry I posted this.
Looks like you named the file init.py instead of __init__.py.
I guess you are using an older version of flask (<1.0).
The newest versions (>1.0) allow to detect automatically the function create_app or make_app (source code) to launch the application from CLI flask command.
You can update the flask package, for example with pip :
pip install --upgrade Flask
or add the following lines at the end of the __init__ file to create the application in an explicit way:
if __name__ == "__main__":
app = create_app()
app.run()