How to pass classs self through a flask.Blueprint.route decorator?

2024/5/20 14:46:32

I am writing my website's backend using Flask and Python 2.7, and have run into a bit of a problem. I like to use classes to enclose my functions, it makes things neat for me and helps me keep everything modular. One problem I'm having, though, is that the decorators flask uses for routing doesn't preserve the self variable. I use this for accessing the loadDb method of the class that its in. See below. Anyone have any ideas why this is happening, and know how I could solve this, or even if there is a way to solve this?

class Test(object):blueprint = Blueprint("Test", __name__)def __init__(self, db_host, db_port):self.db_host = db_hostself.db_port = db_portdef loadDb(self):return Connection(self.db_host, self.db_port)@blueprint.route("/<var>")def testView(var): # adding self here gives me an errorreturn render_template("base.html", myvar=self.loadDb().find({"id": var})
Answer

There is an error if you add self because the method works the same as a function for the decorator, and the flask isn't expecting a function with a first argument self.

Let's look at the code of route : https://github.com/pallets/flask/blob/master/src/flask/blueprints.py#L52

It calls self.add_url_rule (self being the Blueprint) with a few arguments, one of those being the function. What you want is to add a rule with the method bound to an instance of Test(self.testView), not the method itself (Test.testview). This is tricky because the decorator is executed at the creation of the class, before any instance ever exist.

The solution I can suggest, asside from avoiding to put your views as methods of a class, is to call yourself blueprint.add_url_rule in the contructor of Test (i.e., at the first point the instance of Test is known.

https://en.xdnf.cn/q/72826.html

Related Q&A

why cannot I use sp.signal by import scipy as sp? [duplicate]

This question already has an answer here:scipy.special import issue(1 answer)Closed 8 years ago.I would like to use scipy.signal.lti and scipy.signal.impulse function to calculate the transfer function…

How to speed up nested cross validation in python?

From what Ive found there is 1 other question like this (Speed-up nested cross-validation) however installing MPI does not work for me after trying several fixes also suggested on this site and microso…

Streaming video from camera in FastAPI results in frozen image after first frame

I am trying to stream video from a camera using FastAPI, similar to an example I found for Flask. In Flask, the example works correctly, and the video is streamed without any issues. However, when I tr…

Fastest way to concatenate multiple files column wise - Python

What is the fastest method to concatenate multiple files column wise (within Python)?Assume that I have two files with 1,000,000,000 lines and ~200 UTF8 characters per line.Method 1: Cheating with pas…

Can autograd in pytorch handle a repeated use of a layer within the same module?

I have a layer layer in an nn.Module and use it two or more times during a single forward step. The output of this layer is later inputted to the same layer. Can pytorchs autograd compute the grad of t…

Altering numpy function output array in place

Im trying to write a function that performs a mathematical operation on an array and returns the result. A simplified example could be:def original_func(A):return A[1:] + A[:-1]For speed-up and to avoi…

Does the E-factory of lxml support dynamically generated data?

Is there a way of creating the tags dynamically with the E-factory of lxml? For instance I get a syntax error for the following code:E.BODY(E.TABLE(for row_num in range(len(ws.rows)):row = ws.rows[row…

Check if datetime object in pandas has a timezone?

Im importing data into pandas and want to remove any timezones – if theyre present in the data. If the data has a time zone, the following code works successfully: col = "my_date_column" df[…

Extract translator comments with xgettext from JavaScript (in Python mode)

I have a pretty well-working command that extracts strings from all my .js and .html files (which are just Underscore templates). However, it doesnt seem to work for Translator comments.For example, I …

Embedding python + numpy code into C++ dll callback

I am new of python embedding. I am trying to embed python + numpy code inside a C++ callback function (inside a dll)the problem i am facing is the following. if i have:Py_Initialize(); // some python g…