gpt4 book ai didi

python - 如何从 Python 中的 Flask 应用程序调用某些函数?

转载 作者:太空狗 更新时间:2023-10-29 20:56:15 29 4
gpt4 key购买 nike

我的 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/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com