Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

flask

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
like image 509
Szymon Avatar asked Apr 01 '14 10:04

Szymon


Video Answer


1 Answers

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()
...
like image 173
Martijn Pieters Avatar answered Nov 16 '22 03:11

Martijn Pieters