我的 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()
我有一个简单的问题。 如何在Python中调用index()
函数,只在if
语句(8-13行)中执行代码?
我这样试过:
>>> import myapp
>>> myapp.index()
但我收到消息:
RuntimeError: working outside of request context
最佳答案
参见 Request Context文档;您需要显式创建上下文:
>>> ctx = myapp.app.test_request_context('/', method='POST')
>>> ctx.push()
>>> myapp.index()
您还可以将上下文用作上下文管理器(请参阅 Other Testing Tricks):
>>> with myapp.app.test_request_context('/', method='POST'):
... myapp.index()
...
关于python - 如何从 Python 中的 Flask 应用程序调用某些函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22782856/