1

I'm just started to learning backend web development using Python from a tutorial [here][1].

The first project is a simple Hello World respond to requests for website home page.

Whole the program for above project is consist of 3 files:

myWebsite/
    app/
        __init__.py
        views.py
    run.py

And the Python files are as below :

__init__.py

from flask import Flask
app = Flask (__name__)
from app import views

views.py

from app import app
@app.route ('/')
def sayHello():
    return "Hello World"

run.py

from app import app
app.run (debug = True)

My origin question:

The program will execute by interpreting run.py. As far as I know in the first line of this file, from app import app, it search __init__.py for an object named app and if it found, make a it available for the next lines, right? Well, that seems OK for me (I think!).

The question is, why we need to from app import app in views.py while I don't want to execute it! I mean I just want to use this file in my __init__.py file, so I think that enough to import it in __init__.py and I don't need to from app import app in views.py. Am I wrong?


As a side question :

When I write from x import y, what is x and what is y?

  • Is x a directory or a file?
  • Is y a file or an object in a file named __init__.py?

When I write import z, what is z? a file or an object inside one of the libraries?


I know that my question seems simple for experts, but I migrate from C to Python, and look at import like #include in C and I think this is origin of my problem. I read some Q&A in SO related to my issue, but I am confused about it yet.

Ebrahim Ghasemi
  • 5,850
  • 10
  • 52
  • 113
  • 1
    possible duplicate of [Python relative imports for the billionth time](http://stackoverflow.com/questions/14132789/python-relative-imports-for-the-billionth-time) – doru Jul 08 '15 at 07:36
  • 1
    In `views.py` you need `app` because you use the decorator `app.route`. – Matthias Jul 08 '15 at 07:38
  • @Matthias But I don't call `views.py` directly. I use content of it in `__init__.py` only – Ebrahim Ghasemi Jul 08 '15 at 07:39
  • @user4815162342 Thank you. I correct it. It was `from app import view` – Ebrahim Ghasemi Jul 08 '15 at 07:40
  • 2
    What's wrong with the [Python tutorial](https://docs.python.org/3/tutorial/modules.html)? –  Jul 08 '15 at 07:46
  • 3
    Btw, if you're new to Python, I recommend you to use Python 3 instead of Python 2. Flask seems to be pretty much support Python 3 fine, so you'll be better of learning Python 3. –  Jul 08 '15 at 07:51

0 Answers0