before_action ... only: how to do this in python flask? [closed]

2024/11/17 8:38:00

I need to change a ruby code to python and I am also new to this. Can someone tell me is there any function like before_action ... only: in python flask? This is the function I want to change:

class IftttController < ActionController::Basebefore_action :return_errors_unless_valid_service_keybefore_action :return_errors_unless_valid_action_fields, only: :create_new_thingdef return_errors_unless_valid_service_keyunless request.headers["HTTP_IFTTT_SERVICE_KEY"] == IFTTT_SERVICE_KEYreturn render plain: { errors: [ { message: "401" } ] }.to_json, status: 401endenddef return_errors_unless_valid_action_fieldsif params[:actionFields] && params[:actionFields][:invalid] == "true"return render plain: { errors: [ { status: "SKIP", message: "400" } ] }.to_json, status: 400endend
end

And as I read on internet, @app.before_request is equal to it, but I don't how to use it for specific action (before_action :return_errors_unless_valid_action_fields, only: :create_new_thing) like on the ruby on rails, Here is my code, I don't know whether it correct or not:

@ifttt.before_request
def return_errors_unless_valid_action_fields():if request.args.get("actionFields") and request.args["actionFields"]["invalid"] == True:return render_template_string(jsonify(errors = [{status= "SKIP", message = "400"}]), 400

Can anyone help me? Thank you very much.

Answer

Flask applications have a few hooks that let the user run a function before or after a request:

app = Flask(...)@app.before_request
def i_have_been_called():print('I have been called')

This should output "I have been called" to the console before every request.

Other hooks built into Flask include before_request, before_first_request, after_request, teardown_appcontext and more.

As for the only: params, there are no such things in Flask. You must simply write your function to check for such a case:

@app.before_request
def i_prefer_post():from flask import requestif request.method == 'POST':print('I prefer POST')
https://en.xdnf.cn/q/118825.html

Related Q&A

Destroy function not destroying a frame efficiently after the first iteration in Tkinter Python

I have built a code that saves the calculated data at every iteration in a for loop and the results are stored in 3 different csv files. These saved results are read in another python code that display…

Access columns and rows of numpy.ndarray

I currently struggling with extracting certain columns and rows from a matrix stored as a numpy.ndarray. I have a list in which Ive appended these numpy.ndarrays. This list is stored in a variable name…

How to access instance object in list and display there data? in python

class Bank:def __init__(self, name, balance=0):self.name = nameself.balance = balance# def Display_details(self):# print( self.name),# print(self.balance),#### def Withdraw(self, a):# self.…

Using Class, Methods to define variables

I have a number of chemicals with corresponding data held within a database, how do I go about returning a specific chemical, and its data, via its formula, eg o2.class SourceNotDefinedException(Except…

Python Tkinter: Color changing grid of buttons?

I understand that you can make a button that can do some actions when clicked with Tkinter, but how can I just make a button that turns from one color to another when clicked? Then, from that, how do …

Writing a function that checks prime numbers

def primecheck(num): if num > 1: for i in range(2, num): if (num % i) == 0: return False breakelse: return TrueIm trying to make a function that checks if an input is prime or not. This code does …

Getting error code 1 while installing geopandas with pip

This is the error I get when trying to install geopandas using pip install geopandas. Im using Python 3.7.Collecting geopandasUsing cached https://files.pythonhosted.org/packages/24/11/d77c157c16909bd7…

Find if a sorted array of floats contains numbers in a certain range efficiently

I have a sorted numpy array of floats, and I want to know whether this array contains number in a given range. Note that Im not interested in the positions of the number in the array. I only want to k…

Django Operation error: (2026, SSL connection error: SSL_CTX_set_tmp_dh failed)

I can not start my django server after running a statement through manage.py for generating class diagrams from db. And I always get this error but I dont know how to deal with it. OperationalError: (2…

TypeError with module object is not callable

I have a test folder the structure within the folder__init.py__ aa.py test.pyfor aa.pyclass aa:def __init__(self,max):self.max=maxprint max+1def hello(self):print(max)for test.pyimport aa abc = aa(100)…