Flask – Discussion

Discuss Flask ”; Previous Next Flask is a web application framework written in Python. Armin Ronacher, who leads an international group of Python enthusiasts named Pocco, develops it. Flask is based on Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects. Print Page Previous Next Advertisements ”;

Flask – Deployment

Flask – Deployment ”; Previous Next Externally Visible Server A Flask application on the development server is accessible only on the computer on which the development environment is set up. This is a default behavior, because in debugging mode, a user can execute arbitrary code on the computer. If debug is disabled, the development server on local computer can be made available to the users on network by setting the host name as ‘0.0.0.0’. app.run(host = ’0.0.0.0’) Thereby, your operating system listens to all public IPs. Deployment To switch over from a development environment to a full-fledged production environment, an application needs to be deployed on a real web server. Depending upon what you have, there are different options available to deploy a Flask web application. For small application, you can consider deploying it on any of the following hosted platforms, all of which offer free plan for small application. Heroku dotcloud webfaction Flask application can be deployed on these cloud platforms. In addition, it is possible to deploy Flask app on Google cloud platform. Localtunnel service allows you to share your application on localhost without messing with DNS and firewall settings. If you are inclined to use a dedicated web server in place of above mentioned shared platforms, following options are there to explore. mod_wsgi mod_wsgi is an Apache module that provides a WSGI compliant interface for hosting Python based web applications on Apache server. Installing mod_wsgi To install an official release direct from PyPi, you can run − pip install mod_wsgi To verify that the installation was successful, run the mod_wsgi-express script with the start-server command − mod_wsgi-express start-server This will start up Apache/mod_wsgi on port 8000. You can then verify that the installation worked by pointing your browser at − http://localhost:8000/ Creating .wsgi file There should be a yourapplication.wsgi file. This file contains the code mod_wsgi, which executes on startup to get the application object. For most applications, the following file should be sufficient − from yourapplication import app as application Make sure that yourapplication and all the libraries that are in use are on the python load path. Configuring Apache You need to tell mod_wsgi, the location of your application. <VirtualHost *> ServerName example.com WSGIScriptAlias / C:yourdiryourapp.wsgi <Directory C:yourdir> Order deny,allow Allow from all </Directory> </VirtualHost> Standalone WSGI containers There are many popular servers written in Python that contains WSGI applications and serve HTTP. Gunicorn Tornado Gevent Twisted Web Print Page Previous Next Advertisements ”;

Flask – WTF

