KEMBAR78
Flask Final With Ajax | PDF | Ajax (Programming) | Web Server
0% found this document useful (0 votes)
61 views33 pages

Flask Final With Ajax

Flask book

Uploaded by

jenishgojariya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views33 pages

Flask Final With Ajax

Flask book

Uploaded by

jenishgojariya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Flask Introduction

Flask is a web application framework written in Python. A Web Application Framework


or a simply a Web Framework

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.

It is based on WSGI toolkit and jinja2 template engine.

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:

 Template inheritance and inclusion.

 Define and import macros within templates

creating the Flask class object:

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

Usually you create a Flask instance in your main module

from flask import Flask // import Flask in Python

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”

the server needs to be started by

app.run()

the program will be

from flask import Flask

app = Flask(__name__)

@app.route('/')
defindex():
return'Web App with Python Flask!'

app.run()

2
Vivekanand college of BCA
Flask Introduction

5.1.3.1 route() , run(), add_url_rule():


Route() method: Modern web apps use a technique named routing.

Routes in Flask are mapped to Python functions. You have already created one route, the ‘/‘ route:

@app.route('/')
33defindex():

The route() decorator, @app.route(), binds a URL to a function.

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"

The output of the function hello_world() is shown in your browser.

Route method with different arguments:

from flask import Flask, redirect, url_for


app= Flask(__name__)
@app.route("/") // takes / as decorator
def home():
return "<h1> Hello, World! This is a home page </h1>"
@app.route("/<name>") // takes any string after the url
def user(name):
return "Hello! Your name is" + str(name)
@app.route("/sales/<prid>") // takes number
defgetprid(prid=0):
return " productid is "+str(prid)

@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)

It accepts the following parameters.

3
Vivekanand college of BCA
Flask Introduction

1. rule: It represents the URL binding with the function.


2. options: It represents the list of parameters to be associated with the rule object

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.

The syntax is given below.

1. app.run(host, port, debug, options)

SN Option Description

1 host The default hostname is 127.0.0.1, i.e. localhost.

2 port The port number to which the server is listening to. The default port number is 5000

3 debug The default is false. It provides debug information if it is set to true.

4 options It contains the information to be forwarded to the server.

1. rom flask import Flask


2. app = Flask(__name__)
3.
4. @app.route('/home')
5. def home():
6. return "hello, welcome to our website";
7.
8. if __name__ =="__main__":
9. app.run(debug = True)

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)

It will produce the following result on the web browser.

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.

Consider the following example.

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.

The add_url_rule() function


There is one more approach to perform routing for the flask web application that can be done by
using the add_url() function of the Flask class. The syntax to use this function is given below.

1. add_url_rule(<url rule>, <endpoint>, <view function>)

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

Consider the following example.

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)

Flask URL Building


The url_for() function is used to build a URL to the specific function dynamically. The first
argument is the name of the specified function, and then we can pass any number of
keyword argument corresponding to the variable part of the URL.

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

Consider the following python flask script.

Example

1. from flask import *


2.
3. app = Flask(__name__)
4.
5. @app.route('/admin')
6. def admin():
7. return 'admin'
8.
9. @app.route('/librarion')
10. def librarion():
11. return 'librarion'
12.
13. @app.route('/student')
14. def student():
15. return 'student'
16.
17. @app.route('/user/<name>')
18. def user(name):
19. if name == 'admin':
20. return redirect(url_for('admin'))
21. if name == 'librarion':
22. return redirect(url_for('librarion'))
23. if name == 'student':
24. return redirect(url_for('student'))
25. if __name__ =='__main__':
26. app.run(debug = True)

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:

Flask HTTP methods


HTTP is the hypertext transfer protocol which is considered as the foundation of the data transfer
in the world wide web. All web frameworks including flask need to provide several HTTP
methods for data communication.

The methods are given in the following table.

SN Method Description

1 GET It is the most common method which can be used to send data in the unencrypted form to

the server. @app.route(‘/’,methods=[‘GET’])

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

1. from flask import *

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

Now, create the following python script as get_example.py.

get_example.py

1. from flask import *


2. app = Flask(__name__)
3.
4.
5. @app.route('/login',methods = ['GET'
'GET'])
6. def login():
7. uname=request.args.get('uname'
'uname')
8. passwrd=request.args.get('pass'
'pass')
9. if uname=="ayush" and passwrd==
passwrd=="google":
10. return "Welcome %s" %uname
11.
12. if __name__ == '__main__':
13. app.run()

Now, open the HTML file, login.html on the web browser and give the required input.
in

Now, click the submit button.

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.

The data is obtained by using the following line of code.

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.

Dynamic data representation using Jinja2


Jinja2:

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.

Consider the following example.

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

1. from flask import *


2. app = Flask(__name__)
3.
4. @app.route('/')
5. def message():
6. return render_template('message.html')
7. if __name__ == '__main__':
8. app.run(debug = True)

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.

o {% ... %} for statements


o {{ ... }} for expressions to print to the template output
o {# ... #} for the comments that are not included in the template output
o # ... ## for line statement

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)

Embedding Python statements in HTML


