Home > front end >  Flask package structure, where do I properly place my API files?
Flask package structure, where do I properly place my API files?

Time:03-09

Here is my current setup and it works, but this will bulk up the init file. How should I structure this so that my API is in its own folders and runs correctly? When I put testapi.py on the same level as run.py I couldn't get any models to import.

├── my_frame
│   ├── __init__.py
│   ├── forms.py
│   ├── models.py
│   ├── routes.py
│   ├── site.db
│   ├── static
│   ├── templates
│   └── testapi.py
├── run.py
└── venv

init.py

import os
from flask import Flask
from flask_restful import Api, Resource
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail

#app config, db, encryption, loginmanager
app = Flask(__name__)
app.config['SECRET_KEY'] =
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)

#app API
api = Api(app)
class HelloWorld(Resource):
    def get(self):
        return {"data": "Hello World"}

api.add_resource(HelloWorld,"/helloworld")

CodePudding user response:

I recommend this structure (based on the structure of the Flasky application - Miguel Grinberg):

├── app
│   ├── __init__.py
│   ├── models.py
│   ├── site.db
│   ├── static
│   ├── templates
│   ├── api
│   │   ├── __init__.py
│   │   └── hello_worlds.py
│   └── main
│       ├── __init__.py
│       ├── forms.py
│       └── routes.py (a.k.a. views.py)
├── tests
│   └── test_api.py
├── run.py
└── venv

api/hello_worlds.py

from flask_restful import Resource


class HelloWorld(Resource):
    def get(self):
        return {"data": "Hello World"}

api/__init__.py

from flask import Blueprint
from flask_restful import Api

from app.api.hello_worlds import HelloWorld


# Initialize the API component.
api_blueprint = Blueprint("api", __name__)
_api = Api(api_blueprint)

# Register the resources of the API to it.
_api.add_resource(HelloWorld, "/helloworld")

app/__init__.py

import os

from flask import Flask
from flask_restful import Api, Resource
from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from flask_login import LoginManager
from flask_mail import Mail


app = Flask(__name__)
app.config['SECRET_KEY'] =
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
db = SQLAlchemy(app)
bcrypt = Bcrypt(app)
login_manager = LoginManager(app)

from app.api import api_blueprint
app.register_blueprint(api_blueprint, url_prefix="/api/v1")

from app.main import main_blueprint
app.register_blueprint(main_blueprint)

To access your resource make a request to http://localhost:5000/api/v1/helloworld (for example).

  • Related