Flask – WTF ”; Previous Next One of the essential aspects of a web application is to present a user interface for the user. HTML provides a <form> tag, which is used to design an interface. A Form’s elements such as text input, radio, select etc. can be used appropriately. Data entered by a user is submitted in the form of Http request message to the server side script by either GET or POST method. The Server side script has to recreate the form elements from http request data. So in effect, form elements have to be defined twice – once in HTML and again in the server side script. Another disadvantage of using HTML form is that it is difficult (if not impossible) to render the form elements dynamically. HTML itself provides no way to validate a user’s input. This is where WTForms, a flexible form, rendering and validation library comes handy. Flask-WTF extension provides a simple interface with this WTForms library. Using Flask-WTF, we can define the form fields in our Python script and render them using an HTML template. It is also possible to apply validation to the WTF field. Let us see how this dynamic generation of HTML works. First, Flask-WTF extension needs to be installed. pip install flask-WTF The installed package contains a Form class, which has to be used as a parent for user- defined form. WTforms package contains definitions of various form fields. Some Standard form fields are listed below. Sr.No Standard Form Fields & Description 1 TextField Represents <input type = ”text”> HTML form element 2 BooleanField Represents <input type = ”checkbox”> HTML form element 3 DecimalField Textfield for displaying number with decimals 4 IntegerField TextField for displaying integer 5 RadioField Represents <input type = ”radio”> HTML form element 6 SelectField Represents select form element 7 TextAreaField Represents <testarea> html form element 8 PasswordField Represents <input type = ”password”> HTML form element 9 SubmitField Represents <input type = ”submit”> form element For example, a form containing a text field can be designed as below − from flask_wtf import Form from wtforms import TextField class ContactForm(Form): name = TextField(“Name Of Student”) In addition to the ‘name’ field, a hidden field for CSRF token is created automatically. This is to prevent Cross Site Request Forgery attack. When rendered, this will result into an equivalent HTML script as shown below. <input id = “csrf_token” name = “csrf_token” type = “hidden” /> <label for = “name”>Name Of Student</label><br> <input id = “name” name = “name” type = “text” value = “” /> A user-defined form class is used in a Flask application and the form is rendered using a template. from flask import Flask, render_template from forms import ContactForm app = Flask(__name__) app.secret_key = ”development key” @app.route(”/contact”) def contact(): form = ContactForm() return render_template(”contact.html”, form = form) if __name__ == ”__main__”: app.run(debug = True) WTForms package also contains validator class. It is useful in applying validation to form fields. Following list shows commonly used validators. Sr.No Validators Class & Description 1 DataRequired Checks whether input field is empty 2 Email Checks whether text in the field follows email ID conventions 3 IPAddress Validates IP address in input field 4 Length Verifies if length of string in input field is in given range 5 NumberRange Validates a number in input field within given range 6 URL Validates URL entered in input field We shall now apply ‘DataRequired’ validation rule for the name field in contact form. name = TextField(“Name Of Student”,[validators.Required(“Please enter your name.”)]) The validate() function of form object validates the form data and throws the validation errors if validation fails. The Error messages are sent to the template. In the HTML template, error messages are rendered dynamically. {% for message in form.name.errors %} {{ message }} {% endfor %} The following example demonstrates the concepts given above. The design of Contact form is given below (forms.py). from flask_wtf import Form from wtforms import TextField, IntegerField, TextAreaField, SubmitField, RadioField, SelectField from wtforms import validators, ValidationError class ContactForm(Form): name = TextField(“Name Of Student”,[validators.Required(“Please enter your name.”)]) Gender = RadioField(”Gender”, choices = [(”M”,”Male”),(”F”,”Female”)]) Address = TextAreaField(“Address”) email = TextField(“Email”,[validators.Required(“Please enter your email address.”), validators.Email(“Please enter your email address.”)]) Age = IntegerField(“age”) language = SelectField(”Languages”, choices = [(”cpp”, ”C&plus;&plus;”), (”py”, ”Python”)]) submit = SubmitField(“Send”) Validators are applied to the Name and Email fields. Given below is the Flask application script (formexample.py). from flask import Flask, render_template, request, flash from forms import ContactForm app = Flask(__name__) app.secret_key = ”development key” @app.route(”/contact”, methods = [”GET”, ”POST”]) def contact(): form = ContactForm() if request.method == ”POST”: if form.validate() == False: flash(”All fields are required.”) return render_template(”contact.html”, form = form) else: return render_template(”success.html”) elif request.method == ”GET”: return render_template(”contact.html”, form = form) if __name__ == ”__main__”: app.run(debug = True) The Script of the template (contact.html) is as follows − <!doctype html> <html> <body> <h2 style = “text-align: center;”>Contact Form</h2> {% for message in form.name.errors %} <div>{{ message }}</div> {% endfor %} {% for message in form.email.errors %} <div>{{ message }}</div> {% endfor %} <form action = “http://localhost:5000/contact” method = post> <fieldset> <legend>Contact Form</legend> {{ form.hidden_tag() }} <div style = font-size:20px; font-weight:bold; margin-left:150px;> {{ form.name.label }}<br> {{ form.name }} <br> {{ form.Gender.label }} {{ form.Gender }} {{ form.Address.label }}<br> {{ form.Address }} <br> {{ form.email.label }}<br> {{ form.email }} <br> {{ form.Age.label }}<br> {{ form.Age }} <br> {{ form.language.label }}<br> {{ form.language }} <br> {{ form.submit }} </div> </fieldset> </form> </body> </html> Run formexample.py in Python shell and visit URL http://localhost:5000/contact. The Contact form will be displayed as shown below. If there are any errors, the page will look like this − If there are no errors, ‘success.html’ will be rendered. Print Page Previous Next Advertisements ”;

Flask – Redirect & Errors

