Python Flask: User Downloading Scraped Images - python

I have a little script that is an image scraper. Essentially, you provide the script with a link and it downloads all the images on the webpage to a folder on your desktop. I would like the same functionality but on the browser. I ant users to enter a link and the script starts downloading the images from the link to their computer. My Code Is Below:
#app.route('/')
def main():
return render_template('index.html')
#app.route('/Downlading', methods=['POST'])
def Downlading():
url= request.form['url']
start = request.form['start']
end = request.form['end']
dphy = image_downloader(url) #this is the script that saves the images
return str(dphy)
I am able to get the user url and pass it to image_downloader, which downloads the images. The problem is that the images get downloaded from the command prompt. I want the script to run inside the browser, just like it would run in my IDE. Sorry if this is confusing.
My HTML code:
<form action="/Downlading" method="POST" >
URL: <input type="text" name="url"><br/>
Start: <input type="text" name="start"><br/>
End: <input type="text" name="end"><br/>
<input type="submit" name="form" value="Submit" />
</form>

You need to create an HTML template for the variable to be reflected on. For example:
HTML - upload.html:
<html>
<title>Example on StackOverflow</title>
<p> The str representation of the variable dphy is {{ dphy }} </p>
</html>
Python (add this to existing flask script):
#app.route('/Downlading', methods=['POST'])
def Downlading():
url= request.form['url']
start = request.form['start']
end = request.form['end']
dphy = image_downloader(url) #this is the script that saves the images
return render_template('upload.html', dphy=str(dphy))
This should work, but I can't test it right now so I'm not positive. This is the basic idea for passing variables through Flask - create a template that uses the variable, then pass it in explicitly when rendering that created template.

Related

How to replace standard input () with flask form in Python

My question is similar to Replacing input() portions of a Python program in a GUI. But I need a web UI not desktop UI(tkinter based solution as answered in the link)
You will have to create a webpage with HTML/CSS and create a form in it to get the input. Then, you will have to link the webpage with your backend (flask) to receive the input in python and manipulate as needed. Following a tutorial like this one will help you get started. Or, you can simply search the web for "Form handling in Flask" to find something that suits your needs.
Say you're asking for the user to input their username. You'd do something like this.
HTML
<body>
<form action="" method="post">
<input type="text" placeholder="" value="{{ request.form.username }}">
<input type="submit" value="Submit">
</form>
</body>
Whatever you want to call your variable, you put after request.form
In your program (where you import flask), also import request from flask like so:
from flask import request
Under your route's function, check if the request's method is POST and assign your form variable:
def index():
if request.method == "POST":
foo = request.form["username"]
return render_template("index.html")
So when the user clicks the submit button, foo will be whatever they put in the text box.
You can see more at https://flask.palletsprojects.com/en/1.1.x/quickstart/#accessing-request-data

Taking user input from HTML form as a variable for Python script [duplicate]

This question already has answers here:
Sending data from HTML form to a Python script in Flask
(2 answers)
Closed 3 years ago.
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
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
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.

Read a python rewritten image in Flask

I have code using Flask as given below:
app = Flask(__name__,static_url_path='/static')
#app.route('/')
def my_form():
return render_template('my-form.html')
#app.route('/result', methods=['POST'])
def result():
text = request.form['Name']
sentiment = generateimage(text)
return render_template("result.html")
my-form.html
<div class="col-lg-1"></div>
<div class="col-lg-10">
<form action="http://localhost:5505/result" method="POST">
<div class="form-group">
<label for="comment">Text</label>
<textarea class="form-control" rows="10" cols="4" id="comment" name="Name"></textarea>
</div>
<input type="submit" class="btn btn-info" value="Analyze">
</form>
</div>
</div>
result.html
<img src ="/static/fig1.png"/>
What flask.py does is grab the text from my-form, process it and generate an image in a static folder, but when the result.html page loads up it displays the previously generated image and not the most recent one.
How do I solve this issue?
def generateimage(text)
######some code######
plt.savefig('/home/aurora/Desktop/sentiment/static/fig1.png', dpi=dpi)
I'll assume that this is a caching issue, otherwise your first call to the system would not produce an image at all. A quick and dirty hack is to just force your image not to be cached by adding a random query string after the image URL within the result.html:
<img src ="/static/fig1.png?{{no_cache}}"/>
And then just call it from your Flask app as:
return render_template("result.html", no_cache=time.time()) # import time, of course
This, kind of, defeats the purpose of static content - if you're always going to render the image based on user input there is little point in storing it at all - just create a different Flask endpoint that will render the image directly to the user without ever storing it and call that instead of the image's static URL.

