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
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()
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With