Flask tutorial : cannot execute .run.py. terminal doenst recognize shebang? - python

I am following the tutorial here:
https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-i-hello-world
I have also create a
app/view.py
from app import app
#app.route('/')
#app.route('/index')
def index():
return "Hello World!"
and
app/init.py
from flask import Flask
app = Flask(__name__)
from app import views
I am down to the last step and written the
run.py
file as such:
#!flask/bin/python
from app import app
app.run(debug=True)
I am running it by evoking the ./run.py command in terminal. getting the following error:
from: can't read /var/mail/app
./run.py: line 4: syntax error near unexpected token `debug=True'
./run.py: line 4: `app.run(debug=True)'
I am running a conda virtual environment.
All the answers I see online suggest adding the shebang but its already there. I will appreciate guidance on this.

That's not a valid shebang - it has to be an absolute pathname, in other words the first character after the #! can only be a slash.

Related

cannot set flask environment variable in macos

After typing
export FLASK_APP=use_flask.py
And then typing
printenv
which outputs inter alia:
TERM_SESSION_ID=AA805368-CF19-4631-AABB-A0112AD535CE
FLASK_APP=/users/me/documents/pcode/color/use_flask.py
USER=me
CONDA_EXE=/Users/me/Applications/miniconda3/bin/conda
I then place in the file use_flask.py
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello():
return 'hey man'
And then type
ls
which outputs inter alia
use_flask.py
I then type:
flask run
I get the error
-bash: flask: command not found
I have also tried exporting the full path of the use_flask.py file but that did not work either. What am I doing wrong?
I ran
pip install flask flask-alchemy
I thought I already had flask installed because when I typed
from flask import Flask
into my Pycharm editor and then ran the code no error message occurred. So although I solved the problem I don't understand why it didn't work the first time.

How do I fix #app.route syntax error with Flask?

from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello from Flask!'
if __name__ == "__main__":
app.run()
But Python is prompting the following error:
#app.route('/')
...
File "<stdin>", line 2
^
SyntaxError: invalid syntax
I ran your code and it worked for me. There does not seem to be a clear syntax error.
Try saving your file again and clearing your terminal before running it.
Another alternative is running the following in your command prompt before running your code:
set FLASK_APP={name of your file}.py
In the command prompt it should look something like this:
C:\path\to\app>set FLASK_APP=hello.py
Lastly, you can also try running it by writing the following in your command prompt or terminal instead of using the main() function you have now:
python -m flask run
More details and alternatives here: https://flask.palletsprojects.com/en/1.1.x/quickstart/
Hope this helps!

How to set up Flask on pythonanyhwere based on flask megatutorial

