11

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
2
  • http://localhost:5000/ works fine in a browser though? Just checking what you are really stuck on. Commented Apr 1, 2014 at 10:29
  • I was wondering about the capabilities of calling flask functions standalone outside of the __main__ context. Ideally I would be able to reuse all the view rendering from an offline context, that is not from the flask app session but another python module which automated rendering the templates from some scheduler by writing to disk a bunch of static pages whose content was generated by the flask functions. Commented May 16, 2019 at 4:52

2 Answers 2

9

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()
...
Sign up to request clarification or add additional context in comments.

Comments

1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.