Flask Final With Ajax
Flask Final With Ajax
Framework represents a collection of libraries and modules that enable web application
developers to write applications without worrying about low-level details such as
protocol, thread management, and so on.
Flask is called a "micro" framework because it doesn't directly provide features like form
validation, database abstraction, authentication, and so on. Such features are instead
provided by special Python packages called Flask extensions. The extensions integrate
seamlessly with Flask so that they appear as if they were part of Flask itself.
What is WSGI?
It is an acronym for web server gateway interface which is a standard for python web
application development. It is considered as the specification for the universal interface
between the web server and web application.
There are multiple WSGI containers that are available today. Hence, a WSGI container is
required to be installed in the project so that a web server can communicate to a WSGI
container which further communicates to the Python application and provides the
response back accordingly. Finally, when the web server obtains the response, it is sent
back to the web browser/users.
What is Jinja2?
Jinja2 is a web template engine which combines a template with a certain data source to
render the dynamic web pages.
1
Vivekanand college of BCA
Flask Introduction
Jinja is a fast, expressive, extensible templating engine. Special placeholders in the template
allow writing code similar to Python syntax. Then the template is passed data to render the
final document.
It includes:
The flask object implements a WSGI application and acts as the central object. It is passed the
name of the module or package of the application
Create app, that hosts the applicationFlask constructor takes the name of current
module(__name__) as argument.
app = Flask(__name__)
Then you need a route that calls a Python function. A route maps what you type in the
browser (the url) to a Python function.
@app.route('/')
defindex():
return “hello world”
app.run()
app = Flask(__name__)
@app.route('/')
defindex():
return'Web App with Python Flask!'
app.run()
2
Vivekanand college of BCA
Flask Introduction
Routes in Flask are mapped to Python functions. You have already created one route, the ‘/‘ route:
@app.route('/')
33defindex():
If you want the route /hello, you can bind it to the hello_world() function like this:
@app.route('/hello')
defhello_world():
return"hello world"
@app.route("/admin")
def admin():
return redirect(url_for("home")) // redirects the /admin to home()
if __name__=='__main__':
app.run("localhost",port=8000)
The route() function of the Flask class defines the URL mapping of the associated
function. The syntax is given below.
1. app.route(rule, options)
3
Vivekanand college of BCA
Flask Introduction
As we can see here, the / URL is bound to the main function which is responsible for
returning the server response. It can return a string to be printed on the browser's
window or we can use the HTML template to return the HTML file as a response from
the server.
Finally, the run method of the Flask class is used to run the flask application on the local
development server.
SN Option Description
2 port The port number to which the server is listening to. The default port number is 5000
4
Vivekanand college of BCA
Flask Introduction
Flask facilitates us to add the variable part to the URL by using the section. We can reuse the
variable by adding that as a parameter into the view function. Consider the following example.
Example
1. from flask import Flask
2. app = Flask(__name__)
3.
4. @app.route('/home/<name>')
5. def home(name):
6. return "hello,"+name;
7.
8. if __name__ =="__main__":
9. app.run(debug = True)
The converter can also be used in the URL to map the specified variable to the particular data
type. For example, we can provide the integers or float like age or salary respectively.
Example
1. from flask import Flask
2. app = Flask(__name__)
3.
5
Vivekanand college of BCA
Flask Introduction
4. @app.route('/home/<int:age>')
5. def home(age):
6. return "Age = %d"%age;
7.
8. if __name__ =="__main__":
9. app.run(debug = True)
The following converters are used to convert the default string type to the associated data type.
1. string: default
2. int: used to convert the string to the integer
3. float: used to convert the string to the float.
4. path: It can accept the slashes given in the URL.
This function is mainly used in the case if the view function is not given and we need to connect
a view function to an endpoint externally by using this function.
6
Vivekanand college of BCA
Flask Introduction
Example
1. from flask import Flask
2. app = Flask(__name__)
3.
4. def about():
5. return "This is about page";
6.
7. app.add_url_rule("/about","about",about)
8.
9. if __name__ =="__main__":
10. app.run(debug = True)
This function is useful in the sense that we can avoid hard-coding the URLs into the
templates by dynamically building them using this function.
7
Vivekanand college of BCA
Flask Introduction
Example
8
Vivekanand college of BCA
Flask Introduction
The above script simulates the library management system which can be used by the
three types of users, i.e., admin, librarion, and student. There is a specific function
named user() which recognizes the user the redirect the user to the exact function which
contains the implementation for this particular function
Benefits of the Dynamic URL Building
1. It avoids hard coding of the URLs.
2. We can change the URLs dynamically instead of remembering the manually changed hard-coded
URLs.
3. URL building handles the escaping of special characters and Unicode data transparently.
4. The generated paths are always absolute, avoiding unexpected behavior of relative paths in
browsers.
5. If your application is placed outside the URL root, for example, in /myapplication instead of /,
url_for() properly handles that for you.
5.3 Flask HTTP methods:
SN Method Description
1 GET It is the most common method which can be used to send data in the unencrypted form to
2 HEAD It is similar to the GET but used without the response body.
3 POST It is used to send the form data to the server. The server does not cache the data transmitte
method. @app.route(‘/’,methods=[‘POST’])
4 PUT It is used to replace all the current representation of the target resource with the uploaded
9
Vivekanand college of BCA
Flask Introduction
content. @app.route(‘/’,methods=[‘PUT’])
5 DELETE It is used to delete all the current representation of the target resource specified in the
URL. @app.route(‘/’,methods=[‘DELETE’])
We can specify which HTTP method to be used to handle the requests in the route() function of
the Flask class. By default, the requests are handled by the GET() method.
POST Method
To handle the POST requests at the server, let us first create a form to get some data at the client
side from the user, and we will try to access this data on the server by using the POST request.
login.html
1. <html>
2. <body>
3. <form action = "http://localhost:5000/login" method = "post">
4. <table>
5. <tr><td>Name</td>
6. <td><input type ="text" name ="uname"></td></tr>
7. <tr><td>Password</td>
8. <td><input type ="password" name ="pass"></td></tr>
9. <tr><td><input type = "submit"></td></tr>
10. </table>
11. </form>
12. </body>
13. </html>
Now, Enter the following code into the script named post_example.py.
post_example.py
10
Vivekanand college of BCA
Flask Introduction
2. app = Flask(__name__)
3.
4. @app.route('/login',methods = ['POST'
'POST'])
5. def login():
6. uname=request.form['uname'
'uname']
7. passwrd=request.form['pass']]
8. if uname=="ayush" and passwrd==
passwrd=="google":
9. return "Welcome %s" %uname
10.
11. if __name__ == '__main__':
12. app.run(debug = True)
Now, start the development server by running the script using python post_exmple.py and open
login.html on the web browser as shown in the following image.
Give the required input and click Submit, we will get the following result.
11
Vivekanand college of BCA
Flask Introduction
Hence, the form data is sent to the development server by using the post method.
GET Method
Let's consider the same example for the Get method. However, there are some changes in the
data retrieval syntax on the server side. First, create a form as login.html.
login.html
1. <html>
2. <body>
3. <form action = "http://localhost:5000/login" method = "get">
4. <table>
5. <tr><td>Name</td>
6. <td><input type ="text" name ="uname"></td></tr>
7. <tr><td>Password</td>
8. <td><input type ="password"
"password" name ="pass"></td></tr>
9. <tr><td><input type = "submit"
"submit"></td></tr>
10. </table>
11. </form>
12. </body>
13. </html>
12
Vivekanand college of BCA
Flask Introduction
get_example.py
Now, open the HTML file, login.html on the web browser and give the required input.
in
13
Vivekanand college of BCA
Flask Introduction
As we can check the result. The data sent using the get() method is retrieved on the
development server.
uname = request.args.get('uname'
'uname')
Here, the args is a dictionary object which contains the list of pairs of form parameter and its
corresponding value.
In the above image, we can also check the URL which also contains the data sent with
the request to the server. This is an important difference between the GET requests and
the POST requests as the data sent to the server is not shown in the URL on the browser
in the POST requests.
Flask facilitates us to render the external HTML file instead of hardcoding the HTML in
i the view
function. Here, we can take advantage of the jinja2 template engine on which the flask is based.
Flask provides us the render_template() function which can be used to render the
external HTML file to be returned as the response from the view fun
function.
ction.
14
Vivekanand college of BCA
Flask Introduction
Example
To render an HTML file from the view function, let's first create an HTML file named as
message.html.
message.html
1. <html>
2. <head>
3. <title>Message</title>
4. </head>
5. <body>
6. <h1>hi, welcome to the website </h1>
7. </body>
8. </html>
script.py
Here, we must create the folder templates inside the application directory and save the
HTML templates referenced in the flask script in that directory.
In our case, the path of our script file script.py is E:\flask whereas the path of the HTML
template is E:\flask\templates
15
Vivekanand college of BCA
Flask Introduction
Jinja2 Delimiters:
Jinga 2 template engine provides some delimiters which can be used in the HTML to
make it capable of dynamic data representation. The template system provides some
HTML syntax which are placeholders for variables and expressions that are replaced by
their actual values when the template is rendered.
The jinga2 template engine provides the following delimiters to escape from the HTML.
Example
Consider the following example where the variable part of the URL is shown in the
HTML script using the {{ ... }} delimiter.
Msg1.html
<html>
<head>
<title>Message</title>
</head>
<body>
<h1>hi, {{ name }}</h1>
</body>
</html>
16
Vivekanand college of BCA
Flask Introduction
Script.py
from flask import *
app = Flask(__name__)
@app.route('/<uname>')
def message(uname):
return render_template('msg1.html',name=uname)
if __name__ == '__main__':
app.run(debug = True)
Example
In the following example, we will print the table of a number specified in the URL, i.e.,
the URL http://localhost:5000/table/10 will print the table of 10 on the browser's
window.
script.py
@app.route('/table/<int:num>')
def table(num):
return render_template('print-table.html',n=num)
if __name__ == '__main__':
17
Vivekanand college of BCA
Flask Introduction
app.run(debug = True)
print-table.html
<html>
<head>
<title>print table</title>
</head>
<body>
<h2> printing table of {{n}}</h2>
{% for i in range(1,11): %}
<h3>{{n}} X {{i}} = {{n * i}} </h3>
{% endfor %}
</body>
</html>
18
Vivekanand college of BCA
Flask Introduction
Example
In the following example, the flask script returns the HTML file, i.e., message.html which
is styled using the stylesheet style.css
style.css. The flask template system finds
nds the static CSS file
under static/css directory. Hence the style.css is saved at the specified path.
19
Vivekanand college of BCA
Flask Introduction
script.py
message.html
1. <html>
2. <head>
3. <title>Message</title>
4. <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
5. </head>
6.
7. <body>
8. <h1>hi, welcome to the website</h1>
9. </body>
10. </html>
style.css
1. body {
2. background-color:blue;
3. }
4. h1 {
5. color: blue;
6. }
7. p {
8. color: red;
9. }
20
Vivekanand college of BCA
Flask Introduction
Flask Session
The session data is stored on the server.
The session can be defined as the duration for which a user logs into the server and logs out. The
data which is used to track this session is stored into the temporary directory on the server.
The session data is stored on the top of cookies and signed by the server cryptographically.
In the flask, a session object is used to track the session data which is a dictionary object
that contains a key-value pair of the session variables and their associated values.
The following syntax is used to set the session variable to a specific value on the server.
1. Session[<variable-name>] = <value>
To remove a session variable, use the pop() method on the session object and mention
the variable to be removed.
1. session.pop(<variable-name>, none)
Let's see a simple example to understand how can we set and get the session variable.
Example
from flask import *
21
Vivekanand college of BCA
Flask Introduction
app = Flask(__name__)
app.secret_key = "abc"
@app.route('/')
def home():
res = make_response("<h4>session variable is set, <a href='/get'>Get Variable</a></h4>")
session['response']='session#1'
return res;
@app.route('/get')
def getVariable():
if 'response' in session:
s = session['response'];
return render_template('getsession.html',name = s)
if __name__ == '__main__':
app.run(debug = True)
getsession.html
<html>
<head>
<title>getting the session</title>
</head>
<body>
<p>The session is set with value: <strong>{{name}}</strong></p>
</body>
</html>
22
Vivekanand college of BCA
Flask Introduction
The server-side flask script fetches the file from the request object using request.files[] Object.
On successfully uploading the file, it is saved to the desired location on the server.
23
Vivekanand college of BCA
Flask Introduction
The uploaded file is saved to the temporary directory of the server for a while before it is saved
to some desired location. The name of the destination file can be obtained using the following
syntax.
1. name = request.files['file'].filename
However, we can mention the path of the folder where the file is to be uploaded to the server and
the maximum size of the uploaded file. This all can be done in the configuration settings of the
flask object.
SN Syntax Description
Consider the following example to upload a file from the local file system to the server.
Example
In this example, we will provide a file selector(file_upload_form.html) to the user where
the user can select a file from the file system and submit it to the server.
At the server side, the file is fetched using the request.files['file'] object and saved to the
location on the server.
Since we are using the development server on the same device, hence the file will be
uploaded to the directory from where the flask script upload.py is executed.
upload.py
@app.route('/')
def upload():
return render_template("file_upload_form.html")
24
Vivekanand college of BCA
Flask Introduction
if __name__ == '__main__':
app.run(debug = True)
file_upload_form.html
<html>
<head>
<title>upload</title>
</head>
<body>
<form action = "/success" method = "post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type = "submit" value="Upload">
</form>
</body>
</html>
success.html
<html>
<head>
<title>success</title>
</head>
<body>
<p>File uploaded successfully</p>
<p>File Name: {{name}}</p>
</body>
</html>
25
Vivekanand college of BCA
Flask Introduction
An HTML form is shown to the user so that the user can browse the file system for the
file which will be uploaded to the development server.
Here, the user has chosen a file named as galexy.jpg which will be uploaded to the
server.
26
Vivekanand college of BCA
Flask Introduction
We can confirm this by checking into the directory where the upload.py is located as
given in the below image.
27
Vivekanand college of BCA
Flask Introduction
What is AJAX?
Code explanation:
First, check if the input field is empty (str.length == 0). If it is, clear the
content of the txtHint placeholder and exit the function.
28
Vivekanand college of BCA
Flask Introduction
Ajax_test.php
<html>
<head>
<script>
function showUser(str)
if (str == "")
{
document.getElementById("txtHint").innerHTML = "";
return;
}
else
{
varxmlhttp = new XMLHttpRequest();
varxmlhttp.onreadystatechange = function()
{
document.getElementById("txtHint").innerHTML =
this.responseText;
}
};
varxmlhttp.open("GET","get_user.php?q="+str,true);
29
Vivekanand college of BCA
Flask Introduction
varxmlhttp.send();
}
}
</script>
</head>
<body>
<form>
<option value="2">purchase</option>
<option value="3">personal</option>
</select>
</form>
<br>
</body>
</html>
getuser.php
<html>
<head>
</head>
<body>
<?php
$q = $_GET['q'];
#$q=1;
$con = mysqli_connect("localhost","root","","testdb");
30
Vivekanand college of BCA
Flask Introduction
echo "<table>
<tr>
<th>DID</th>
<th>Dname</th>
</tr>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['did'] . "</td>";
echo "<td>" . $row['dname'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
31
Vivekanand college of BCA
Flask Introduction
app = Flask(__name__)
@app.route('/')
def upload():
return render_template("upload_file.html")
def success():
if request.method == 'POST':
f = request.files['file']
f.save(f.filename)
if __name__ == '__main__':
app.run()
upload_file.html
html>
<head>
<title>upload</title>
</head>
<body>
32
Vivekanand college of BCA
Flask Introduction
</form>
</body>
</html>
Upload_file1.html
<html>
<head>
<title>success</title>
</head>
<body>
</body>
</html>
33
Vivekanand college of BCA