agleister
agleister

Reputation: 3

before_request() requires arguments, causes program to fail

I am following the flaskr tutorial. When I run python flaskr.py, I get this error:

Traceback (most recent call last):
  File "flaskr.py", line 26, in <module>
@app.before_request()
  File "/Users/myname/anaconda/lib/python2.7/site-packages/flask/app.py", line 62, in wrapper_func
return f(self, *args, **kwargs)
TypeError: before_request() takes exactly 2 arguments (1 given)

However, on step 4 it specifically says that before_request() takes no arguments. I have carefully followed all the instructions. Why am I getting this error?

import sqlite3
from flask import Flask, g

DATABASE = '/tmp/flaskr.db'

app = Flask(__name__)
app.config.from_object(__name__)

def connect_db():
    return sqlite3.connect(app.config['DATABASE'])

@app.before_request()
def before_request():
    g.db = connect_db()

@app.teardown_request()
def teardown_request(exception):
    db = getattr(g, 'db', None)
    if db is not None:
        db.close()

if __name__ == '__main__':
    app.run()

Upvotes: 0

Views: 1051

Answers (1)

davidism
davidism

Reputation: 127240

before_request is a decorator. Rather than calling it, you apply it directly to the decorated function.

@app.before_request
def my_before_request_function():
    pass

teardown_request behaves the same way, so you need to change that too or you'll get the same error.

If you go back to the tutorial and look carefully at the code, you will notice that they do not call the decorators directly.


Decorators are called with the decorated function as the first (and only) argument. Another pattern of decorators is the "decorator factory", where a function does take arguments, producing the actual decorator (which just takes the implicit decorated function argument). Since before_request is not a factory, the docs just say it takes no arguments.

Upvotes: 1

Related Questions