Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask blueprint doesn't work without prefix

Tags:

python

flask

Hi I have a Flask app structured in following way and I have problem with blueprints setup. Whatever I do, they only work with url_prefix set up. It works currently as /main/verify but as it is a small app I would love to have an endpoint like /verify. What's interesting I managed to make it work with / route, but for the same configuration it didn't work for the /verify. I am pretty clueless right now, I can live with it as it is, but I really wonder what am I doing wrong.

Here is the code:

__init__.py

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from config import config


db = SQLAlchemy()


def create_app(config_name):
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    config[config_name].init_app(app)

    db.init_app(app)

    from main import main
    app.register_blueprint(main)

    return app

main/__init__.py

from flask import Blueprint
main = Blueprint('main', __name__, url_prefix='/main')
from . import views

main/views.py

from flask import request, jsonify
from . import main


@main.route('/')
def index():
    return "Hello world"


@main.route('/verify')
def verify():
    url = request.args['url']
    query = request.args['query']

    return jsonify({ ... })
like image 266
jeremi Avatar asked Mar 09 '23 11:03

jeremi


1 Answers

As I see you didn't register blueprint without prefix. If you need to register endpoints without prefix you must create a new instance of Blueprint

main = Blueprint('main', __name__, url_prefix='/main')
# main endpoints(with prefix /main)...
@main.route('/')
def index_main():
    return "Hello world from /main/"
# routes without any prefix
default = Blueprint('default', __name__)

@default.route('/')
def index():
    return "Hello world from /"

app = Flask(__name__)
app.register_blueprint(main)
app.register_blueprint(default)

Hope this helps.

like image 73
Danila Ganchar Avatar answered Mar 21 '23 03:03

Danila Ganchar