I've just joined this platform, i am amateur at python, i tried to do something at python, i want to design a basic website with python flask module, i want to get data from other py files but when i run the main program data comes just once, i want to get data frequently like each 1 seconds etc. i want to get "c" value (at from plc.py) each second. like auto update from other py file.
my main program is;
from multiprocessing import Process,Queue,Pipe
from flask import Flask, jsonify, render_template, request
from flask_apscheduler import APScheduler
import webbrowser
import time
from plc import c
app = Flask(__name__)
scheduler = APScheduler()
#app.route('/_stuff', methods = ['GET'])
def stuff():
return jsonify(result=c[3]) # c[3] yerine time.asctime() yazınca değişken veri geliyor
def scheduledTask():
print(c)
return (c)
#app.route('/')
def index():
return render_template('dy1.html')
if __name__ == '__main__':
scheduler.add_job(id='Scheduled task', func=scheduledTask, trigger='interval', seconds=5)
scheduler.start()
app.run(debug=True, use_reloader=True)
Related
I am trying to send Keyboard typed data to a webpage using Flask SSE following this tutorial. I could send the data. But the problem is that I could send the data only when the cursor is focused on the terminal (I am using input() method in an infinite loop to capture data).
Since I want to capture data even though the cursor is not focused in the terminal I tried using the keyboard module (record() method). Though I could successfully run and capture in a separate program, I couldnt run it in Flask code. I am running the following code.
import gevent
from gevent.pywsgi import WSGIServer
from gevent import monkey
monkey.patch_all()
from numpy import random
from flask import Flask, json, Response, render_template
import keyboard
import sys
app = Flask(__name__)
def event():
while True:
print("Inside")
recorded_events = keyboard.read_key(suppress=True);
#app.route('/')
def index():
return render_template('index.html')
#app.route('/stream/', methods=['GET', 'POST'])
def stream():
return Response(event(), mimetype="text/event-stream")
if __name__ == "__main__":
WSGIServer(('', 5001), app).serve_forever()
Aren't you supposed to yield the values?
def event():
while True:
yield keyboard.read_key(suppress=True)
I'm trying to write a Python application that will execute certain code repeatedly on a timer when that timer is enabled. I'd like to be able to enable/disable the timer from a web page. I've been attempting to do this with Flask and the sched event scheduler, to no avail. I'm not sure if either Flask or sched are the right tools for the job, and I appreciate any guidance. Thanks!
My Code So Far:
from flask import Flask, render_template, request
import sched, time
app = Flask(__name__)
cameraScheduler = sched.scheduler(time.time, time.sleep)
def triggerCamera(sc):
print('Picture Taken')
cameraScheduler.enter(5,1,triggerCamera,(sc,))
#app.route('/', methods = ['POST','GET'])
def settings():
if request.method == 'POST':
if(request.form.getlist('timer') == ['true']):
cameraScheduler.enter(5,1,triggerCamera,(cameraScheduler,))
cameraScheduler.run
else:
cameraScheduler.cancel()
return render_template("settings.html")
if __name__ == '__main__':
app.run()
Try actually calling the scheduler cameraScheduler.run() (you are missing the parentheses there).
I have a flask app script that has multiple routes...
#app.py
def create_app(Tractor_id=0):
#app.route("/")
def index():
return render_template('index.html')
#app.route("/id")
def start():
return Tractor_id
#app.route("/stop")
def stop():
I'm trying to implement it multiple times with different parameters each time with the help of DispatcherMiddleware but I'm having trouble with it.
Here's the actual implementation:
# multiapp.py
from werkzeug.middleware.dispatcher import DispatcherMiddleware
from werkzeug.serving import run_simple
import start
T1 = start.create_app(Tractor_id='101')
T2 = start.create_app(Tractor_id='102')
# merge
application = DispatcherMiddleware(
None, {
'/{}'.format('T101'): T1,
'/{}'.format('T102'): T2
}
)
if __name__ == '__main__':
run_simple(
hostname='localhost',
port=5000,
application=application,
use_reloader=True,
use_debugger=True,
use_evalex=True)
In the index.html there are buttons that should redirect the user to the /id and /stop routes, but the do not work.
The general question would be, how to run multiple Flask applications which each have multiple routes within them?
I dont know DispatcherMiddleware.
But if you are trying to bind few flask servers, just pick for every process another port and it will work.
When you request them of course pay attention to port.
If you are struggling with actually making a multi route server, heres a good example.
for reasons I want to trigger the reboot of an raspberry pi using a REST api.
My REST api is coded in python flask like this:
from flask import Flask
from flask import jsonify
import subprocess
app = Flask(__name__)
#app.route('/api/reboot')
def reboot():
subprocess.call("/sbin/reboot")
return jsonify(triggered='reboot')
if __name__ == '__main__':
app.run(debug=True,host="0.0.0.0")
the code is working perfectly fine. But due to its a reboot the return will not be send (because the system is rebooting obviously).
Is there a way to trigger the reboot some kind of async with a delay of a couple milliseconds, that allows to return some value (in my case just an custom 'ack') prior the actual reboot?
Try threading.Timer:
For example:
from flask import Flask
from flask import jsonify
import subprocess
import threading
app = Flask(__name__)
def _reboot():
subprocess.call("/sbin/reboot")
#app.route('/api/reboot')
def reboot():
t = threading.Timer(1, _reboot)
t.start()
return jsonify(triggered='reboot')
if __name__ == '__main__':
app.run(debug=True,host="0.0.0.0")
I have created a flask application and am hosting it on a Ubuntu server. I know that my apache config is correct since I am able serve the example flask application. However, this one seems to be giving me trouble. The code is below:
from flask import Flask, render_template, request, url_for
import pickle
import engine
import config
# Initialize the Flask application
app = Flask(__name__)
model = pickle.load(open(config.MODEL_PATH, "rb"))
collection = engine.Collection(config.DATABASE_PATH)
search_engine = engine.SearchEngine(model, collection)
#app.route('/')
def form():
return render_template('index.html')
#app.route('/search/', methods=['POST'])
def search():
query = request.form['query']
results = search_engine.query(query)
return render_template('form_action.html', query=query, results=results)
#app.route('/retrieve/<int:item_number>', methods=['GET'])
def retrieve(item_number):
item = engine.Product(item_number, collection.open_document(str(item_number)))
return render_template('document.html', item=item)
if __name__ == '__main__':
app.run()
When running the file directly through the python interpreter, it works fine and I can access. However, when starting through apache and wsgi, I get no response from the server. It just hangs when making a request and nothing is available on the logs.
I suspect that my issue may have something to do with the three objects I initialize at the beginning of the program. Perhaps it gets stuck running those?
Update: I have tried commenting out certain parts of the code to see what is causing it to stall. Tracing it out to the engine module, importing NearestNeighbors seems to be causing the issue.
import sqlite3
import config
from sklearn.neighbors import NearestNeighbors
from preprocessor import preprocess_document
from collections import namedtuple