Joseph Wahba Joseph Wahba - 1 year ago 106
Python Question

Python Multiple decorators and calling functions

This question could be a simple question.

I have two python decorators having functions inside them as follows:

@app.route('/insertsql', methods=['GET', 'POST'])
def insertsql():

@app.route('/login', methods=['GET', 'POST'])
def login():

I want to use the
function inside the
function. Is that possible ? When I try it I get this error

Bad Request The browser (or proxy) sent a request that this server
could not understand.

Any suggestions ?

Answer Source

There are a few different ways to approach this. If you want to ensure the user is logged in before running that action you could use a decorator.

def before_request():

However, it could be you are really just trying to do two things within one route. How I like to handle this is by breaking up Flask apps into different components. Routes, Controllers and Models. This way a route can call multiple controller actions, where that logic isn't tightly coupled to your route and can be easily re-used.

Project Structure:

├── ├── ├── controllers │   └── ├── ├── models │   └── ├── routes │   └── v1 │   ├── │   └── ├── services └── templates

Code organization:
  • Controllers:

    Called from routes. Glue in application that are responsible for processing requests. Works by getting data in the Models using business logic from the Services and return results for the view. Should validate user input.

    Controller Actions: Reference Guide

    • index
    • show
    • create
    • update
    • destroy

      • Plural file names: eg:
      • Plural class names: eg: Cases
  • Models:

    Database interaction related code here. Responsible for data integrity.

    • Singular file name: eg:
    • Singular class name: eg: Case
  • Routes:

    Handles URI requests, these are BluePrints in Flask. Calls Controllers. Organized into a namespaced version for the api using v1. API related routes go within this directory.

    • Plural file names, with api prefix: eg:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download