Flask – Redirect & Errors ”; Previous Next Flask class has a redirect() function. When called, it returns a response object and redirects the user to another target location with specified status code. Prototype of redirect() function is as below − Flask.redirect(location, statuscode, response) In the above function − location parameter is the URL where response should be redirected. statuscode sent to browser’s header, defaults to 302. response parameter is used to instantiate response. The following status codes are standardized − HTTP_300_MULTIPLE_CHOICES HTTP_301_MOVED_PERMANENTLY HTTP_302_FOUND HTTP_303_SEE_OTHER HTTP_304_NOT_MODIFIED HTTP_305_USE_PROXY HTTP_306_RESERVED HTTP_307_TEMPORARY_REDIRECT The default status code is 302, which is for ‘found’. In the following example, the redirect() function is used to display the login page again when a login attempt fails. from flask import Flask, redirect, url_for, render_template, request # Initialize the Flask application app = Flask(__name__) @app.route(”/”) def index(): return render_template(”log_in.html”) @app.route(”/login”,methods = [”POST”, ”GET”]) def login(): if request.method == ”POST” and request.form[”username”] == ”admin” : return redirect(url_for(”success”)) else: return redirect(url_for(”index”)) @app.route(”/success”) def success(): return ”logged in successfully” if __name__ == ”__main__”: app.run(debug = True) Flask class has abort() function with an error code. Flask.abort(code) The Code parameter takes one of following values − 400 − for Bad Request 401 − for Unauthenticated 403 − for Forbidden 404 − for Not Found 406 − for Not Acceptable 415 − for Unsupported Media Type 429 − Too Many Requests Let us make a slight change in the login() function in the above code. Instead of re-displaying the login page, if ‘Unauthourized’ page is to be displayed, replace it with call to abort(401). from flask import Flask, redirect, url_for, render_template, request, abort app = Flask(__name__) @app.route(”/”) def index(): return render_template(”log_in.html”) @app.route(”/login”,methods = [”POST”, ”GET”]) def login(): if request.method == ”POST”: if request.form[”username”] == ”admin” : return redirect(url_for(”success”)) else: abort(401) else: return redirect(url_for(”index”)) @app.route(”/success”) def success(): return ”logged in successfully” if __name__ == ”__main__”: app.run(debug = True) Print Page Previous Next Advertisements ”;

Sending Form Data to Template

Flask – Sending Form Data to Template ”; Previous Next We have already seen that the http method can be specified in URL rule. The Form data received by the triggered function can collect it in the form of a dictionary object and forward it to a template to render it on a corresponding web page. In the following example, ‘/’ URL renders a web page (student.html) which has a form. The data filled in it is posted to the ‘/result’ URL which triggers the result() function. The results() function collects form data present in request.form in a dictionary object and sends it for rendering to result.html. The template dynamically renders an HTML table of form data. Given below is the Python code of application − from flask import Flask, render_template, request app = Flask(__name__) @app.route(”/”) def student(): return render_template(”student.html”) @app.route(”/result”,methods = [”POST”, ”GET”]) def result(): if request.method == ”POST”: result = request.form return render_template(“result.html”,result = result) if __name__ == ”__main__”: app.run(debug = True) Given below is the HTML script of student.html. <html> <body> <form action = “http://localhost:5000/result” method = “POST”> <p>Name <input type = “text” name = “Name” /></p> <p>Physics <input type = “text” name = “Physics” /></p> <p>Chemistry <input type = “text” name = “chemistry” /></p> <p>Maths <input type =”text” name = “Mathematics” /></p> <p><input type = “submit” value = “submit” /></p> </form> </body> </html> Code of template (result.html) is given below − <!doctype html> <html> <body> <table border = 1> {% for key, value in result.items() %} <tr> <th> {{ key }} </th> <td> {{ value }} </td> </tr> {% endfor %} </table> </body> </html> Run the Python script and enter the URL http://localhost:5000/ in the browser. When the Submit button is clicked, form data is rendered on result.html in the form of HTML table. Print Page Previous Next Advertisements ”;

Flask – Templates

