简体   繁体   中英

Returning Data from Python Function for use with Jinja2 Template (Flask)

I'm doing my best to learn Python, and I think I'm coming along ok, but I'm stuck here.

I am pulling data from the OMDB API. I want the data returned to populate a template for a site I'm making with Flask.

So far I'm getting data back from the API just fine with this code:

import requests


class Movie(object):
    def __init__(self, **kwargs):
        for key, val in kwargs.items():
            setattr(self, key.lower(), val)


def search():
    base_url = 'http://www.omdbapi.com/?'
    title_search = 't={}'.format(raw_input('Search for a movie title. '))
    url = '{}{}&y=&plot=&short&r=json&tomatoes=true'.format(
           base_url, title_search)
    omdb_url = requests.get(url)
    movie_data = omdb_url.json()

    movie = Movie(**movie_data)

    print movie.title
    print movie.plot
    print movie.director
    print movie.rated
    print movie.imdbrating
    print movie.tomatofresh

search()

Where I'm stuck is how to get the values that I'm currently printing (movie.title, movie.plot, etc.) into my flask template. So far I have this:

from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def index():
    context = {'title': movie.title, 'plot': movie.plot,
               'director': movie.director, 'rated': movie.rated,
               'imdbrating': movie.imdbrating,
               'tomatofresh': movie.tomatofresh}

    front_page = render_template('index.html', **context)
    return front_page

In my template I have things like {{ movie.title }}, which is where things don't seem to work. If I just leave the template as html, render_template('index.html') renders just fine. However, I can't figure out how to get the data from the API into those template regions. Sorry if this is stupid. This is my first question on here. Thank you in advance for any help.

render_template('index.html', **context)

This is the important line. **context controls what you pass to your template. Its keys are the names of the variables available. To include the value of movie.title in your template, use

{{ title }}

Alternatively, you can remove context from index entirely and call

render_template('index.html', movie=movie)

This will give your template access to a variable called movie . You can then print out the title using

{{ movie.title }}

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