flask html input format

I am trying to read a file in using python/Flask and display it at the click of a button. To view the file, a return function like this works fine:
return redirect(url_for('uploaded_file',filename=filename))
But I am trying to implement in HTML to view file at a click. Something like this:
<form><input action="redirect(url_for etc. ??)" type=submit value=viewFile> </form>
What would be the correct syntax for action?
Thanks for any hint.
The action attribute should go on <form>, not <input>. The value of action should just be the URL of your route which accepts the file. Assuming you're using Jinja2, something like this:
Jinja2:
<form action="{{url_for('upload')}}" enctype="multipart/form-data">
<input type="file" name="view_file">
<input type="submit" value="Upload">
</form>
Python:
#app.route('/upload', methods=['POST'])
def upload():
# Handle upload and save to disk here..
return redirect(url_for('uploaded_file', filename=filename))
#app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
See also http://flask.pocoo.org/docs/0.11/patterns/fileuploads/ (it looks like you are already working from that example..)
This code worked for me to pass filename to html form input.
python:
...
return render_template('view.html', cat = filename)
html (view.html):
<!doctype html>
<form action="{{url_for('uploaded_file', filename=cat)}}" enctype="multipart/form-data">
<input type=submit value='view file'>
</form>

How to include more than one HTML-form in a FLASK view?

I´m building a little web application using python 2.7 and flask (my first one).
I´m trying to include three HTML forms in one flask view to have all three of the forms on one webpage:
One form to allow data upload (will be an XML-file)
One Button to start a python process, that performs analysis on the XML-file
One Button that allows download of the results of step 2
While I got it working, when using a separate view for each of the three steps, I somehow can´t get it done when trying to include all three steps in one view. Does anyone know what I am doing wrong?
Here´s my code so far. The HTML-code is included in the python script. Working with templates didn´t help me either. The HTML page is working, but the buttons don´t perform any action.
...
#app.route('/PAM', methods=['GET', 'POST'])
def start_PAM():
if request.method == 'POST':
if "Upload" in request.form.values():
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
print "File upload complete !!"
return redirect('/PAM')
elif "Start PAM" in request.form.values():
import os
os.system("D:\Python_Test\PAM\PAM_1st_Try.py")
print "PAM Process Finished!!"
return redirect('/PAM')
elif "Download" in request.form.values():
filename = "FILE.XML"
return redirect(url_for('download_file', filename=filename))
return '''
<!doctype html>
<title>Start PAM Process</title>
<h1>XML Upload</h1>
<form action="" method=post enctype=multipart/form-data>
<p><input type=file name=file>
<input type=submit value=Upload>
</form>
<p><h1>Start the PAM Process</h1>
<form name='Start PAM' method='POST'>
<p><input type="submit" value="PAM" class="submitButton"/>
</form>
<p><h1>Download Result</h1>
<form name='Download' method='POST'>
<p><input type="submit" value="Download" class="submitButton"/>
</form>
'''
#app.route("/downloads/<filename>")
def download_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename, as_attachment=True)
app.debug = True
if __name__ == '__main__':
app.run()
I think the step you're missing is to assign an action to the forms. At the moment the HTML doesn't know what to do with the form?
http://www.w3schools.com/tags/att_form_action.asp

Categories

Resources