Python-Flask - 类中的渲染模板给出了404

时间:2018-02-06 11:19:19

标签: python flask

我试图在本地运行使用烧瓶的html python,我尝试在类对象中渲染模板,它编译但是当我尝试在http://localhost:5000上访问它时它给了我404.有人能说出什么我在这里做错了吗?

我正在尝试使用chart.js库来显示json格式的值。

from flask import Flask
from flask import render_template
import os.path
import json

app = Flask(__name__)

#import the json file

_player_json_file = os.path.join(os.path.dirname(__file__), 'players.json')

def read_players(player_file=None):
    if player_file is None:
        player_file = _player_json_file
        try:
            data = json.loads(open(player_file).read())
        except IOError:
            return {}

        #make player dictionary

        players = {}

        #get player ID from json file = data.

        for playerID in data:
            players[playerID] = Player_data(data[playerID])
            return players


class Players_Data (object):
    @app.route("/")
    def __init__(self, data):
        """
        Assign all the values from the json file to new variables
        the values are birth date age weight...

        """
        self.player_ID = data['gsis_id']
        self.gsis_name = data.get('gsis_name', '')
        self.player_fullname = data.get('full_name', '')
        self.player_first_name = data.get('first_name', '')
        self.player_last_name = data.get('last_name', '')
        self.player_weight = data.get('weight','')
        self.player_height = data.get('height' , '')
        self.player_birth = data.get('birthdate', '')
        self.player_pro_years = data.get('years_pro', '')
        self.player_team = data.get('data', '')
        values = [player_ID,gsis_name,player_fullname,player_first_name,player_last_name,player_weight]
        return render_template('chart.html', data=data, values=values)


    if __name__ == "__main__":
        app.run(host='localhost')

1 个答案:

答案 0 :(得分:0)

我认为模板渲染不是问题所在。您可以从视图中返回一个字符串作为示例。

你得到404因为那不是你在烧瓶中做出优雅观点的方式。您可以在这里查看:http://flask.pocoo.org/docs/0.12/views/

但基本上你必须从flask.views.View扩展,然后手动将路由附加到app实例,所以它看起来像这样:

from flask import Flask
from flask.views import View

app = Flask(__name__)


class Players_Data(View):
    def dispatch_request(self):
        return 'LOL'


app.add_url_rule('/', view_func=Players_Data.as_view('show_users'))


if __name__ == "__main__":
    app.run(host='localhost')