4

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

Amy
  • 63
  • 1
  • 1
  • 4
  • 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: http://flask.pocoo.org/docs/1.0/patterns/wtforms/) – DeepSpace Apr 01 '19 at 13:55

2 Answers2

6

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
irezwi
  • 789
  • 8
  • 14
  • 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) – Amy Apr 01 '19 at 14:46
  • If you post your code here it would be easier to find your mistake – irezwi Apr 01 '19 at 14:49
  • `@app.route('/results', methods=["POST"]) def my_form_post(): variable = request.form['variable'] tweepy() return variable` – Amy Apr 01 '19 at 14:51
  • Look above, I edited my answer – irezwi Apr 01 '19 at 15:21
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.

Emmanuel Valdez
  • 419
  • 6
  • 9