Due to the fact that HTML is a mark-up language and purely used for the designing
purpose, sometimes, in the web applications, we may need to execute the statements
for the general-purpose computations. For this purpose, Flask facilitates us the delimiter
{%...%} which can be used to embed the simple python statements into the HTML.

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

from flask import *


app = Flask(__name__)

@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

Referring Static files in HTML


The static files such as CSS or JavaScript file enhance the display of an HTML web page.
A web server is configured to serve such files from the static folder in the package or the
next to the module. The static files are available at the path /static of the application.

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

1. from flask import *


2. app = Flask(__name__)
3.
4. @app.route('/')
5. def message():
6. return render_template('message.html')
7. if __name__ == '__main__':
8. app.run(debug = True)

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

Flask File Uploading


File uploading is the process of transmitting the binary or normal files to the server. Flask
facilitates us to upload the files easily. All we need to have an HTML form with the encryption
set to multipart/form-data.

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

1 app.config['UPLOAD_FOLDER'] It is used to mention the upload folder.

2 app.config['MAX_CONTENT-PATH'] It is used to mention the maximum size of the file to be uplo

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

from flask import *


app = Flask(__name__)

@app.route('/')
def upload():
return render_template("file_upload_form.html")

24
Vivekanand college of BCA
Flask Introduction

@app.route('/success', methods = ['POST'])


def success():
if request.method == 'POST':
q f = request.files['file']
f.save(f.filename)
return render_template("success.html", name = f.filename)

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.

The below snapshot is generated for the URL localhost:5000/success. On successfully


uploading the file, a success message is shown to the user with the name of the
uploaded file.

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?

AJAX = Asynchronous JavaScript and XML.

AJAX is a technique for creating fast and dynamic web pages.

AJAX allows web pages to be updated asynchronously by exchanging small


amounts of data with the server behind the scenes. This means that it is
possible to update parts of a web page, without reloading the whole page.

Example: Google Maps, Gmail, Youtube, and Facebook tabs

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.

However, if the input field is not empty, do the following:

 Create an XMLHttpRequest object


 Create the function to be executed when the server response is ready
 Send the request off to a PHP file (gethint.php) on the server
o State=1request has been setup
o State=2 request sent
o state=3 request process
o State=4 request complete
o Status=404 for file not found
o Status=200 for file found
 Notice that q parameter is added to the url (gethint.php?q="+str)
 And the str variable holds the content of the input field

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()
{

if (this.readyState == 4 && this.status == 200)

document.getElementById("txtHint").innerHTML =
this.responseText;
}

};

varxmlhttp.open("GET","get_user.php?q="+str,true);

//true for asynchronous data

29
Vivekanand college of BCA
Flask Introduction

varxmlhttp.send();

}
}

</script>
</head>

<body>
<form>

<select name="users" onchange="showUser(this.value)">

<option value="">Select a dept:</option>


<option value="1">sales</option>

<option value="2">purchase</option>
<option value="3">personal</option>

</select>

</form>
<br>

<div id="txtHint"><b>Person info will be listed here...</b></div>

</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

$que="SELECT * FROM dept WHERE did=$q";


$result = $con->query($que);

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>

 A variable varxmlhttp is declared. Then, a new XMLHttpRequest object is


created. If a your target audience use browsers older than Internet Explorer 8,
ActiveXObject is used to create XMLHttpRequest.
 'onreadystatechange' is a property of XMLHttpRequest object which is called
whenever 'readyState' attribute is changed.
 We check whether the value of the 'readyState' property is 4, which denotes that
the operation is complete.
 If the operation is completed, the status of the response to the request is
checked. It returns the HTTP result code. Result code 200 states that the
response to the request is successful.
 Now we set the value of the string to be displayed within the div whose id is
'suggestion' as 'responseText' property of the XMLHttpRequest object.
'responseText' is the response to the request as text.
 By using 'open' method of XMLHttpRequest object, a new request to the server is
initialized. There are three parameters passed by this method. 'POST'
determines the type of the httprequest. ‘get_user.php' sets the server side file
and setting the third parameter 'true' states that the request should be handled
asynchronously.
 'send' method is used to send data contained in the 'data' variable to the server.

Uploading file code:


Upload_file.py

31
Vivekanand college of BCA
Flask Introduction

from flask import *

app = Flask(__name__)

@app.route('/')

def upload():

return render_template("upload_file.html")

@app.route('/success', methods = ['POST'])

def success():

if request.method == 'POST':

f = request.files['file']

f.save(f.filename)

return render_template("upload_file1.html", name = f.filename)

if __name__ == '__main__':

app.run()

upload_file.html

html>

<head>

<title>upload</title>

</head>

<body>

<form action = "/success" method = "post" enctype="multipart/form-data">

32
Vivekanand college of BCA
Flask Introduction

<input type="file" name="file" />

<input type = "submit" value="Upload">

</form>

</body>

</html>

Upload_file1.html

<html>

<head>

<title>success</title>

</head>

<body>

<p>File uploaded successfully</p>

<p>File Name: {{name}}</p>

</body>

</html>

33
Vivekanand college of BCA

You might also like