Flask – Templates ”; Previous Next It is possible to return the output of a function bound to a certain URL in the form of HTML. For instance, in the following script, hello() function will render ‘Hello World’ with <h1> tag attached to it. from flask import Flask app = Flask(__name__) @app.route(”/”) def index(): return ”<html><body><h1>Hello World</h1></body></html>” if __name__ == ”__main__”: app.run(debug = True) However, generating HTML content from Python code is cumbersome, especially when variable data and Python language elements like conditionals or loops need to be put. This would require frequent escaping from HTML. This is where one can take advantage of Jinja2 template engine, on which Flask is based. Instead of returning hardcode HTML from the function, a HTML file can be rendered by the render_template() function. from flask import Flask app = Flask(__name__) @app.route(”/”) def index(): return render_template(‘hello.html’) if __name__ == ”__main__”: app.run(debug = True) Flask will try to find the HTML file in the templates folder, in the same folder in which this script is present. Application folder Hello.py templates hello.html The term ‘web templating system’ refers to designing an HTML script in which the variable data can be inserted dynamically. A web template system comprises of a template engine, some kind of data source and a template processor. Flask uses jinja2 template engine. A web template contains HTML syntax interspersed placeholders for variables and expressions (in these case Python expressions) which are replaced values when the template is rendered. The following code is saved as hello.html in the templates folder. <!doctype html> <html> <body> <h1>Hello {{ name }}!</h1> </body> </html> Next, run the following script from Python shell. from flask import Flask, render_template app = Flask(__name__) @app.route(”/hello/<user>”) def hello_name(user): return render_template(”hello.html”, name = user) if __name__ == ”__main__”: app.run(debug = True) As the development server starts running, open the browser and enter URL as − http://localhost:5000/hello/mvl The variable part of URL is inserted at {{ name }} place holder. The jinja2 template engine uses the following delimiters for escaping from HTML. {% … %} for Statements {{ … }} for Expressions to print to the template output {# … #} for Comments not included in the template output # … ## for Line Statements In the following example, use of conditional statement in the template is demonstrated. The URL rule to the hello() function accepts the integer parameter. It is passed to the hello.html template. Inside it, the value of number received (marks) is compared (greater or less than 50) and accordingly HTML is conditionally rendered. The Python Script is as follows − from flask import Flask, render_template app = Flask(__name__) @app.route(”/hello/<int:score>”) def hello_name(score): return render_template(”hello.html”, marks = score) if __name__ == ”__main__”: app.run(debug = True) HTML template script of hello.html is as follows − <!doctype html> <html> <body> {% if marks>50 %} <h1> Your result is pass!</h1> {% else %} <h1>Your result is fail</h1> {% endif %} </body> </html> Note that the conditional statements if-else and endif are enclosed in delimiter {%..%}. Run the Python script and visit URL http://localhost/hello/60 and then http://localhost/hello/30 to see the output of HTML changing conditionally. The Python loop constructs can also be employed inside the template. In the following script, the result() function sends a dictionary object to template results.html when URL http://localhost:5000/result is opened in the browser. The Template part of result.html employs a for loop to render key and value pairs of dictionary object result{} as cells of an HTML table. Run the following code from Python shell. from flask import Flask, render_template app = Flask(__name__) @app.route(”/result”) def result(): dict = {”phy”:50,”che”:60,”maths”:70} return render_template(”result.html”, result = dict) if __name__ == ”__main__”: app.run(debug = True) Save the following HTML script as result.html in the templates folder. <!doctype html> <html> <body> <table border = 1> {% for key, value in result.items() %} <tr> <th> {{ key }} </th> <td> {{ value }} </td> </tr> {% endfor %} </table> </body> </html> Here, again the Python statements corresponding to the For loop are enclosed in {%..%} whereas, the expressions key and value are put inside {{ }}. After the development starts running, open http://localhost:5000/result in the browser to get the following output. Print Page Previous Next Advertisements ”;

Flask – Request Object

Flask – Request Object ”; Previous Next The data from a client’s web page is sent to the server as a global request object. In order to process the request data, it should be imported from the Flask module. Important attributes of request object are listed below − Form − It is a dictionary object containing key and value pairs of form parameters and their values. args − parsed contents of query string which is part of URL after question mark (?). Cookies − dictionary object holding Cookie names and values. files − data pertaining to uploaded file. method − current request method. Print Page Previous Next Advertisements ”;

Flask – Overview

Flask – Overview ”; Previous Next What is Web Framework? Web Application Framework or simply Web Framework represents a collection of libraries and modules that enables a web application developer to write applications without having to bother about low-level details such as protocols, thread management etc. What is Flask? Flask is a web application framework written in Python. It is developed by Armin Ronacher, who leads an international group of Python enthusiasts named Pocco. Flask is based on the Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects. WSGI Web Server Gateway Interface (WSGI) has been adopted as a standard for Python web application development. WSGI is a specification for a universal interface between the web server and the web applications. Werkzeug It is a WSGI toolkit, which implements requests, response objects, and other utility functions. This enables building a web framework on top of it. The Flask framework uses Werkzeug as one of its bases. Jinja2 Jinja2 is a popular templating engine for Python. A web templating system combines a template with a certain data source to render dynamic web pages. Flask is often referred to as a micro framework. It aims to keep the core of an application simple yet extensible. Flask does not have built-in abstraction layer for database handling, nor does it have form a validation support. Instead, Flask supports the extensions to add such functionality to the application. Some of the popular Flask extensions are discussed later in the tutorial. Print Page Previous Next Advertisements ”;

