简体   繁体   中英

Python-Flask - render template within a class gives 404

I am trying to run python with html using flask locally, i try to render a template within a class object, it compiles but when i try to access it on http://localhost:5000 it gives me 404. Could anyone tell what I'm doing wrong here?

I am trying to display values from a json format using chart.js library.

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')

I don't think template rendering is the issue here. You can just return a string from your view as an example.

You get a 404 because that's not how you do classy views in flask. You can have a look here: http://flask.pocoo.org/docs/0.12/views/

But essentially you have to extend from flask.views.View and then manually attach your route to app instance, so it looks something like this:

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM