Flask web framework tutorial : In flask web development tutorial we will explain the web framework and web development. The Python web framework and a third-party Python library are used for developing web applications.
They will provide basic and advanced concepts of the Python Flask framework.
Flask is a web framework that provides libraries to build lightweight web applications in python also developed by Armin Ronacher who leads an international group of Python enthusiasts. The flask is an API of Python which allows building up web-applications. The framework is explicit than Django’s framework and easy to learn because it has less base code to implement a simple web-Application. The flask is based on WSGI toolkit and Jinja2 template engine. It is web application written in the python language and based on werkzeug and jinja template.
Here the websites are built using the Flask micro framework.
The scalability effort takes to back site from the later point in time.
The flask will allow building like lego blocks and mixing then installing modules.
The flask website will become easier to structure and start a simple app.
It utilizes routing with tempting an engine and build local server for design/development.
The site created by Armin ronacher as it is great source to start the flask for web development and help using web development.
Exploreflask.com:-
It will give an introduction to common coding and some design tips.
Also as acronym for web server gateway interface, this is a standard for Python web application development.
They are considered as the specification for the universal interface, between the web server and web application.
Jinja2 is a web template engine that combines a template with the data source to render the dynamic web pages.
For the installation of flask, we need to have python 2.7 installed on our system.
We suggest python 3 for the development in the flask.
It is virtualenv as the virtual python environment builder used to create the multiple python virtual environment side by side.
Installed by using the following command.
$ pip install virtualenv
After installation, we can create new a virtual environment into a folder as given below.
$ virtualenv venv
$ Mkdir new
$ cd new
We use the following command on the Linux operating system.
$ Venv/bin/activate
Use the following command.
$ venv\scripts\activate
Install the flask by using the following command.
$ pip install flask
We can install the flask using the command without creating the virtual environment.
To test the flask installation we have to open python on the command line and type python.
Then try to import the package flask.
Flask web framework tutorial
After installation, of the flask we do not get the error in the process.
This means flask will provide you with tools, libraries, and technologies that allow you to build a web application.
The web application can be some web pages a blog as a web-based calendar application or a commercial website.
Flask is part of the micro-framework this framework and does not depend on external libraries.
The Pros would be the framework is light and there is little dependency to update and watch for security bugs.
From flask import flask
App=flask (_name_)
a@app.route(‘/’)
def hello_world ():
return ‘Hello World’
if_name_==’_main_’:
app.run ()
Here we save the file and run the script after output.
We go to url and see the webpage displaying helloworld.
The route () in the flask is used to bind URL to the function and extend the functionality of the web application.
Then add_url_rule () function is available to bind URL with function.
Def gfg ():
Return’geeksforgeeks’
App.add_url_rule (‘/’,’g2g’, gfg)
Output:-
Geeksforgeeks
From flask import flask
App=flask (_name_)
@app. route (‘/hello/<name>’)
Def hello_name (name):
Return’Hello%s!’%name
If_name_==’_main_’
app.run ()
Output:-
The protocol is data communication in the World Wide Web.
The data retrieval specified URL defined in protocol methods as,
HEAD:-
It send data to serve the data is not cached.
PUT:-
It gets replaced target resources with content.
GET:-
Also send a simple form to the server.
DELETE:-
It deletes the target resource provided as the URL.
<html>
<body>
<form action=” http://localhost:5000/loginmethod=”post”>
<p>Enter Name :< /p>
<p><input type=”text”name=”nm”/></p>
<p><input type=”submit”value=”submit”/></p>
</form>
</body>
</html>
Then save file
It is considered as a web framework because in situations the equivalent Flask web application is more explicit.
It is easy to start as a beginner because there is little boilerplate code for getting a simple app up and running.
Web application with Flask:-
From flask import Flask
App=Flask (_name_)
@app.route (‘/’)
Def hello_world ():
Return’Hello, World’
If__name__ ==’__main__’ :
app.return ()
The "Hello, World!"
The flask used to do web framework and build database interaction.
Flask sqlalchemy will connect the SQL database to flask application.
From flask import flask
From flask_sqlachemy import SQLAlchemy
App=Flask (_name_)
App.config [‘SQLALCHEMY_DATABASE_URL’] =’postgres: //localhost:5432/flask_todo’
Db=SQLAlchemy (app)
The application development will refer to the data representation of some real objects.
For building of application for car and define model that encapsulates all attributes.
The flask-sqlalchemy is used to set-up and define the model in database.
The db.model will define attributes of modules as db.column.
Here each column must specify the data type and pass data type into call db.column.
Attributes are as follows:-
From.app import db
From datetime import datetime
Class Task (db, Model):
Id=db.column (db.Integer, primary_key=True)
Name=db.Column (db.Unicode, nullbale=False)
Note=db.column (db.Unicode)
Creation_date=db.column (db.DateTime, nullable=False)
Due_date=db.column (db.DateTime)
Completed=db.column (db.Boolean, default=False)
Completed=db.Column (db.Boolean, default=False)
Def__init__ (self,*args, **kwargs):
Super ().__init_ (*args, **kwargs)
Self.creation_Date=datetime.now ()
We create the script called as setup.py and manage the database.
Initialized.py is used to import the db object from app.py and create the table.
From todo.app import db
Import os
If bool (os.environ.get (‘DEBUG’,’’)):
Db.drop_all ()
Db.create_all ()
The job of a web framework for handling an incoming requests and return the response of HTTP.
The flask will provide a separate request object to view the function.
The request object for every function use the object named from flask package.
@app. route (‘/a/sampe/<variable>/route’)
Defsome_view (variable):
Sr.no |
converters |
1 |
Int:-Accept the integer value. |
2 |
Path:-it will accepts the slashes used as a directory separator character |
3 |
Float:-used for the floating-point value. |
The web frameworks will provide routing technique for users to remember the URLs.
We can access the web page without navigating from the Home page.
It is done through route () decorator.
@app. route (‘/hello’)
Def hello_world ():
Return’ hello world’
The add_url_rule () function of an application is used to bind URL with the function.
Def hello_world ():
Return ‘hello world’
App.add_url_rule (‘/’,’hello_world’)
The variables in the flask are used to build a URL by adding the variable parts to the rule parameter.
The variable part is marked as is passed keyword argument.
From flask import flask
App=flask (__name__)
@app. route (‘/hello/’)
Def hello_name (name):
Return ‘Hello%s!’%name
If__name__==’__main__’
app.run (debug=True)
Output:-
Hello GeeksforGeeks!
The web application will require a static file such as javascript or a CSS file to render the display of the web page in the browsers.
Web server is configured to set them during the development of files.
From flask import flask, render_temple
App=Flask (__name__)
@app.route (“/”)
Def index ():
Return render_tenplate (“index.html”)
If__name__==’__main__’
App.run(debug=True)
<html>
<head>
<script type=”text/javascript”src= {{url_for (‘static’, filename=’hello.js’)}}”></script>
</head>
<body>
<input type=”button”onclick=”sayHello ()”value=”sayhello”/>
</body>
</html>
Sessions in Flask:-
The data is stored on the Server and defined as a time interval in which the client logs into a server until the user log out.
The data is in between them and holds in a temporary folder on Server.
The Session object that contains the key-value pair of the variables is associated with the session.
The SECRET_KEY is used to store the data on the cookie.
Session [key] =value
Session.pop (key.None)
Functions of flask are:-
Used to return the response and redirect the user to another target location.
Syntax:-
Flask. redirect (location, statuscode, response)
Used to handle the error in the code.
Syntax:-
Flask. abort (code)
It is very easy and needs HTML attributes, URL handler to fetch the file.
The files are stored on the server and then on the location.
From flask import flask, render_template, request
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’:
F=request. files [‘file’]
f.save (secure_filename (f.filename))
return ‘file uploaded sucessfully’
If__name__==’__main__’
App.run (debug=True)
There are levels of abstraction between you and the database they requests the cache, etc so the performance is better from the start.
The code will provide a huge number of benefits with Flask and have the ability to create multiple Flask applications.
They will create more efficiency, better testability and, better performance.
Applications do not “scale” themselves and infrastructure scales.
So Pinterest is to migrate from Django to Flask as they grew to support more of a micro services pattern.
It has less opinionated so few standards are there to learn.
A Python developer with Django experience will get adjusted to a new Django app quick than a Python developer with Flask experience that would get adjusted to a large Flask application.
The developers can easily collaborate on a single repository and proper code reuse.
Keep the documentation in a single place and then centralize project management/bug tracking, etc.
You have a developer training for contribution of lower quality code and then amplify the bad code.
It is easy to draw the lines of a large standardized framework like Django.
We do not have a full toolset so you may need to build more on your own or search out extensions.
The monoliths will provide a large toolset that is focused on solutions for a larger set of users.