Szymon
Szymon

Reputation: 633

How to call some function from the Flask app in Python?

I've the myapp.py like this:

from flask import Flask
from flask import request
from flask import render_template
app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
         # do something
         # for example:
         message = 'I am from the POST method'
         f = open('somefile.out', 'w')
         print(message, f)

    return render_template('test.html', out='Hello World!')

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

I have a simple question. How to call the index() function and execute code only in the if statement (line from 8 to 13) in the Python?

I tried in this way:

>>> import myapp
>>> myapp.index()

but I get the message:

RuntimeError: working outside of request context

Upvotes: 11

Views: 16885

Answers (2)

Peter Hudec
Peter Hudec

Reputation: 2483

The error is caused by accessing the request.method attribute in the index() function. You could call index() without any problems unless you try to access the request attributes inside it.

The request proxy works only within a request context.

You can read more aboout it here: http://flask.pocoo.org/docs/reqcontext/

>>> request.method
(...)
>>> RuntimeError: working outside of request context

You can create a request context like this:

>>> with app.test_request_context('/'):
...     request.method
... 
'GET'

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1121196

See the Request Context documentation; you need to create a context explicitly:

>>> ctx = myapp.app.test_request_context('/', method='POST')
>>> ctx.push()
>>> myapp.index()

You can also use the context as a context manager (see Other Testing Tricks):

>>> with myapp.app.test_request_context('/', method='POST'):
...     myapp.index()
...

Upvotes: 9

Related Questions