Flask表单在提交时将表单数据附加到url

问题描述 投票:0回答:2

我有HTML表单

<form>
 <input type="text" name="keyword" id="keyword" />
<input type="submit">Submit</input>

提交时,我想将表单数据传递给flask应用]

requests.py

def search_news(keyword):
search_news_url = 'https://newsapi.org/v2/everything?q={}&language=en&apiKey={}'.format(keyword,api_key)
with urllib.request.urlopen(search_news_url) as url:
    search_news_data = url.read()
    search_news_response = json.loads(search_news_data)

    search_news_results = None

    if search_news_response['articles']:
        search_news_list = search_news_response['articles']
        search_news_results = process_search_results(search_news_list)

return search_news_results

def process_search_results(search_news_list):
news_results = []
for search_results_item in search_news_list:
    author = search_results_item.get('author')
    title = search_results_item.get('title')
    description = search_results_item.get('description')
    url = search_results_item.get('url')
    urlToImage = search_results_item.get('urlToImage')
    publishedAt = search_results_item.get('publishedAt')
    content = search_results_item.get('content')
    totalResults = search_results_item.get('totalResults')

    if content:
        news_results_object = Everything(author,title,description,url,urlToImage,publishedAt,content,totalResults)
        news_results.append(news_results_object)
return news_results

views.py

from ..requests import get_everything,search_news
....
@main.route('/')
    def index():
    everything = get_everything()
    title = 'News Highlight'
    searching_news = request.args.get('keyword')

if searching_news:
    redirect(url_for('.search',keyword = searching_news))
return render_template('index.html',title = title,everything = everything)


....
@main.route('/search/<keyword>')
def search(keyword):
keyword_list = keyword.split(" ")
keyword_format = '%20'.join(keyword_list)
searched_news = search_news(keyword_format)
title = f'Search results for {keyword} '
return render_template('search.html',searched_news = searched_news)

在表单提交时,它会将表单数据附加到url上,如下所示:

http://127.0.0.1:5000/?keyword=game+of+thrones

我已经尝试过使用post方法,但是我得到了服务器不支持方法错误。谁能帮忙。

但是当我附加这样的链接时:

http://127.0.0.1:5000/search/game%20%of%thrones

该应用搜索并显示结果

python forms flask search python-requests
2个回答
0
投票

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.