user3675188
user3675188

Reputation: 7409

How to separate flask routes to another modules

I have hundreds of routes in my flask main module,

I think it need to separate those hundred of routes from the main module.

How to do it ?

#!/usr/bin/env python3
# -*- coding: utf8 -*-
from flask import request, url_for
from flask import Flask, request, jsonify
from flask_request_params import bind_request_params
from flask import g
import datetime
import pandas as pd
import pymongo
from webargs import Arg
from webargs.flaskparser import use_args, use_kwargs
import yaml
import time, functools
from pdb import set_trace
from pandas_helper import PandasHelper
import errors
from app_helper import *
from release_schedule import ReleaseSchedule
from mongo import Mongo


@app.route('/next_release', methods=["GET"])
@return_json
def next_release():
    schedules = ReleaseSchedule.next_release(DB)
    return pd.DataFrame([sche for sche in schedules])

...
@app.route('/last_release', methods=["GET"])

Upvotes: 3

Views: 3502

Answers (2)

AlexLordThorsen
AlexLordThorsen

Reputation: 8488

This is what blueprints were made to do.

Another alternative is flask-classy (which is awesome). I'm going to talk about the blueprint approach since that's what I know better.

If I was in your position I would want to split my routes up based on common imports.

Without knowning your application I'm going to guess that a distribution like this

parse_user_data_views.py

from webargs import Arg
from webargs.flaskparser import use_args, use_kwargs
import yaml

push_to_db_views.py

from pandas_helper import PandasHelper
from mongo import Mongo
import pymongo
import pandas as pd
import datetime

release_views.py

from release_schedule import ReleaseSchedule
import pandas as pd

@app.route('/next_release', methods=["GET"])
@return_json
def next_release():
    schedules = ReleaseSchedule.next_release(DB)
    return pd.DataFrame([sche for sche in schedules])

is likely distribution. We can't answer this for you, only you can.

But this allows you to separate out your application in some pretty nice ways.

in __init__.py

from flask import Flask 

from yourapplication.release_views import release_views
from yourapplication.push_to_db_views import push_to_db_views
from yourapplication.parse_user_data_views import parse_user_data_views


app = Flask(__name__)
app.register_blueprint(release_views)
app.register_blueprint(push_to_db_views)
app.register_blueprint(parse_user_data_views)

Upvotes: 4

Bidhan
Bidhan

Reputation: 10687

Create a new file called views.py and add all your routes there. Then import views.py in your __ init __.py .

Upvotes: 0

Related Questions