After successfully completing the pythonanywhere flask tutorial (pa.com), Miguel Grinberg's the "Flask Mega Tutorial" (fmt) beckoned. Sadly, I've not even made it to "Hello, World". Here's what I have done:
In pa.com attempting to follow fmt verbatim is a no go:
python3 -m venv flask
leads to an error of
ensurepip is not available
and we do not have sudo access.
Undeterred, I reasoned that all Miguel is asking us to do is distribute the functionality we see in one file in the pa.com tutorial (flask_app.py) into a few files that will make the building of a full app easier. Since pa.com is already setting up my base web app with flask and python 3.4, not being able to set up the virtual env. did not seem to be a block, at least not at first.
Per the fmt, in the base dir of the pa.com (pwd -> home/{username}/microblog) -- which is where the flask_app.py file that successfully generates the pa.com tutorial page lives -- I set up app and tmp directories, and create app/__init__.py, app/views.py and the run.py files as directed by fmt
Hitting the app page (run.py the only file in the main directory) generates an Unhandled Exception on the page.
Changing the name to flask_app.py (which seems to be what pa.com expects on flask installations) generates the same error.
Modifying the content of the flask_app.py code to:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return "working from flask_app.py"
Generates a successful output from the app, whereas having the same code in a file named run.py generates the same Unhandled Exception error.
the lines:
from app import app in both run.py and views.py and
from app import views in __init__.py
all make me wonder... where is this "app" module coming from? But aside from being puzzled by that question, no other ideas on how to proceed from here. Any suggestions? Would really like to get set up on pa.com and work through this tutorial/book.
Feel like I am missing something basic, but not sure what.
First rule is: don't use app.run() on PythonAnywhere - that's what run.py is trying to do. That's fine for your own PC, but on PA it will cause an error. It's fine to have the file there, but don't try and import from that file in your wsgi config.
Instead, you just need to import the flask app variable, which Miguel gets you to put in app/__init__.py (that's slightly confusing, a variable called app, and a folder called app, but we can deal with it!)
To do that, you'll want to add the folder that contains the app folder to your sys.path. You also need to "rename" the app variable to application as you import it:
# assuming we have /home/myusername/microblog/app/__init__.py:
path = '/home/myusername/microblog'
if path not in sys.path:
sys.path.append(path)
# now we can import the app variable from the app folder's __init__
# and rename it to application
from app import app as application
More info: a brief guide to flask on pythonanywhere and a guide to debugging imports and sys.path problems in your pythonanywhere wsgi file
from microblog import app as application
This is fixed my solution.
Best Regards
Related
i have a strange experience with Python code, so:
Im trying to learn Flask with some tutorial, and i managed to follow some with nice result, and now im trying to start my own project to make sure i understood the stuff, but i find myself stuck by hours for this problem
I have this directory structure:
/projectName/
/venv/
/website/
/static/
/templates/
/__init__.py
/otherPython.py
/app.py
app.py
from website import create_app
app = create_app()
if __name__ == '__main__':
app.run(debug=True)
init.py
from flask import Flask
def create_app():
# I create the app and give the secret key
app = Flask(__name__)
app.config['SECRET_KEY'] = 'stackoverflow'
return app
The Problem
Cannot find reference 'create_app' in 'imported module website'
Enviroment:
Win10 pro 10.0.19045
python 3.10
PyCharm 2022.1.4 (community edition)
Does somebody have any clue on what im missing, or if im allucinating and dont see a clear code/path error?
In a identical project it works, i already tryied to mark ProjectFolder as Source Root, already tryed to clean caches and restart, and i cannot understand why as a identical import with same folder structura and method name, in one project work(the tutorial one), and now in mine doesnt.
I dont know if that is helpfull but after from website import if i do ctrl+space i do not see the init.py file nor the create_app() method.
the error im getting: ImportError: attempted relative import with no known parent package
My folder structure:
-Backend
__init__.py
run.py
procfile
__init.py:
has the create app method
run.py:
from . import create_app
if __name__ == "__main__":
app = create_app("config")
app.run(debug=True)
procfile:
web: gunicorn run:app
EDIT:
I rearranged the app structure by which:
Backend
init.py
procifle
extensions.py
src
init.py
run.py
init.py:
empty
src/init.py:
from ..extensions import db,migrate
has the create app method
src/run.py:
from src import create_app
if __name__ == "__main__":
app = create_app("config")
app.run(debug=True)
so now the new error is:
from ..extensions import db
ImportError: attempted relative import beyond top-level package
Edit #2:
another thing to point out is, that suppose in the run.py i do the following:
from Backend import create_app()
I get the following error: no module named "Backend" why could that be?
Has anyone faced a similar issue and what can I do to solve it?
Update based on new information I think we can get you home.
1.) Move run.py next to the procfile (same dir). That "run file" should be in that top level dit at /app/run.py in Heroku.
A good basic pattern for file organization is to "module" everything (a dir with a __init__.py file). Then all imports are from the top level run.py [where the process is running from] walking subfolders. As long as you traverse down into imports things stay pretty stable. If you are trying to navigate up dirs it becomes problematic.
Resolve any imports, it can be tricky at first but soon becomes a way of thinking.
2.) Move extensions.py into src (for now) and import from src import foo
The following is the pattern in all my active Django and similar apps running in Heroku. Same layout I have been using for many years. In the following screenshot manage.py is the Django equivalent of your run.py. I am not using the docker image on this app, so that is not in the equation, just code and dependencies.
Your problems are totally understandable, it's easy to take for granted all the times other Python devs do this.
I am just starting up my first Flask project and I am trying to set it up as packages so the app can be broken up. My file structure is:
project/
setup.py
config.py
requirements.txt
.gitignore
appname/
__init__.py
view.py
static/
stylesheets
templates/
html
I have followed a number of tutorials and some have used python setup.py to run the project and others have used flask run. First off, what is the difference?
Now in my init.py the code is:
from flask import Flask, render_template
from appname import views
app = Flask(__name__)
My views.py has:
from appname import app
from flask import render_template
#app.route('/')
def index():
return render_template("index.html")
So far I have been exclusively trying flask run but I get the error:
AppException: The file/path provided (appname) does not appear to exist
If I replace the from appname import views with the views code it works fine. So the issues lies with how I am importing but I feel like I have tried every sort of importing format I know...
Well, the first thing that I see is an infinite loop of imports:
appname imports appname.views, and
appname.views imports appname.
You can break the infinite loop of imports like this: in __init__.py, remove the import of views which is not used:
from flask import Flask
app = Flask(__name__)
To run your application, you must tell Flask where you application is. To do that, you need to export an environment variable, like this:
export FLASK_APP=appname/__init__.py
flask run
* Serving Flask app "appname"
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Everything is explained in the Quick start page of the documentation.
Ooops, I forgot your first question: python setup.py is used to run setuptools tasks (like the make command with makefile). It has nothing to do with Flask. See Building and Distributing Packages with Setuptools.
You're trying to import views whereas your module is called view.py see python docs on python packaging
I'm following the Flask Mega Tutorial, and I'm running into an issue once I get to the second part and restructure my folder structure to match theirs, I cannot import Flask.
My current folder structure is as follows
/FlaskTest
/app
/static, templates etc
/flask
/virtualenv folders etc
/tmp
run.py
as far as I can tell, the folder structures are identical other than naming of the top level directory.
in my __init__.py file (/app/__init__.py), I'm doing as instructed in the tutorial,
from flask import Flask
app = Flask(__name__)
from app import views
I'm getting an Import Error that "cannot import name 'Flask'". I'm guessing the issue is because the flask package was installed to /flask/lib/site-packages.
My question: How can I reference the sub folder of flask/site-packages?
I've read through the python import system documentation and from what I can make of it through the first pass of reading it over, I would need to likely do something like from flask import flask.Flask or something to that effect.
UPDATE: So after cd'ing around the directory and checking pip list, I realized that flask wasn't accessible to my app directory. I ran pip install flask in the app directory. Now my site runs, but I'm not sure if this is the best practice of doing things with Python. Please provide some clarity as what the best practice is for installing packages and where the packages reside.
UPDATE 2: After creating a directory called standalone. In this folder, I created a virtual environment called standalone-test. Once, I did that, I also mkdir'ed app and copied it's contents from FlaskTest so that way the code would be identical. I was able to run the run.py script by using python run.py, but I can't run python -m app like you had said without running into an error. The error is as follows if it helps.
"No module name app.main; 'app' is a package and cannot be directly executed.
I am able to run python run.py as I mentioned, but I'm not able to run the python -m app command as you had mentioned
I think something went wrong in your execution environment. Here are some explanations.
The virtualenv
See the documentation of virtualenv
If you have followed the tutorial:
The flask directory is your virtualenv,
On posix system, you have a flask/bin subdirectory, or
On Windows system, you have a flask\Scripts subdirectory.
I make the assumption that you are on posix system.
To activate your virtualenv, run:
source flask/bin/activate
Your prompt should change to something like: (flask)$.
To list the installed libraries use pip:
pip list
Make sure you see Flask. The tutorial encourages you to install a lot of Flask plugins, so there are a lot of Flask-Something…
If Flask is missing, install it:
pip install Flask
Run your app
Your application is in the app directory, it has an __init__.py file (it's a Python package).
In this file, you have:
from flask import Flask
app = Flask(__name__)
from app import views
From your FlaskTest/ directory, try to run this script like this:
cd FlaskTest/ # if not in this directory
python -m app
This should import Flask, instanciate your app (but don't run it), import the views module.
If app/views.py exist you should have no error.
=> at this point, we have simulated what run.py imports…
Now write run.py in your FlaskTest/ directory:
#!flask/bin/python
from app import app
app.run(debug=True)
Run it like this:
python run.py
Note that the shebang #!flask/bin/python is unusual, but should work in the context of the tutorial.
This should start your http server…
I'm trying to get a Flask "hello world" application working on a Dreamhost shared server, following the instructions on their wiki, but I'm not having any luck.
My Flask application is the "hello world" one from the Flask quickstart guide:
from flask import Flask
app = Flask(__name__)
#app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run()
Which I've got in a file called "hello.py" in a folder called mysite, as per the DH wiki instructions. My passenger_wsgi.py file is:
import sys, os
INTERP = os.path.join(os.environ['HOME'], 'flask_env', 'bin', 'python')
if sys.executable != INTERP:
os.execl(INTERP, INTERP, *sys.argv)
sys.path.append(os.getcwd())
from mysite import hello as application
I've tried running the commands in a Python console, and last import line failed until I added the __init__.py file to the mysite directory.
When I try and access the website I just get a 500 error (and nothing in the logs unfortunately, unless they're in logs I can't get to as this is a shared server...).
As this is the most basic of setups (i.e., copied and pasted from a wiki), I can't help feeling that I'm missing something really simple. Or perhaps this isn't possible on a shared server?
Does answering my own question mean I'm talking to myself?
Anyway - I seem to have fixed it. Rather than find a nice helpful error message, I went through all the steps again one at a time, and it turns out it was an import error in the passenger_wsgi.py file. As the app is in the mysite subdirectory, the line:
from mysite import hello as application
should have been (and in fact, now is):
from mysite.hello import app as application
And it works. Which is nice.