How do you run a python script using html button (flask) - python

I am trying to run a python script using html button in flask. I want it so that when the users press the button in html, the script which sends email in python will run.
This is the HTML portion. I want the python script to run when the user press the submit button.
<div class="container">
<h1 class="brand"><span>Haze</span> Alertion</h1>
<div class="wrapper">
<div class="company-info">
<h3>Haze Warning Signup</h3>
<ul>
<li><i class="fa fa-road"></i> Polytechnic</li>
<li><i class="fa fa-phone"></i> 1234-5678</li>
<li><i class="fa fa-envelope"></i> smartlifestyle#hotmail.com</li>
</ul>
</div>
<div class="contact">
<h3>Registration</h3>
<div class="alert">Your message has been sent</div>
<form id="contactForm">
<p>
<label>Name</label>
<input type="text" name="name" id="name" required>
</p>
<p>
<label>Location</label>
<input type="text" name="company" id="company">
</p>
<p>
<label>Email Address</label>
<input type="email" name="email" id="email" required>
</p>
<p>
<label>Repeat Email Address</label>
<input type="email" name="phone" id="phone">
</p>
<p class="full">
<label>Any Special Instructions</label>
<textarea name="message" rows="5" id="message"></textarea>
</p>
<p class="full">
<button type="submit">Submit</button>
</p>
</form>
</div>
</div>
And this is the python script.
import smtplib
import config
import data
from flask import Flask, render_template
app = Flask(__name__)
#app.route('/Email_Signup')
def Email_signup():
return render_template('Email_Signup(PSI).html')
def send_email(subject, msg):
try:
server = smtplib.SMTP('smtp.gmail.com:587')
server.ehlo()
server.starttls()
server.login(config.EMAIL_ADDRESS, config.PASSWORD)
message = 'Subject: {}\n\n{}'.format(subject, msg)
server.sendmail(config.EMAIL_ADDRESS, data.EMAIL_ADDRESS, message)
server.quit()
print("Success: Email sent!")
except:
print("Email failed to send.")
subject = "Haze Warning"
msg = "Brave yourselves, Haze is coming!"
send_email(subject, msg)

Please take a look at this docs
You can't just place button without any form.
Or you have to place simple link like:
Email Signup

You should access the route with javascript.
Checkout AJAX with jQuery:
http://flask.pocoo.org/docs/0.12/patterns/jquery/
Here's a very similar question:
How to make server side code run when a button is cliked?

Related

POST request to Flask Blueprint api not working

