I have a streaming server for my Raspberry Pi. I want to be able to control it with servos (pan and tilt) from the website. Therefore I want to start a python script, that starts when a botton is pressed at the website, without refreshing the page. Is there a way to do that? I'm using flask.
You would want to setup an endpoint in your flask app like:
from flask import Flask
app = Flask(__name__)
#app.route("/")
def indexpage():
# Serve your index web page here
return app.send_static_file('index.html')
#app.route("/runscript")
def runscript():
# Do whatever you want here
run_my_script()
app.run()
Then in your webpage have a form which sends a GET request to your app at the runscript endpoint.
<form action="/runscript" method="get">
<input type="submit" value="Submit">
</form>
Related
I am trying to run my appium scripts on button click in a html template, but unfortunately I have searched everywhere but still I found no solution.
My html template is inside a templates folder in the flask project directory and I am taking path as an input and want to pass that string to my Appium script and as soon as I click on the Submit button on my template it should launch the test script on my locally connected phone taking the path as a parameter.
Any kind of help will be appreciated.
Regards
I tried adding functions of my test script in the flask route but I have multiple functions in my python script and for every function I would have to create multiple routes. I was expecting to run the python script all at once on the default flask route ('/').
Following is my code for flask_server.py file as per now I am just getting the parameter in it and showing it in the next route but instead I want to pass my appium script here and run it on device on submit.
from flask import Flask
from flask import render_template
from flask import request
from Instagram.instagram_android_automation import
InstagramAndroidAutomation
from flask import Flask, redirect, url_for, request
app = Flask(__name__)
#app.route('/dashboard/<name>')
def dashboard(name):
return 'welcome %s' % name
#app.route('/login',methods = ['POST', 'GET'])
def login():
if request.method == 'POST':
user = request.form['name']
return redirect(url_for('dashboard',name = user))
else:
user = request.args.get('name')
return render_template('login.html')
if __name__ == '__main__':
app.run(debug = True)
This question already has answers here:
Get the data received in a Flask request
(23 answers)
Closed 2 years ago.
I created an app that moves the largest files from the chosen folder to a new folder for inspection. I tried to create an interface for it using django and when I asked my friend, who is fluent in python about the architecture, he said I don't really need a database, so I should rather try flask.
In a flask tutorial, I found the guy is actually using SQLAlchemy and is creating a database. How can I pass HTML input to my python omitting database?
The pure python app I have already created works just fine without any database.
HTML input section:
{% block body %}
<h1>Your computer can run faster today</h1>
<p>You just need to remove the largest files from some of your folders. It's easy with this small project. Enjoy :)</p>
<form>
<label for="fname">Path to the folder you want to remove largest files from:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Path to the folder you want to put your removed files for inspection</label><br>
<input type="text" id="lname" name="lname">
</form>
{% endblock %}
Python input section:
print("Type a path to the folder you want to remove the largest files from")
path1 = os.path.abspath(input())
print("Type a path to create a folder for the largest files to inspect them before removing")
path2 = os.path.abspath(input())
path3 = path2 + '/ToBeRemoved'
The most basic Flask app to achieve this will look something like this.
from flask import Flask, request, render_template
app = Flask(__name__)
#app.route('/')
def remove_large_files():
if request.method == 'POST':
path_from = request.form.get('fname')
path_to = request.form.get('lname')
if path_from and path_to:
# process your files
# return a response
return render_template('template.html')
Replace template.html by the template that contains your form.
Refer to the Request object docs for more info.
I have a HTML page where there is one hyperlink. This html email will be sent to users via outlook (I have written the mail function using flask python) and when users will click on hyperlink on the email body, it will eventually open another page. This page will be same but, the content of the page will be different for different users based on the users' email id.
Right now, my requirement is to pass the user email ID through hyperlink so, I can display different content based on email ID. Can it be done through hyperlink? As, you know that outlook uses Microsoft Word as rendering engine so, will it be difficult to pass parameter through hyperlink ?
Or, can I pass the email ID through my flask function while sending the mails?
My flask function which will send mail to outlook is below
from flask import Flask, render_template
from flask_mail import Mail, Message
app = Flask(__name__)
app.config.update(
DEBUG=True,
MAIL_SERVER='My Company SMTP MAIL SERVER',
MAIL_PORT=My Company SMTP PORT NUMBER,
# MAIL_USE_SSL=True,
MAIL_USERNAME='XXXXX.YYYY#mycompanyname.com',
)
mail = Mail(app)
#app.route('/')
def mailSend():
try:
recipeint_emails = fetch_recipient_emails
msg = Message("Send Mail Tutorial!",
sender="XXXXX.YYYY#mycompanyname.com",
recipients=recipeint_emails)
msg.html = render_template('linkPage.html')
mail.send(msg)
return 'Mail sent!'
except Exception as e:
print(type(e))
print(e)
return 'error'
The linkPage.html will contain the hyperlink which is mentioned below
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hyperlinkdemo</title>
</head>
<body>
Visit Dynamic Page
</body>
</html>
Any suggestion will be very helpful.
Flask has already a builtin function url_for to generate properly a link with extra parameters. Refer to this doc
UPDATE
it's recommended to choose the accurate name for routes
it's recommended to use snake_case when naming views
i recommend you to refer to the official Flask-Mail doc section Bulk Mail
#app.route('/bulk-email')
def bulk_mail():
[..]
# Get all users first
with mail.connect() as conn:
for user in users:
msg = Message(subject="Tutorial",
sender="XXXXX.YYYY#mycompanyname.com",
recipients=[user.email])
# pass dynamically the user to the template
msg.html = render_template('linkPpage.html', user=user)
conn.send(msg)
in linkPage.html template you can do
<p>Dear {{ user.username }},</p>
<p>
Open Link tutorial
</p> //added double quotation
you have to implement the logic of link_tutorial function, when user click on the link it will be redirected to your app to show him a customized page / tutorial:
#app.route('/link-tutorial/<int:user_id>')
def link_tutorial(user_id):
# fetch the user with the given user_id and render the right template for him.
[..]
return render_template('tutorial.html')
finally, i would recommend you using celery an asynchronous task queue to handle the bulk email more efficiently than Flask-Mail, because sending mail is a blocking task and your app will be very slow and not responsive.
I have been trying to run a python script (rainbow.py) through a HTML button. I have no idea how to do this and all the answers I have found make no sense to me. All I want is a simple explanation of how to run a python script through regular HTML script.
I am trying to do this on a Raspberry Pi.
You can make it through Flask, a Python Web Microframework:
HTML (index.html):
Your button
Python (app.py):
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/')
def index():
# render your html template
return render_template('index.html')
#app.route('/something')
def do_something():
# when the button was clicked,
# the code below will be execute.
print 'do something here'
...
if __name__ == '__main__':
app.run()
Start the server:$ python app.py
Then go to http://127.0.0.1:5000.
File structure:
template\
-index.html
app.py
Is there any way to modify the home button url link on the flask-admin admin top panel so that I redirect back to a main site?
I can add a link in a custom.html page eg:
{% extends 'admin/master.html' %}
{% block body %}
Home
{% endblock %}
But this is hidden away inside the custom page. I'd prefer a top-bar link out of admin.
Easiest way is to add a menu link and leave the admin home page alone (you might want to add a dashboard or suchlike in the future):
from flask_admin.menu import MenuLink
# Create admin
admin = Admin(app, name='Admin', url='/')
admin.add_view(ImageView(model=Image, session=db.session, category='Database', name='Images'))
# Add custom link to public website home page
admin.add_link(MenuLink(name='Public Website', category='', url=url_for('main.home')))
Note, url_for needs to be called within a Flask application context. For example, if using the Flask application factory pattern, this would look something like the following:
def create_app(config):
app = App('app')
# setup config
# setup blueprints
# setup Flask-Admin
from app.admin import create_admin
from app.admin.configure import configure_admin
with app.app_context():
admin = create_admin(app=app)
configure_admin(app, admin)
# more stuff
return app
__init__.py in app.admin module
def create_admin(app=None):
return Admin(app, template_mode='bootstrap3')
configure.py in app.admin module
def configure_admin(app, admin):
# setup views
# add link to home page
admin.add_link(MenuLink(name='Public Website', category='', url=url_for('home.HomeView:index')))
You can override get_url method of MenuLink. That way you get around application context problem.
from flask import url_for
from flask_admin import Admin
from flask_admin.menu import MenuLink
class MainIndexLink(MenuLink):
def get_url(self):
return url_for("main.index")
admin = Admin(name="Admin")
admin.add_link(MainIndexLink(name="Main Page"))
def create_app():
app = Flask(__name__)
from app.admin import admin
admin.init_app(app)
return app
If you are having issues with app context error when using app.app_context():
RuntimeError: Unable to build URLs outside an active request without 'SERVER_NAME' configured. Also configure 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as needed.
You can simply 'test_request_context()' method.
with app.test_request_context():
admin.add_link(MenuLink(name='Name', category='', url=url_for('home.home_route')))
This is documented here