![](/img/trans.png)
[英]How can you call a function which is defined in app.py, from HTML template rendered by app.py, on flask
[英]Flask: How to pass the value of a variable from app.py and display it on a html page
我需要幫助,所以我的 app.py 中的這個 function 查詢一個 API 並得到一個響應,其中包含一個名為“選擇”的數組,數組的第一個 object 是我正在檢索並保存在“答案”中的內容“ 多變的
`
def openAIQuery (query):
response = openai.Completion.create(
model="text-davinci-003",
prompt= query,
temperature=0.7,
max_tokens=1000,
top_p=1,
frequency_penalty=0,
presence_penalty=0)
if 'choices' in response:
if len(response['choices']) > 0:
answer = response["choices"][0]["text"]
else:
answer = "Oops sorry, you beat DaVinci this time"
else:
answer = "Oops sorry you beat DaVinci this time"
return answer
This function is another function in my app.py that should assign the returned "answer" in the openAIAnswer variable
@app.route('/product-description', methods=["GET", "POST"])
def productDescription():
if request.method == 'POST':
submission = request.form['productDescription']
query = "Write a detailed product description for: {}".format(submission),
openAIAnswer = openAIQuery(query)
prompt = 'DaVinci Suggestions for {} are: '.format( submission )
return render_template("product-description.html" )
`
我的問題是我想在我的模板目錄中的另一個 html 頁面中顯示提示和 openAIAnswer 的值,但它確實有效
`
<div class="p-3 rounded">
<div class="row">
<div class="col-lg-12">
<h3 class="text-primary">{{prompt}}</h3>
<p class="lead">{{openAIAnswer}}</p>
</div>
</div>
</div>
`請我需要解決方案
每當我運行該應用程序並執行必要的操作時,我都會從錯誤日志中看到我的 API 請求返回了
response_code=200
但我的 HTML 頁面不顯示 openAIAnswer 以及 html 頁面上的提示,這正是我想要實現的
我后來使用了 locals() 方法,該方法返回一個字典,其中包含當前程序的所有局部變量和符號,例如,我在這里添加了它return render_template("product-description.html", **locals( ))
和代碼工作過
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.