我myapp.py是这样的:
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()
Run Code Online (Sandbox Code Playgroud)
我有一个简单的问题.如何在Python index()中的if语句(8到13行)中调用函数并执行代码?
我试过这样的方式:
>>> import myapp
>>> myapp.index()
Run Code Online (Sandbox Code Playgroud)
但我收到的消息是:
RuntimeError: working outside of request context
Run Code Online (Sandbox Code Playgroud)
请参阅请求上下文文档; 您需要显式创建上下文:
>>> ctx = myapp.app.test_request_context('/', method='POST')
>>> ctx.push()
>>> myapp.index()
Run Code Online (Sandbox Code Playgroud)
您还可以将上下文用作上下文管理器(请参阅其他测试技巧):
>>> with myapp.app.test_request_context('/', method='POST'):
... myapp.index()
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7854 次 |
| 最近记录: |