I am trying to execute a form POST request. The request is received at the route api function but the POST condition is not executing.
Code
<form class="pt-2 pb-4" action = "{{ url_for('data_sources_api.testfn') }}" method = "POST">
<div class="row">
<div class="col-md-4 mb-3">
<label for="url" class="form-label">URL</label>
<input type="text" class="form-control" id="url" name="url" aria-describedby="emailHeurllp"
placeholder="Enter new events top domain source url">
</div>
<div class="col-md-4 mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Organization Name">
</div>
<div class="col-md-12">
<button type="button" class="btn btn-secondary mr-2" value="submit" name = "submit">Submit</button>
</div>
</div>
</form>
Flask Code
#data_sources_api.route('/login/test', methods=["GET", "POST"])
def testfn():
# Check if user is loggedin
if loggedin():
# User is loggedin, render the home page
if request.method == 'POST':
print("POST Request Received")
result = request.form
return render_template('users/data-sources.html', role=session['role'])
return redirect(url_for('account_api.login'))
The request received is GET when i click the submit button and not POST :(
Thanks in advance
I think the problem is with button. Replace the button with input type="submit":
<input type="submit" value="Submit">
Here is the example of Django form.

Automation of login is not possible using Selenium (Python)

I am trying to get report from id-pwd required site. This site is showing 2 different login sites randomly (I do not know why, but I am guessing they do not like retrieving data by bot).
Login HTML 1:
<div class="login-modal-content">
<form accept-charset="UTF-8" action="/mp/login" class="signin-page-form" name="sign-in-form" method="post" novalidate="novalidate">
<div class="field email-field fade-label">
<label class="text" for="email">Email Address</label>
<input autocapitalize="off" autocomplete="off" autocorrect="off" autofocus="autofocus" class="text" id="email" name="email" size="30" spellcheck="false" type="email" value="">
</div>
<div class="message-box-error-wrapper">
<div class="message-box-error"></div>
</div>
<div class="field password-field fade-label">
<label class="text" for="password">Password</label>
<input class="text" id="password" name="password" size="30" autocomplete="off" type="password" value="">
<div class="login-forgot-password-wrapper">
Forgot Password
</div>
</div>
<div style="clear: both"></div>
<div id="captcha" class="g-recaptcha submit-button"></div>
<div class="submit-button full-length-submit-button">
<button id="sign-in-button" name="sign-in-button" type="submit" class="btn btn-blue track-event">
<span class="button-text">Sign In</span>
</button>
</div>
<div class="footer">
Don’t have a ---- account?
<span class="signup-today">
Sign up
</span>
</div>
</form>
</div>
Login HTML 2.
<main class="layout-base__body">
<h1 data-test-heading="">Sign in</h1>
<p data-test-subheading="">
New to Square? <market-link href="/signup?country_code=us&lang_code=en" hydrated="">Sign up</market-link>
</p>
<form data-test-form="" name="sign-in-form">
<market-field data-test-email-field="" hydrated="">
<market-input-text data-test-email-input="" name="email" input-id="email" autocomplete="username" type="email" value="" hydrated="" class="">
<label for="email">Email address</label>
</market-input-text>
<!---->
</market-field>
<market-field data-test-password-field="" hydrated="">
<market-input-password data-test-password-input="" name="password" type="password" hydrated="">
<label for="password">Password</label>
</market-input-password>
<!---->
</market-field>
<p>
<div>
<market-link data-test-forgot-password="" id="login-standard-forgot-password-link" href="#" hydrated="">
Forgot password?
</market-link>
</div>
</p>
<!---->
<div>
<market-button data-test-submit="" id="login-standard-submit" name="sign-in-button" rank="primary" role="button" type="button" variant="regular" size="medium" hydrated="">
Sign in
</market-button>
</div>
</form>
</main>
Here is my partial code for login.
def find_single_name(browser, timeout, el_name):
try:
WebDriverWait(browser, timeout).until(
EC.presence_of_element_located(
(By.NAME, el_name)
)
)
element = browser.find_element(By.NAME, el_name)
return element
except TimeoutException:
print(f"Could not find element ID of {el_name}")
return None
###########
login_id = find_single_name(browser=browser, timeout=60, el_name='email')
login_id.click()
login_id.clear()
login_id.send_keys(id)
time.sleep(1)
login_pwd = find_single_name(
browser=browser, timeout=60, el_name='password')
login_pwd.click()
login_pwd.clear()
login_pwd.send_keys(pwd)
time.sleep(1)
login_btn = find_single_name(
browser=browser, timeout=60, el_name='sign-in-button')
login_btn.click()
time.sleep(timeout)
When I happened to get login HTML 1 page, no problem to sign in and download all the reports I need, but same code is not working on login HTML 2. browser closed in no time on login 2 HTML.
I am struggling with this problem for weeks and gave up to solve this issue. Please advise me. I am praying not to deal with login 2 HTML whenever scraping that site...

Can I use mailto and send a form in flask app?

I've seen a few problems like this but they have a different answer than I was hoping so here I am.
I am planning to send mail details such that the client's mail app opens with the message sent via the form.
Thing is though, I've seen it being doable with PHP but I am running a Flask app.
So is there a way to do it using Python?
This is my form code:
<form id="contactForm" name="sentMessage" novalidate="novalidate" action="mailto:mail#gmail.com?subject=feedback&body=message">
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2"><label>Name</label><input class="form-control" type="text" id="name" required="" placeholder="Name"><small class="form-text text-danger help-block"></small></div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-0 pb-2"><label>Email Address</label><input class="form-control" type="email" id="email" required="" placeholder="Email Address"><small class="form-text text-danger help-block"></small></div>
</div>
<div class="control-group">
<div class="form-group floating-label-form-group controls mb-5 pb-2"><textarea class="form-control" id="message" required="" placeholder="Message" rows="5"></textarea><small class="form-text text-danger help-block"></small></div>
</div>
<div id="success"></div>
<div class="form-group"><button class="btn btn-primary btn-xl" id="sendMessageButton" type="submit">Send</button></div>
</form>
What I am looking to do is send a subject and content that is present in the textarea element as the body.
I managed to solve it myself with a workaround using redirect and request and it worked.
#app.route('/test',methods=['POST'])
def test():
mess=request.form['textarea']
return redirect('mailto:test#email.com?body='+str(mess))
In the form what I changed was
<form id="contactForm" name="sentMessage" novalidate="novalidate" action="{{url_for('test'}}" method="POST">

log in to a website using Python's Requests module doesn't work on this site but work on other site

use the following code on twitter and github it work fine but it doesn't work on the main site i am using it for, can someone please tell me what went wrong.
i did not get any error instead it scrap back the login page instead of log me.
import requests
session = requests.Session()
params = {'j_username': '**********', 'j_password': '************'}
r = requests.post("https://connect.data.com/loginProcess", params)
print("Cookie is set to:")
print(r.cookies.get_dict())
print("-----------")
print("Going to profile page...")
r = requests.get("https://connect.data.com/home")
print(r.text)
I am new to this so i can't figure out what went wrong, i have try many answer out before asking the question but none seem to workout for the site.
The login url is /login but the file that the login is been process is /loginProcess that is why i use /loginProcess but loginProcess does not print out my cookie but /login does print it out
The form to the site look like this:
<form id="command" name="LoginForm" action="https://connect.data.com/loginProcess" method="post">
<div>
<div class="login-container fields float-left">
<div class="content">
<div class="first">
<span class="title">Login</span>
</div>
<div class="middle">
<input id="j_username" name="j_username" type="email" class="text" placeholder="Email" maxlength="128" tabindex="1">
</div>
<div class="middle">
<input id="j_password" name="j_password" type="password" class="text" placeholder="Password" autocomplete="off" tabindex="2" maxlength="128">
</div>
<div class="middle">
<label for="_spring_security_remember_me" class="general-checkbox-label">
<input name="_spring_security_remember_me" tabindex="3" value="on" id="_spring_security_remember_me" class="checkbox margin-0px" type="checkbox">
<span>Keep me logged in </span>
</label>
</div>
<div class="last">
<button id="login_btn" type="submit" class="button-standard button-primary" tabindex="4">
<span class="button-standard-text">Login</span>
</button>
<a class="link" href="https://connect.data.com/forgotpassword" onclick="var x=".tl(";s_objectID="https://connect.data.com/forgotpassword_1";return this.s_oc?this.s_oc(e):true">Forgot Password?</a>
</div>
</div>
</div>
<div class="login-container marketing-message float-right">
<div class="content">
<h2>
Don't have an account?
Sign up now - it's FREE!
</h2>
<div class="float-left">
<img class="login-bicons" src="./Data.com Connect Business Contact Directory of Business Contacts and Company Information_files/clear.cache.gif">
</div>
<div class="float-left margin-left-20px">
<p>
<span id="pageTitle" style="color: #146791">Find</span>
business card information & B2B professionals.
</p>
<p>
<span id="pageTitle" style="color: #87c540">Research</span>
people & companies.
</p>
<p class="margin-top-5px">
<span id="pageTitle" style="color: #f37521">Get</span>
millions of contacts.
</p>
</div>
<div class="clear"></div>
</div>
</div>
<div class="clear nonlogged-container-foot">
<span class="new-to-ddc">New to Data.com?</span>
<a class="sign-up" href="https://connect.data.com/registration/signup" onclick="var x=".tl(";s_objectID="https://connect.data.com/registration/signup_1";return this.s_oc?this.s_oc(e):true">Sign up for an account...</a>
</div>
</div>
<input type="hidden" name="CSRF_TOKEN" id="CSRF_TOKEN" value="ce56932e08fc97bc29c5f6535b572664a66000513143584504b0ee7c66ef9659"></form>

How to write python script in flask

I have problem about my python script with HTML.
I'm newbie.
My python script looks as follow:
#!/usr/bin/python3.4
# Import modules for CGI handling
import cgi, cgitb
# Create instance of FieldStorage
form = cgi.FieldStorage()
# Get data from fields
first_name = form.getvalue('first_name')
last_name = form.getvalue('last_name')
print("Content-type:text/html\r\n\r\n")
print("<html>")
print("<head>")
print("<title>Hello - Second CGI Program</title>")
print("</head>")
print("<body>")
print("<h2>Hello %s %s</h2>" % (first_name, last_name))
print("</body>")
print("</html>")
and my HTML file:
<form action="hello_get.py" method="get">
First Name: <input type="text" name="first_name"> <br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
I run HTML and write to input first name and last name, but my script doesn't start. It's just show the windows If I want to open script, or save it.
EDIT:
My HTML:
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<p>Want to get in touch with me? Fill out the form below to send me a message and I will try to get back to you within 24 hours!</p>
<!-- Contact Form - Enter your email address on line 19 of the mail/contact_me.php file to make this form work. -->
<!-- WARNING: Some web hosts do not allow emails to be sent through forms to common mail hosts like Gmail or Yahoo. It's recommended that you use a private domain email address! -->
<!-- NOTE: To use the contact form, your site must be on a live web host with PHP! The form will not work locally! -->
<form action="/app/get.cgi" method="get">
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Name</label>
<input type="text" name="name" class="form-control" placeholder="Name" id="name" required data-validation-required-message="Please enter your name.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Email Address</label>
<input type="email" name="email" class="form-control" placeholder="Email Address" id="email" required data-validation-required-message="Please enter your email address.">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Message</label>
<textarea rows="5" name="message" class="form-control" placeholder="Message" id="message" required data-validation-required-message="Please enter a message."></textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div id="success"></div>
<div class="row">
<div class="form-group col-xs-12">
<button type="submit" class="btn btn-default">Odoslať</button>
</div>
</div>
</form>
</div>
</div>
</div>
(my python script) get.cgi:
#!/usr/bin/python3.4
# Import modules for CGI handling
import cgi, cgitb
file = open('file.txt', mode='w')
form = cgi.FieldStorage()
name = form.getvalue('name')
email = form.getvalue('email')
message = form.getvalue('message')
file.write(name)
file.write(email)
file.write(message)
file.close()
and my app.py which is main flask module
from flask import Flask, render_template, request
app = Flask(__name__)
app.secret_key = 'mypa$$w0rd'
#app.route('/')
#app.route('/index.html')
def index():
return render_template('index.html')
#app.route('/about.html')
def about():
return render_template('about.html')
#app.route('/contact.html')
def contact():
return render_template('contact.html')
#app.route('/post.html')
def sample_post():
return render_template('post.html')
if __name__ == '__main__':
app.run()
I'm running it as localhost.
Output when i click on SEND(in my html it equals ODOSLAT in my language):
Not Found
The requested URL was not found on the server. If you entered the URL
manually please check your spelling and try again.
And text field in browser search now looks like this:
http://127.0.0.1:5000/app/get.cgi?name=asdf&email=julo.marko%40gmail.com&message=asfasfasf
If you have a Flask web application, you don't need any .cgi scripts. Just point your form to the appropriate route in flask. With the url in your html:
#app.route('/api/get.cgi')
def api_get():
first_name = request.args.get('first_name')
last_name = request.args.get('last_name')
return """<html><body><h2>Hello %s %s</h2></body></html>""" % (first_name, last_name)

Categories