gpt4 book ai didi

python - 如何在没有路由的情况下在Python Flask中执行普通函数并使用路由返回该过程的结果?

转载 作者:太空宇宙 更新时间:2023-11-03 15:06:52 26 4
gpt4 key购买 nike

应用程序正在加载“links_submit.html”,其中有一个字段,您可以在其中编写链接,例如 (www.google.com),然后您提交它,然后应用程序会以 HTTP Post 形式接收此 URL,并且重定向到另一个页面“post_response.html”,其中包含一个简单的 html,用于使用单词“Ok”进行反馈。然后我想用这个链接做一个过程(抓取谷歌并搜索特定的东西),完成这个过程后,自动从“post_reponse.html”重定向到另一个页面以显示我从谷歌提取的结果。现在我不知道如何对我的 Flask 上的应用程序说:“好吧,现在让我们使用普通函数(而不是路由),例如:

def loadpage(link_sent_by_the_http post):
res = requests.get('www.google.com')

想象一下,加载页面后,我还在谷歌上提取一些 html 标签,完成此过程后,我想将带有“ok”的页面“post_respose.html”重定向到一个新的 html 页面,其中包含从中提取的 html 标签谷歌。请注意,我知道如何加载谷歌页面并提取我想要的内容,但我不知道如何在 Flask 中间插入这个函数/进程,然后使用“ok”从普通 html 重定向到新路线我提取的结果。

import requests
from flask import Flask, render_template, request, url_for

app = Flask(__name__)

@app.route('/test')
def form():
return render_template('links_submit.html')

@app.route('/links/', methods=['POST'])
def links():
links=request.form['links']
return render_template('post_response.html')

Intern Process (Load the received link > Extract what I want)
and then redirect the "post_response.html" to another "html" which will
contain the results that I have extracted)

if __name__ == '__main__':
app.run(debug=True)

最佳答案

有两种方法-

创建一个 python 文件,例如 webfunctions.py 并将您的函数放入此文件中。例如-

def inc(x):
return int(x) + 1

现在,在您的 flask 应用程序文件中,您可以导入整个文件或仅导入函数 -

from webfunctions import inc

@app.route('/whatsnext/', methods=['POST'])
def waiting():
curVal=request.form['x']
nextVal = inc(curVal)
return render_template('post_response.html', nextVal=nextVal)

否则,您可以在 Flask 应用程序文件的顶部声明您的定义。就像下面这样 -

import requests
from flask import Flask, render_template, request, url_for

def inc(x):
return int(x) + 1


@app.route('/whatsnext/', methods=['POST'])
def waiting():
curVal=request.form['x']
nextVal = inc(curVal)
return render_template('post_response.html', nextVal=nextVal)

关于python - 如何在没有路由的情况下在Python Flask中执行普通函数并使用路由返回该过程的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44578151/

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