首页 > 解决方案 > Flask app AttributeError: 'function' object has no attribute 'post'

问题描述

I would like to understand why this fails and why when I swap the order of the routes it works.

I have this:

from flask import render_template, jsonify
from app.views.ticket.forms import TicketForm
from flask_login import login_required
from . import ticket
from app.models import User
from app.models import Ticket


@ticket.get('/ticket')
@ticket.post('/ticket')
@login_required
def ticket():
    form = TicketForm()
    form.requested_by.query = User.query.all()
    return render_template('ticket.html', form=form)


@ticket.post('/_get_phone/<requester>')
@ticket.get('/_get_phone/<requester>')
@login_required
def _get_phone(requester):
    phone = [(row.ID, row.Name) for row in Ticket.query.filter_by(requested_by=requester).all()]
    return jsonify(phone)

When I try to run the app I get an error:

AttributeError: 'function' object has no attribute 'post'

If I use @ticket.router I get the same error but 'route', if I swap @ticket.post and @ticket.get around I get 'no attribute 'get'.

BUT - if I swap the routes around so that the second one is above the first, it works. So this works:

@ticket.post('/_get_phone/<requester>')
@ticket.get('/_get_phone/<requester>')
@login_required
def _get_phone(requester):
    phone = [(row.ID, row.Name) for row in Ticket.query.filter_by(requested_by=requester).all()]
    return jsonify(phone)


@ticket.get('/ticket')
@ticket.post('/ticket')
@login_required
def ticket():
    form = TicketForm()
    form.requested_by.query = User.query.all()
    return render_template('ticket.html', form=form)

I'm happy that I got it working but why does the order of these matter? I've never had that issue before with others. Is it something to do with on returning render_template and the other jsonify?

It took me a while before I thought to switch the positions of these routes, so it would be good to know what the rules are for this.

标签: flaskroutesjsonify

解决方案


推荐阅读