Joseph Wahba Joseph Wahba - 8 days ago 5
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
login()
function inside the
insertsql()
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

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.

@auth.login_required
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:

├── app.py ├── config.py ├── controllers │   └── cases.py ├── manage.py ├── models │   └── case.py ├── routes │   └── v1 │   ├── api_cases.py │   └── api_test.py ├── 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: cases.py
      • Plural class names: eg: Cases
  • Models:

    Database interaction related code here. Responsible for data integrity.

    • Singular file name: eg: case.py
    • 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: api_cases.py
Comments