I am trying to create a GUI where I will have 2 buttons. Start button will trigger my python script and display the moving graph. When I press the stop button, the graph should exit and python should stop.
when I click on start button, I am getting the desired result. But it goes to infinite loop and the stop button does not exit the code.Clicking on stop button does not take the code to the decorator and my function stop() is not executed.
Below is the snippet :
from flask import Flask, request, flash, url_for, redirect, render_template, session
from flask import render_template
import numpy as np
import matplotlib.pyplot as plt
import io
import threading
import base64
from IPython import get_ipython
from sys import exit
app = Flask(__name__)
#app.route('/')
def home():
return render_template('home.html')
#app.route('/plot' , methods = ['GET', 'POST'])
def build_plot():
img = io.BytesIO()
global running
x = np.linspace(-180, 180,1000)
y = np.sin(x)
global j
fig, ax = plt.subplots()
plt.plot(x[0:200], y[0:200])
#plt.plot(x,y)
for i in range(200, len(y)):
plt.scatter(x[i], y[i])
plt.pause(0.0005)
return(get_ipython().run_line_magic('matplotlib', 'inline'))
#app.route('/stop' , methods = ['GET', 'POST'])
def stop():
#stop_ind='N'
#exit()
return render_template('home.html')
if __name__ == '__main__':
app.debug = True
app.run()
The function where I want to exit is not getting called.
Below is my HTML :
<!DOCTYPE html>
<html>
<title>HOME PAGE..</title>
<body>
<h1>Home Page..!!</h1>
<form action="/plot" method="POST">
<input type="number" name="Number" ><br>
<br>
<input type="submit" value="Start" >
</form>
<form action="/stop" method="POST">
<br>
<input type="submit" value="Stop" >
</form>
</body>
</html>
</form>
</body>
</html>
Your Flask app can not respond to your input because it is busy in your loop.
You will need to put the calculation of your results in a separate Thread or Coroutine in order to stop it from blocking your main Flask Thread.
Also you can use Websockets to communicate with your Frontend. Have a look at Flask-SocketIO. It uses Websockets to communicate between Flask and your Frontend.
Related
I have a basic HTML Form with file input that accepts multiple files. When the user clicks on Upload button I want to print numbers till 10**9 on my terminal.Say while execution of loop the user clicks refresh/reload, I want to stop current loop and redirect to index page. But even after hitting refresh the loop continues to execute.
index.html
<form method="POST" action="upload" enctype="multipart/form-data" class="uploader">
<input id="file-upload" type="file" name="fileUpload" accept=".ent,.pdb" multiple/>
<input type="submit" class="btn btn-primary" value="Upload"/>
</form>
app.py
from flask import Flask, render_template, redirect
UPLOAD_FOLDER = 'uploads'
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
#app.route("/")
def index():
return render_template("index.html")
#app.route('/upload',methods = ['GET','POST'])
def upload_file():
t=0
while(t<10**9):
print(t)
t+=1
return redirect('/')
if __name__ == '__main__':
app.run(debug=True)
So I've been working or a quick small project and I have that issue
from bottle import get, post, request, run, redirect
import threading
#get('/button')
def button():
return '''
<form action="/button" method="post">
<input type="submit" value="Push"/>
</form>
'''
#post
def action():
print ("button pushed")
global pushed
pushed = True
redirect("/button")
threading.Thread(target=run, kwargs=dict(host='localhost', port=80)).start()
pushed = False
print("Started")
while 1:
if pushed:
print("push recv")
pushed = False
I'm running my code using "sudo python3 code.py"
You haven't attached a route to your #post declaration. It should be:
#post('/button')
I am trying to call a regular function into RadioField - choices[()].
when i select a radio button on my web page and click submit button, i should get the result from from function. my function says to print("Hi").
currently it print's the data on given value like 'value_one' when i select description.
So, i need a way to do call function to choices[('')].
below is my code
from flask import Flask, render_template
from flask_wtf import Form
from wtforms import RadioField, SubmitField
app = Flask(__name__)
app.config.from_object(__name__)
app.secret_key = 'password'
def print_1():
print("Hi")
class SimpleForm(Form):
example = RadioField('Label', choices=[('value_one','description'),('value_two','whatever')])
#app.route('/',methods=['post','get'])
def hello_world():
form = SimpleForm()
if form.validate_on_submit():
print(form.example.data)
else:
print(form.errors)
return render_template('form.html',form=form)
if __name__ == '__main__':
app.run(debug=True)
Below is my html code:
<form method="post">
{{ form.hidden_tag() }}
{{ form.example }}
<input type="submit" value="submit">
</form>
I have the following Python script which is using Flask-socketio
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
from time import sleep
app = Flask(__name__)
app.config['SECRET_KEY'] = 'P#ssw0rd'
socketio = SocketIO(app)
#app.route('/')
def index():
return render_template('index.html')
#socketio.on('connect')
def on_connect():
payload1 = 'Connected!!!'
payload2 = 'Doing thing 1'
payload3 = 'Doing thing 2'
emit('send_thing', payload1, broadcast=True)
sleep(2)
emit('send_thing', payload2, broadcast=True)
sleep(2)
emit('send_thing', payload3, broadcast=True)
if __name__ == '__main__':
socketio.run(app)
And here is the corresponding index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>SocketIO Python</title>
</head>
<body>
<div id="my-div"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.5/socket.io.js"></script>
<script>
(function init() {
var socket = io()
var divElement = document.getElementById('my-div')
socket.on('send_thing', function(payload) {
var dataElement = document.createElement('inner')
dataElement.innerHTML = payload
divElement.appendChild(dataElement)
})
})()
</script>
</body>
</html>
What I am trying to achieve is that when a client connects, it first says 'Connected!!!' and then 2 seconds later a new 'inner' element appears that says 'Doing thing 1' followed by 2 seconds later a new 'inner' element appears that says 'Doing thing 2' etc.
But what is happening is that when a client connects, it sends all 3 lines at the same time (after 4 seconds which is both sleep statements). This is the first time using SocketIO so I'm sure I've done something wrong.
When you use eventlet or gevent, the time.sleep() function is blocking, it does not allow any other tasks to run.
Three ways to address this problem:
Use socketio.sleep() instead of time.sleep().
Use eventlet.sleep() or gevent.sleep().
Monkey patch the Python standard library so that time.sleep() becomes async-friendly.
I have a simple python file that sends a file from a local directory to be displayed in html. And, when the user clicks submit, I want to save this file to a different directory, but I can't seem to make this happen.
Here's my code:
Uploader.py
from __future__ import print_function
from random import choice
from flask import Flask, request, redirect, url_for, flash, render_template, abort, send_file, session
from werkzeug.utils import secure_filename
from flask import send_from_directory
import sys, os
app = Flask(__name__)
#app.route('/')
def init(file_Idx=0):
files = os.listdir(DOWNLOAD_FOLDER)
filePath = os.path.join(DOWNLOAD_FOLDER, files[file_Idx])
return render_template('files.html', file=filePath)
#app.route('/upload', methods=['POST'])
def upload_file():
file = request.files['image'] #Failing here!!!
f = os.path.join(app.config['UPLOAD_FOLDER'], file.filename)
file.save(f)
return render_template('files.html')
files.html
<form action="/upload" method="post" enctype="multipart/form-data">
<img src="{{file}}"/>
<input type=submit name="image">
</form>
Right now the image is displaying, but I can't seem to pass the file to upload_file() to save it in the upload_folder. How can I make this work?
Try this, you can define your desired path in it.
You can Edit the line
file.save(os.path.join("/tmp/", filename))
and place your desired path in it.
from flask import Flask, render_template, request
from werkzeug import secure_filename
app = Flask(__name__)
#app.route('/upload')
def upload_file():
return render_template('upload.html')
#app.route('/uploader', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST':
file = request.files['file']
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
file.save(os.path.join("/tmp/", filename))
if __name__ == '__main__':
app.run(debug = True)
and HTML code for that
<form id="package_form" action="" method="POST">
<div>
<p>Upload Packages:</p>
<p><input id="upload_button" type="file" class="btn btn-default btn-xs" name="file"></p>
<p><input id="submit_button" type="submit" class="btn btn-success" value="Upload">
</div>