Search code examples
pythonhtmlflaskredditpraw

Python How do I assigning a variable name with an HTML list to a (method?)


please forgive my poorly worded title as I am still learning Python. The problem is that in my Python script, I want the .hot to be replaced by a variable called instance which has a selection of options from my HTML file. Unfortunately, for some reason I don't yet understand, I can't just replace 'hot' with 'instance' or str(instance()). If someone could help me with a solution that would be great!

Thank you

Here is the Python Script in question

@app.route('/', methods=['POST'])
def index_post():
    subreddit = request.form['subreddit']
    instance = request.form['instance']
    num = request.form['limit']
    news = []
    i = 0
    for submission in reddit.subreddit(subreddit).hot(limit=int(num)):
        i += 1
        news.append(str(i) + '. ' + submission.title)
    return render_template("index.html", news=news)

Here is my HTML template.

<!doctype html>

<form action="." method="POST">
    Subreddit name:
    <input type="text" name="subreddit" placeholder="Topic">

    Instance:
    <select name="instance">
      <option value="controversial">Controversial</option>
      <option value="gilded">Gilded</option>
      <option value="hot">Hot</option>
      <option value="new">New</option>
      <option value="rising">Rising</option>
      <option value="top">Top</option>
    </select>

    Limit:
    <input type="number" name="limit">
    <input type="submit" value="Search">
</form>

{% for item in news %}
    <p> {{item}} </p>
{% endfor %}

Solution

  • If I understand your question right, you want to do something like this:

    redditFunction = getattr(reddit.subreddit(subreddit), instance)
    for submission in redditFunction(limit=int(num)):
        ...
    

    When instance is new this should call

    reddit.subreddit(subreddit).new(limit=int(num))

    gettattr gets the attribute on the first argument passed to it that is named with the second attribute. So you will get the function that is named in the instance variable, which (hopefully) is the function you are trying to call.