Flask – SQLite

Flask – SQLite ”; Previous Next Python has an in-built support for SQlite. SQlite3 module is shipped with Python distribution. For a detailed tutorial on using SQLite database in Python, please refer to this link. In this section we shall see how a Flask application interacts with SQLite. Create an SQLite database ‘database.db’ and create a students’ table in it. import sqlite3 conn = sqlite3.connect(”database.db”) print “Opened database successfully”; conn.execute(”CREATE TABLE students (name TEXT, addr TEXT, city TEXT, pin TEXT)”) print “Table created successfully”; conn.close() Our Flask application has three View functions. First new_student() function is bound to the URL rule (‘/addnew’). It renders an HTML file containing student information form. @app.route(”/enternew”) def new_student(): return render_template(”student.html”) The HTML script for ‘student.html’ is as follows − <html> <body> <form action = “{{ url_for(”addrec”) }}” method = “POST”> <h3>Student Information</h3> Name<br> <input type = “text” name = “nm” /></br> Address<br> <textarea name = “add” ></textarea><br> City<br> <input type = “text” name = “city” /><br> PINCODE<br> <input type = “text” name = “pin” /><br> <input type = “submit” value = “submit” /><br> </form> </body> </html> As it can be seen, form data is posted to the ‘/addrec’ URL which binds the addrec() function. This addrec() function retrieves the form’s data by POST method and inserts in students table. Message corresponding to success or error in insert operation is rendered to ‘result.html’. @app.route(”/addrec”,methods = [”POST”, ”GET”]) def addrec(): if request.method == ”POST”: try: nm = request.form[”nm”] addr = request.form[”add”] city = request.form[”city”] pin = request.form[”pin”] with sql.connect(“database.db”) as con: cur = con.cursor() cur.execute(“INSERT INTO students (name,addr,city,pin) VALUES (?,?,?,?)”,(nm,addr,city,pin) ) con.commit() msg = “Record successfully added” except: con.rollback() msg = “error in insert operation” finally: return render_template(“result.html”,msg = msg) con.close() The HTML script of result.html contains an escaping statement {{msg}} that displays the result of Insert operation. <!doctype html> <html> <body> result of addition : {{ msg }} <h2><a href = “”>go back to home page</a></h2> </body> </html> The application contains another list() function represented by ‘/list’ URL. It populates ‘rows’ as a MultiDict object containing all records in the students table. This object is passed to the list.html template. @app.route(”/list”) def list(): con = sql.connect(“database.db”) con.row_factory = sql.Row cur = con.cursor() cur.execute(“select * from students”) rows = cur.fetchall(); return render_template(“list.html”,rows = rows) This list.html is a template, which iterates over the row set and renders the data in an HTML table. <!doctype html> <html> <body> <table border = 1> <thead> <td>Name</td> <td>Address>/td< <td>city</td> <td>Pincode</td> </thead> {% for row in rows %} <tr> <td>{{row[“name”]}}</td> <td>{{row[“addr”]}}</td> <td> {{ row[“city”]}}</td> <td>{{row[”pin”]}}</td> </tr> {% endfor %} </table> <a href = “/”>Go back to home page</a> </body> </html> Finally, the ‘/’ URL rule renders a ‘home.html’ which acts as the entry point of the application. @app.route(”/”) def home(): return render_template(”home.html”) Here is the complete code of Flask-SQLite application. from flask import Flask, render_template, request import sqlite3 as sql app = Flask(__name__) @app.route(”/”) def home(): return render_template(”home.html”) @app.route(”/enternew”) def new_student(): return render_template(”student.html”) @app.route(”/addrec”,methods = [”POST”, ”GET”]) def addrec(): if request.method == ”POST”: try: nm = request.form[”nm”] addr = request.form[”add”] city = request.form[”city”] pin = request.form[”pin”] with sql.connect(“database.db”) as con: cur = con.cursor() cur.execute(“INSERT INTO students (name,addr,city,pin) VALUES (?,?,?,?)”,(nm,addr,city,pin) ) con.commit() msg = “Record successfully added” except: con.rollback() msg = “error in insert operation” finally: return render_template(“result.html”,msg = msg) con.close() @app.route(”/list”) def list(): con = sql.connect(“database.db”) con.row_factory = sql.Row cur = con.cursor() cur.execute(“select * from students”) rows = cur.fetchall(); return render_template(“list.html”,rows = rows) if __name__ == ”__main__”: app.run(debug = True) Run this script from Python shell and as the development server starts running. Visit http://localhost:5000/ in browser which displays a simple menu like this − Click ‘Add New Record’ link to open the Student Information Form. Fill the form fields and submit it. The underlying function inserts the record in the students table. Go back to the home page and click ‘Show List’ link. The table showing the sample data will be displayed. Print Page Previous Next Advertisements ”;

