0

Hello can anyone help? I am quite new to practicing FLASK, and my python experience has been mainly around print statements than return values, and I am not sure why return is not acting as print would.

This is my draft of a flask app, e.g. app.py

import my_algorithms

from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/')
def my_form():
    return render_template('my-form.html')

@app.route('/', methods=['POST'])
def my_form_post():
    text = request.form['text']
    return text + str(my_algorithms.receive_text_from_form(text))

I receive the variable text from a web page form.

If I do the following code my_algorithms.py as a print command and run in command line prompt or IDLE I get the results that I want, i.e. multiple news headlines

def receive_text_from_form(text):
    news_keyword = text

    # https://newsapi.org/docs/client-libraries/python
    newsapi = NewsApiClient(api_key='0fb13acc3bc8480eafedb87afa941f7e')


    # /v2/everything
    data = newsapi.get_everything(q=news_keyword)

    jdict = data.get('articles')


    for row in jdict:
        print(row['title'])

However if I do the code above as a return, I only get one result returned back to my flask app.py

def receive_text_from_form(text):
    news_keyword = text

    # https://newsapi.org/docs/client-libraries/python
    newsapi = NewsApiClient(api_key='0fb13acc3bc8480eafedb87afa941f7e')


    # /v2/everything
    data = newsapi.get_everything(q=news_keyword)

    jdict = data.get('articles')


    for row in jdict:
        return(row['title'])

Any ideas what I am doing wrong?

Christopher
  • 427
  • 1
  • 8
  • 18
  • You're only returning one thing with the loop statement you have. That may be a starting point. – Makoto Dec 18 '20 at 20:59
  • Hi Makoto, I am not sure if I follow? There is more than one title in the data, doing a print seems to print them all. How can I make a return , return them all? – Christopher Dec 18 '20 at 21:05
  • A print statement prints a single value. A return statement returns the collection. – Makoto Dec 18 '20 at 21:16
  • Thanks for help. I have found the solution that I needed here. https://stackoverflow.com/questions/44564414/how-to-use-a-return-statement-in-a-for-loop def show_todo(): my_list = [] for key, value in cal.items(): my_list.append((value[0], key)) return my_list – Christopher Dec 18 '20 at 21:24

1 Answers1

1

I have found the solution that I need here

How to use a return statement in a for loop?

def show_todo():
    my_list = []
    for key, value in cal.items():
        my_list.append((value[0], key))
    return my_list
Christopher
  • 427
  • 1
  • 8
  • 18