簡體   English   中英

重置 Flask 渲染模板 output

[英]Reset Flask render_template output

我目前正在為 Battlefy 網站制作解析器,以快速提取結果並將其轉換為 wikicode。

網址: http://tomshoe02.pythonanywhere.com/scraper

實際操作示例: https://i.imgur.com/1lj98cP.png

要解析的示例鏈接: https://dtmwra1jsgyb0.cloudfront.net/stages/6000c862d9155d46db7f41ca/rounds/1/matches

完整的app.py:https://pastebin.com/J2nsfmFa

app.py 代碼片段:

@app.route("/", methods=["GET", "POST"])
@app.route("/lol", methods=["GET", "POST"])
@app.route("/scraper", methods=["GET", "POST"])
def scraper():
    form = BattlefyForm()
    if form.validate_on_submit():
        url = form.matchhistory.data
        result = jloader(url)
        '''
        #result = url
        result = subprocess.check_output([sys.executable,
            "{}/stuff.py".format(directory), url]).decode('iso-8859-1')
        '''
        return render_template("scraper.html", form=form, result=result)
    return render_template("scraper.html", form=form)

每次我在不重新加載 web 應用程序的情況下提交時,新結果都會顯示在舊結果中。 是否有一個模塊可以用來清除 session 緩存並重置網站的 state,而無需在每次提交新的 ZE6B391A8D2C4D45902A23A8B6585703 時都重新加載應用程序?

我不同意阿基布。 無論是在接收到表單數據后執行重定向,還是重新渲染整個頁面並作為來自服務器的響應發送,都無關緊要。
每次調用后,無論是通過 POST 還是 GET 請求,都會重新加載並呈現整個頁面。 這可以使用 ajax 來減少。 但是,這不會導致您的問題。

問題不在於您的路線,而在於您的stuff.py模塊。
您使用全局變量將從加載的 JSON 文件中提取的結果保存在列表中。
第一個解決方案是每次jloader(url)時清空這些列表。 但這並不能完全解決問題。
如果多個用戶同時開始通話,這將導致意外的錯誤結果。 由於如果再次清空列表並填寫更多結果,則無法完成先前的請求。
此外,只要不是絕對必要,就應該避免使用全局變量。
由於列出的原因,我建議您不要使用全局變量並將列表作為局部變量保留在 function 中,為每個請求保留並在最后返回。

這是一種使代碼更清晰且無需全局變量的方法。 我只重寫了您的代碼的摘錄。 我認為您可以自己添加 rest。

import requests
from collections import namedtuple
from datetime import datetime
import gspread

class Match(namedtuple('Match', ['team_a', 'team_b', 'score_a', 'score_b'])):

    @property
    def winner(self):
        if self.score_a > self.score_b:
            return self.team_a
        elif self.score_a < self.score_b:
            return self.team_b
        return None

    def fmt(self):
        return '{{'\
            f'MatchSchedule|team1={self.team_a}|team2={self.team_b}'\
            f'|team1score={self.score_a}|team2score={self.score_b}'\
            f'|winner={self.winner}|date=...|time=...|timezone=PST|'\
            'dst=yes|vod1=|stream='\
            '}}'

def _get(data, key_path, default=None):
    tmp = data
    for k in key_path.split('.'):
        try:
            tmp = tmp[k]
        except KeyError:
            return default
    return tmp


def get_matches(url, team_alias={}):
    data = requests.get(url).json()

    for item in data:
        top_team = _get(item, 'top.name', _get(item, 'top.team.name'))
        low_team = _get(item, 'bottom.name', _get(item, 'bottom.team.name'))
        top_score = _get(item, 'top.score')
        low_score = _get(item, 'bottom.score')

        # Test for results that are None and react accordingly. 
        # The date and time queries are missing here. 

        top_team = team_alias.get(top_team, top_team)
        low_team = team_alias.get(low_team, low_team)

        match = Match(top_team, low_team, top_score, low_score)
        yield(match)

def get_teams():
    gc = gspread.service_account(filename='credentials.json')
    sh = gc.open_by_key('1N7wnIRWJRbULKychJU-EOyisuZBX1rgXwdW91Keki4M')

    col_name = worksheet.col_values(1)
    col_alias = worksheet.col_values(2)

    return dict(zip(col_name, col_alias))

def load_data(url):
    '''Use this instead of jloader(url).'''
    team_alias = get_teams()
    return '\n'.join(match.fmt() for match in get_matches(url, team_alias))

def main():
    url = 'https://dtmwra1jsgyb0.cloudfront.net/groups/5f60cffb30d29b119e36b42b/matches'
    dat = load_data(url)
    print(dat)

if __name__ == '__main__':
    main()
``

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM