skornos
skornos

Reputation: 3291

Flask and nginx routing

I've configured nginx + uwsgi + flask and now I am struggling with prepending path to my flask defined routes. The basic question is: Is it even possible?

Let's say I have a route app.route('/login') and I would like to configure nginx to access this route like from the address /api/login.

My current configuration looks like this but it isn't working

location = /api { rewrite ^ /api/; }
location /api { try_files $uri @api; }
location @api {
        include            uwsgi_params;
        uwsgi_pass         uwsgicluster;

    proxy_redirect     off;
    proxy_set_header   Host $host;
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   X-Forwarded-Host $server_name;
}

Thanks for any help.

Upvotes: 1

Views: 2700

Answers (1)

chishaku
chishaku

Reputation: 4643

One suggestion is to keep the routing logic within your application:

app.route('/api/login')

Or implement an 'api' blueprint with a url_prefix of '/api':

file: api/views.py

from flask import Blueprint, render_template, abort
from jinja2 import TemplateNotFound

api = Blueprint('api', __name__, url_prefix='/api')

@api.route('/', defaults={'page': 'index'})
@api.route('/<page>')
def show(page):
    if page == 'login':
        # do something
    try:
        return render_template('pages/%s.html' % page)
    except TemplateNotFound:
        abort(404)

file: app.py

from flask import Flask
from .api import api

app = Flask(__name__)
app.register_blueprint(api)

Upvotes: 2

Related Questions