I am currently developing an application. this web app has its own domain. when initially created i set up the domain and the registrar using the cname and it succesfully displayed after a couple of hours "this is a flask app..." something like that.
i decided to follow the examples of Mr Grinberg in his book (fully functional on localhost). So i cloned my personal repository to pythonanywhere and ran the following commands.
python manage.py db init
python manage.py db upgrade
python manage.py migrate
every thing is ok so far. and i checked out the mysql database using mysql workbench.
Now comes my issue.
when i run python manage.py runserver
it throws me the following error.
/home/username/.virtualenvs/webapp/local/lib/python2.7/site-packages
/flask_sqlalchemy/__init__.py:800: UserWarning: SQLALCHEMY_TRACK_MODIFICA
TIONS adds significant overhead and will be disabled by default in the future. Set it to True to suppress this warning.
warnings.warn('SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to True to su
ppress this warning.')
Traceback (most recent call last):
File "manage.py", line 20, in <module>
manager.run()
File "/home/username/.virtualenvs/webapp/local/lib/python2.7/site-packages/flask_script/__init__.py", line 412, in run
result = self.handle(sys.argv[0], sys.argv[1:])
File "/home/username/.virtualenvs/webapp/local/lib/python2.7/site-packages/flask_script/__init__.py", line 383, in handle
res = handle(*args, **config)
File "/home/username/.virtualenvs/webapp/local/lib/python2.7/site-packages/flask_script/commands.py", line 425, in __call__
**self.server_options)
File "/home/username/.virtualenvs/webapp/local/lib/python2.7/site-packages/flask/app.py", line 843, in run
run_simple(host, port, self, **options)
File "/home/username/.virtualenvs/webapp/local/lib/python2.7/site-packages/werkzeug/serving.py", line 677, in run_simple
s.bind((hostname, port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
i tried disabling the wsgi.py file (commenting everything out) still the same.
Things to know:
i have a paid acount.
this is the second webapp on pythonanywhere. (the first one is not modeled based on the tutorial and works just fine)
EDIT
i changed the port from 5000 to 9000. and it runs in the console. but i cant visit my site. should i comment out the wsgi file?
currently it looks likes this:
import sys
# # add your project directory to the sys.path
project_home = u'/home/username/e_orders/e_orders'
if project_home not in sys.path:
sys.path = [project_home] + sys.path
# # import flask app but need to call it "application" for WSGI to work
from manager import app as application
manage.py
import os
from app import create_app, db
from app.models import User
from flask_script import Manager, Shell, Server
from flask_migrate import Migrate, MigrateCommand
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
manager = Manager(app)
migrate = Migrate(app, db)
def make_shell_context():
return dict(app=app, db=db, User=User)
manager.add_command('shell', Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
manager.add_command('runserver', Server(port=9000))
if __name__ == '__main__':
manager.run()
EDIT 2
i have the following error with the wsgi configuration above.
errorlog
ImportError: No module named manager
2016-08-04 17:42:39,589 :Error running WSGI application
Traceback (most recent call last):
File "/bin/user_wsgi_wrapper.py", line 154, in __call__
app_iterator = self.app(environ, start_response)
File "/bin/user_wsgi_wrapper.py", line 170, in import_error_application
raise e
ImportError: No module named manager
PythonAnywhere dev here.
If you run a Flask app from a console on PythonAnywhere, it's not actually accessible from anywhere else. It may well run, but nothing will route any requests to it. So there's no need to run anything from the console (unless you're just testing for syntax errors, I guess).
Instead, you need to create a web app on the "Web" tab -- it looks like you've already done that. This then routes using the WSGI file that you seem to have discovered.
If you've done all that, then when you visit the domain that appears on the "Web" tab (normally something like yourusername.pythonanywhere.com) then you should see your site. If you get an error, then check out the error logs (also linked from the "Web" tab), which should help you debug.
[edit: added affiliation]
Sorry for the big delay. The solution to run the server is the one bellow.
# This file contains the WSGI configuration required to serve up your
# web application at http://<your-username>.pythonanywhere.com/
# It works by setting the variable 'application' to a WSGI handler of some
# description.
#
# The below has been auto-generated for your Flask project
import sys
# # add your project directory to the sys.path
project_home = u'/home/username/mysite/'
if project_home not in sys.path:
sys.path = [project_home] + sys.path
# # import flask app but need to call it "application" for WSGI to work
from manage import app as application
i will post the database setup also...

python flask can't find '__main__' module in ''

Hi All I am just learning about flask. I have used pip to install it. Then when I run this basic code I get an error. Basically I see its working then abruptly exits with the following error. This maybe looks to be some environment issue but I'm not sure. The strange thing this was working the other day now it's not.
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True, port=8000, host='0.0.0.0')
* Running on http://0.0.0.0:8000/ (Press CTRL+C to quit)
* Restarting with stat
/Library/Frameworks/Python.framework/Versions/3.4/bin/python3: can't find '__main__' module in ''
You said, that the problem only occurs when you run the code from an interactive shell. It is caused by a feature in werkzeug (the wsgi server flask is based on).
In debug mode werkzeug will automatically restart your server if a project file is changed. Everytime a change is detected werkzeug restarts the file that was initially started. Even the first start is done via the file name!
But in the interactive shell there is no file at all and werkzeug thinks your file is called "" (empty string). It then tries to run that file. For some reason it also thinks that the "" refers to a package. But since that package does not exist it also cannot have a __main__ module, hence the error.
You can simulate that error by running "" directly
python ""
# prints: can't find '__main__' module in ''
You could try to disabe the reloader by setting debug to False (which is also the default):
app.run(debug=False, ...)
Then it should also run in an interactive session. But why would you do that? Just put in a file and run that.

Is there any option getting ipython command prompt while running flask

Let me try to explain my problem with example now.
Here is sample GUI code with Tkinter
from Tkinter import *
root = Tk()
w = Label(root, text="Hello, world!")
w.pack()
root.mainloop()
If I run this code in Ipython, I don't get a command prompt when the GUI is visible.
Now if I comment out the line, "root.mainloop()", the code still works in Ipython and I have access to command prompt so that I can inspect data when the code is running.
Now coming to the Flask case,
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
app.run()
When I run this application in Ipython, I don't get a command prompt. To access variables while the code is running, I need to stop the flask server.
Is there any option to run the flask server and have access to command prompt?
Thank you
I second #NewWorld and would recommend a debugger. You can inspect the program in an IPython shell with the IPython debugger. Install e.g. with:
pip install ipdb
Then load the debugger with: ipdb.set_trace() like;
#app.route('/')
def hello_world():
import ipdb; ipdb.set_trace()
return 'Hello World!'
This will open a IPython command prompt and you can inspect "data while the code is running".
Further information:
Look here to get started with ipdb.
This site gives a short introduction to available commands once inside the debugger.
run the flask application in separate thread.
try this example:-
from flask import Flask
import thread
data = 'foo'
app = Flask(__name__)
#app.route("/")
def main():
return data
def flaskThread():
app.run()
if __name__ == "__main__":
thread.start_new_thread(flaskThread,())
run this file in ipython:-
"run -i filename.py"
then you can access the ipython terminal for inspection.
If you want to use flask shell through ipython you can install the following package:
pip install flask-shell-ipython

Categories

Resources