Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import routes from other file using Flask?

Tags:

python

flask

Folders in app

In the shared image are the folders that I have to build my app, I'm trying to do a login system but I can't access to /user/signup that I have in my routes.py

There are my files content:

web_app.py

from flask import Flask, render_template, request, redirect
app = Flask(__name__)

from user import routes

@app.route('/')
def home():
    return render_template('index.html')

routes.py

from flask import Flask
from web_app import app #from the app module import app(web_app.py main)
from user.models import User

@app.route('/user/signup', methods=['GET'])
def signup():
    return User().signup()

models.py

from flask import Flask, jsonify

class User:

    def signup(self):

        user = {
            "_id": "",
            "name": "",
            "email": "",
            "password": ""
        }

        return jsonify(user), 200

I think I don't need nothing in init.py am I right?

like image 640
Marco Oliveira Avatar asked Sep 05 '25 03:09

Marco Oliveira


1 Answers

You actually need to restructure you whole app. You will use flask blueprints. first import flask blueprints in your routes.py:

from flask import Blueprint

and take out this line:

from web_app import app #from the app module import app(web_app.py main)

then add this into your web_app.py:

from .routes import routes
    app.register_blueprint(routes)

And finally go back to routes.py and add this:

routes = Blueprint('routes', __name__, static_folder='static', template_folder='templates')

So instead of using @app.route(...) in your routes.py file you will use this:

@routes.route(...)
like image 139
Constantine Westerink Avatar answered Sep 07 '25 23:09

Constantine Westerink