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

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.

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 get Phusion Passenger to recognize the correct version of Python for a web application?

I'm trying to set up my first Python web application through Flask. I've used the setup module on my hosting service, and I've hit a problem. When I try to run the app, I get an error page from Phusion Passenger. In the searching I've done so far, similar problems seem to come from Passenger's inability to locate the needed software. But I haven't done this before, so I may well be misunderstanding the problem. All help much appreciated.
Here are the contents of passenger_wsgi.py:
import imp
import os
import sys
sys.path.insert(0, os.path.dirname(__file__))
wsgi = imp.load_source('wsgi', 'flaskblog.py')
application = wsgi.application
And here is what the site admin pulled from the error log:
[ E 2020-05-25 15:09:08.9018 32404/T1q age/Cor/App/Implementation.cpp:221 ]:
Could not spawn process for application /home/eriksimp/public_html/flaskblog: The application process exited prematurely.
App 28117 output: File "/home/eriksimp/virtualenv/public_html/flaskblog/3.7/lib64/python3.7/imp.py", line 171, in load_source
App 28117 output: File "/home/eriksimp/public_html/flaskblog/passenger_wsgi.py", line 8, in <module>
App 28117 output: File "/home/eriksimp/virtualenv/public_html/flaskblog/3.7/lib64/python3.7/imp.py", line 171, in load_source
The problem was that I hadn't activated the environment. (I was following instructions that didn't include that step.) I created the app using cPanel, and at the end of the process, cPanel provided a Terminal command (at the top of the page) to activate the app. I entered Terminal through cPanel, ran that command, then ran "pip install flask."
Then I restarted the application and reloaded the page. Now it works!

Python Tornado AttributeError: module 'test' has no attribute '__path__'

I am attempting to just run the Hello World code from Tornado docs
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
Except I am getting an error: AttributeError: module 'test' has no attribute '__path__'
I am just using IDLE to run test.py
I thought this was due to my Windows 10 computer not having Python accessible to PATH but even with adding in the python 3.6 to PATH I am still getting the same error. Any ideas?
The screenshot is how I added python to PATH and I think I got it correct..
------EDIT------
Ill add some screenshots of the errors/tracebacks I am running into. 1st one is the command prompt below when the test.py is ran in IDLE 3.6 in Windows 10.
If there is an import error, I can import Tornado just fine thru IDLE interpreter.
I also tried running this hello World code in IPython 3.7, and I get this error:
Solution: Run your file without the -m argument.
Another solution would be to provide the file name without the .py extension:
python -m test
This will also work.
Explanation:
The -m argument tells Python to run a module (file) present in the Python path. It doesn't take the name of the file, it takes the name of the module. The difference is that the file name contains .py suffix, whereas the module name doesn't.
So you can run the test.py file like this, too: python -m test.
When to use -m argument:
The -m argument is there for convenience. For example, if you want to run python's default http server (which comes with python), you'd write this command:
python -m http.server
This will start the http server for you. The convenience that -m argument gives you is that you can write this command from anywhere in your system and python will automatically look for the package called http in your the system's Path.
Without the -m argument, if you wanted to run the http server, you'd have to give it's full path like:
python C:\path\to\python\installation\http\server.py
So, -m argument makes it easy to run modules (files) present in the Path.
With Tornado would you happen to know how to kill the Python interpreter? A CNTRL-C doesn't do anything.
I use Linux and Ctrl-C works fine for me. On Windows you can try Ctrl-D or Ctrl-Z. Or here are some answers: Stopping python using ctrl+c

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

Using SCSS with Flask

I'm trying to use scss with Flask and get it to auto-compile.
I've tried using Flask-Scss — unfortunately, when I set it up, I get Scanning acceleration disabled (_speedups not found)! errors, and no CSS file. Anyone know how to fix this, or get it to generate CSS files?
The error results from an error in the installation process. If you install through pip on an Ubuntu system and you get this warning:
==========================================================================
WARNING: The C extension could not be compiled, speedups are not enabled.
Plain-Python installation succeeded.
==========================================================================
Then you should make sure you have the libpcre3-dev library pre-installed (this is the module that contains pcre.h, the module that the C-installation fails on):
apt-get install libpcre3-dev
After doing this, re-install Flask-Scss:
pip install Flask-scss --force-reinstall -I
After restarting the Flask server, the error should now be a thing of the past.
But, please note
Even though the above will solve the problem of the _speedups not found error showing up, there is another likely reason for your files not getting compiled. If you have code like this:
app = Flask(__name__)
from flask.ext.scss import Scss
Scss(app, static_dir='static', asset_dir='assets')
...
if __name__ == "__main__":
app.run(debug=True)
, and you are not setting debug anywhere else, then you should make sure to put
app.debug = True
before the invocation of the Scss object:
app.debug = True
Scss(app, static_dir='static', asset_dir='assets')
Happiness! That should do the trick for getting your .scss files to compile every time you load a page in debug mode.

Categories

Resources