When you use a __init__.py
file, which you should, Python treats the directory as a package.
This means, you have to import from the package, and not directly from the module.
Also, usually you do not put much or any code in a __init__.py
file.
Your directory structure could look like this, where stack
is the name of the package I use.
stack/
├── endpoint.py
├── __init__.py
└── main.py
You __init__.py
file is empty.
main.py
import os
from flask import Flask
# create and configure the app
# instance_relative_config states that the
# config files are relative to the instance folder
app = Flask(__name__, instance_relative_config=True)
# ensure the instance folder exists
try:
os.makedirs(app.instance_path)
except OSError:
pass
from stack.endpoint import *
endpoint
from stack.main import app
# a simple page that says hello
# @app.route defines the url off of the BASE url e.g. www.appname.com/api +
# @app.route
# in dev this will be literally http://localhost:5000/hello
@app.route('/hello')
def hello():
return 'Hello, World!'
You can then run your app...
export FLASK_APP=main.py
# followed by a...
flask run
This all said, when I create a new Flask app, I usually only use one file, this makes initial development easier, and only split into modules when the app really grows bigger.
Also, for separating views or let's call it sub packages, Flask offers so called Blue prints. This is nothing you have to worry about right now, but comes especially handy when trying to split the app into sub applications.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…