Reputation: 3975
I'm creating Restful web services using Flask. From the examples I see we use annotations like
@app.route('/')
I wanted to know how I use this if I have two Classes. I tried moving that to a different file inside a package but then it gives me a 404 error.
Contents of Service.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
Contents of Flask.py
from flask import Flask
app = Flask(__name__)
if __name__ == '__main__':
app.run()
I just want to know how do I specify routes if they are in different classes.
Upvotes: 1
Views: 2457
Reputation: 127180
Do not define app
in both modules. Only define it in one place and import it everywhere else. In the module that defines app
, import your other modules after defining it, to avoid circular imports.
A basic structure for a Flask project looks like:
MyProject/
my_package/
__init__.py
service.py
run.py
MyProject/my_package/__init__.py
from flask import Flask
app = Flask(__name__)
from my_project import service
MyProject/my_package/service.py
from my_project import app
@app.route('/')
def hello_world():
return 'Hello, World!'
MyProject/run.py
from my_package import app
app.run('localhost', debug=True)
Use python run.py
from the MyProject
directory to run the application with the dev server.
You also have some terminology errors. They're called "decorators", not "annotations". They're called "modules", not "classes". Also, common practice is to give files lowercase names.
Upvotes: 2