5

I'm creating a web app in Python/Flask to display tweets using twitters API using tweepy. I have set up an HTML form, and have got the script that finds the tweets with a certain input, currently, this is hard coded. I want the users to input a hashtag or similar, and then on submit, the script to run, with that as its parameter

I've created a form, with method GET and action is to run the script.

<form class="userinput" method="GET" action="Tweepy.py">
    <input type="text" placeholder="Search..">
    <button type="submit"></button>
</form>

I dont know how I would get the users input and store it in a variable to use for the tweepy code, any help would be greatly appreciated

1
  • 3
    Judging by action="Tweepy.py" you do not seem to grasp how HTML forms work. You need to have a webserver that renders the HTML page with the form, then submit the form's content back to the server (preferably using POST, not GET) to a predefined route in your flask app. Flask even has a built-in way to achieve this (which is probably an overkill but it's a good place to start: flask.pocoo.org/docs/1.0/patterns/wtforms) Commented Apr 1, 2019 at 13:55

2 Answers 2

7

templates/index.html

<form method="POST">
    <input name="variable">
    <input type="submit">
</form>

app.py

from flask import Flask, request, render_template
app = Flask(__name__)

@app.route('/')
def my_form():
    return render_template('index.html')

@app.route('/', methods=['POST'])
def my_form_post():
    variable = request.form['variable']
    return variable
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer! I've added the variable into my tweepy code. I have also created a method with it in, and I call that method just before ` return variable` however, it doesn't seem to be doing anything. The tweepy code is meant to send it's output to a database (which it does)
If you post your code here it would be easier to find your mistake
@app.route('/results', methods=["POST"]) def my_form_post(): variable = request.form['variable'] tweepy() return variable
Look above, I edited my answer
1

I guess you have set up and endpoint to run that script, an URL mapped to a function. In that case you need to call it from the form action.

for example

@app.route('/my-function')
def your_function(parameters):
    "code to do something awesome"
    return "the result of your function"

So, in your form you should:

<form class="userinput" method="GET" action="/my-function">
    <input type="text" placeholder="Search..">
    <button type="submit"></button>
</form>

That should do the trick.

Go to the Flask home page for more examples.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.