Flask – Mail

Flask – Mail ”; Previous Next A web based application is often required to have a feature of sending mail to the users/clients. Flask-Mail extension makes it very easy to set up a simple interface with any email server. At first, Flask-Mail extension should be installed with the help of pip utility. pip install Flask-Mail Then Flask-Mail needs to be configured by setting values of the following application parameters. Sr.No Parameters & Description 1 MAIL_SERVER Name/IP address of email server 2 MAIL_PORT Port number of server used 3 MAIL_USE_TLS Enable/disable Transport Security Layer encryption 4 MAIL_USE_SSL Enable/disable Secure Sockets Layer encryption 5 MAIL_DEBUG Debug support. Default is Flask application’s debug status 6 MAIL_USERNAME User name of sender 7 MAIL_PASSWORD password of sender 8 MAIL_DEFAULT_SENDER sets default sender 9 MAIL_MAX_EMAILS Sets maximum mails to be sent 10 MAIL_SUPPRESS_SEND Sending suppressed if app.testing set to true 11 MAIL_ASCII_ATTACHMENTS If set to true, attached filenames converted to ASCII The flask-mail module contains definitions of the following important classes. Mail class It manages email-messaging requirements. The class constructor takes the following form − flask-mail.Mail(app = None) The Constructor takes the Flask application object as a parameter. Methods of Mail class Sr.No Methods & Description 1 send() Sends contents of Message class object 2 connect() Opens connection with mail host 3 send_message() Sends message object Message class It encapsulates an email message. Message class constructor has several parameters − flask-mail.Message(subject, recipients, body, html, sender, cc, bcc, reply-to, date, charset, extra_headers, mail_options, rcpt_options) Message class methods attach() − adds an attachment to message. This method takes the following parameters − filename − name of file to attach content_type − MIME type of file data − raw file data disposition − content disposition, if any. add_recipient() − adds another recipient to message In the following example, SMTP server of Google’s gmail service is used as MAIL_SERVER for Flask-Mail configuration. Step 1 − Import Mail and Message class from flask-mail module in the code. from flask_mail import Mail, Message Step 2 − Then Flask-Mail is configured as per following settings. app.config[”MAIL_SERVER”]=”smtp.gmail.com” app.config[”MAIL_PORT”] = 465 app.config[”MAIL_USERNAME”] = ”[email protected]” app.config[”MAIL_PASSWORD”] = ”*****” app.config[”MAIL_USE_TLS”] = False app.config[”MAIL_USE_SSL”] = True Step 3 − Create an instance of Mail class. mail = Mail(app) Step 4 − Set up a Message object in a Python function mapped by URL rule (‘/’). @app.route(“/”) def index(): msg = Message(”Hello”, sender = ”[email protected]”, recipients = [”[email protected]”]) msg.body = “This is the email body” mail.send(msg) return “Sent” Step 5 − The entire code is given below. Run the following script in Python Shell and visit http://localhost:5000/. from flask import Flask from flask_mail import Mail, Message app =Flask(__name__) mail=Mail(app) app.config[”MAIL_SERVER”]=”smtp.gmail.com” app.config[”MAIL_PORT”] = 465 app.config[”MAIL_USERNAME”] = ”[email protected]” app.config[”MAIL_PASSWORD”] = ”*****” app.config[”MAIL_USE_TLS”] = False app.config[”MAIL_USE_SSL”] = True mail = Mail(app) @app.route(“/”) def index(): msg = Message(”Hello”, sender = ”[email protected]”, recipients = [”[email protected]”]) msg.body = “Hello Flask message sent from Flask-Mail” mail.send(msg) return “Sent” if __name__ == ”__main__”: app.run(debug = True) Note that the built-insecurity features in Gmail service may block this login attempt. You may have to decrease the security level. Please log in to your Gmail account and visit this link to decrease the security. Print Page Previous Next Advertisements ”;