HTTP Methods
HTTP (HyperText Transfer Protocol) methods are used to
perform actions on web resources. Here’s a list of the most
commonly used HTTP methods:
1. GET: Requests data from a specified resource.
2. POST: Submits data to be processed to a specified
resource.
3. PUT: Updates a current resource with new data.
4. DELETE: Deletes a specified resource.
5. HEAD: Similar to GET, but it retrieves only the headers
and not the body of the resource.
6. OPTIONS: Describes the communication options for the
target resource.
7. PATCH: Partially updates a specified resource.
Example:
1.Create a templates directory in your project folder and place
an index.html file in it with the form content.
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Form Example</title>
</head>
<body>
<!-- GET Form -->
<form method="GET" action="/get">
<input type="text" name="get_data"
placeholder="Enter some data">
<input type="submit" value="GET Request">
</form>
<br>
<!-- POST Form -->
<form method="POST" action="/post">
<input type="text" name="post_data"
placeholder="Enter some data">
<input type="submit" value="POST
Request">
</form>
<br>
<!-- PUT Form -->
<form method="POST" action="/put?
_method=PUT">
<input type="text" name="put_data"
placeholder="Enter new data">
<input type="submit" value="PUT Request">
</form>
<br>
<!-- DELETE Form -->
<form method="POST" action="/delete?
_method=DELETE">
<input type="text" name="delete_data"
placeholder="Enter data to delete">
<input type="submit" value="DELETE
Request">
</form>
<br>
<!-- PATCH Form -->
<form method="POST" action="/patch?
_method=PATCH">
<input type="text" name="patch_data"
placeholder="Enter data to update">
<input type="submit" value="PATCH
Request">
</form>
</body>
</html>
2. Create a Flask application to handle the form
submissions.
app.py:
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/get', methods=['GET'])
def get_example():
data = request.args.get('get_data')
return f'Received GET data: {data}'
@app.route('/post', methods=['POST'])
def post_example():
data = request.form['post_data']
return f'Received POST data: {data}'
@app.route('/put', methods=['POST'])
def put_example():
try:
if request.args.get('_method') == 'PUT':
data = request.form['put_data']
return f'Received PUT data: {data}'
else:
return 'PUT request not properly
formatted'
except Exception as e:
return f'Error processing PUT request:
{str(e)}'
@app.route('/delete', methods=['POST'])
def delete_example():
try:
if request.args.get('_method') ==
'DELETE':
data = request.form['delete_data']
return f'Deleted data: {data}'
else:
return 'DELETE request not properly
formatted'
except Exception as e:
return f'Error processing DELETE request:
{str(e)}'
@app.route('/patch', methods=['POST'])
def patch_example():
try:
if request.args.get('_method') ==
'PATCH':
data = request.form['patch_data']
return f'Patched data: {data}'
else:
return 'PATCH request not properly
formatted'
except Exception as e:
return f'Error processing PATCH request:
{str(e)}'
if __name__ == '__main__':
app.run(debug=True)
Flask -Templates
Flask uses Jinja2 as its template engine to render dynamic web pages.
Creating Templates: Store your HTML templates in a directory
named templates in your project folder.
Rendering Templates: Use the render_template function to
render HTML templates.
Structure of Project
Set3_1/
│
|── templates/
│ ├── index.html
|── static/
└── styles.css
├── app.py
app.py
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def home():
return render_template('index.html')
if __name__ == '__main__':
app.run(debug=True)
templates/
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Simple Web Server</title>
</head>
<body>
<h1>Welcome to the Simple Web Server!</h1>
<p>This is a static HTML page served by
Flask.</p>
</body>
</html>
Static/
Styles.css
/* static/styles.css */
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
margin: 0;
padding: 0;
}
h1 {
color: #333;
text-align: center;
margin-top: 20px;
}
p {
color: #666;
text-align: center;
}
.container {
width: 50%;
margin: 100px auto;
padding: 20px;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 8px;
}
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 {%..%}.
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.
Flask – Request Object
Sending Form Data to Template.
Form: A dictionary object containing key-value pairs of form
parameters and their values. It's used to access data sent via POST
requests.
python
from flask import Flask, request
app = Flask(__name__)
@app.route('/submit', methods=['POST'])
def submit():
name = request.form['name']
return f'Hello, {name}!'
args: A dictionary object containing parsed contents of the query
string, which is part of the URL after the question mark (?). It's used to
access data sent via GET requests.
python
@app.route('/search', methods=['GET'])
def search():
query = request.args.get('query')
return f'Search results for: {query}'
Cookies: A dictionary object holding Cookie names and values. It’s
used to access cookies sent by the client.
python
@app.route('/show_cookies', methods=['GET'])
def show_cookies():
user_cookie = request.cookies.get('username')
return f'Username cookie: {user_cookie}'
files: A dictionary object containing the data pertaining to uploaded
files. It’s used to handle file uploads.
python
@app.route('/upload', methods=['POST'])
def upload_file():
file = request.files['file']
return f'File uploaded: {file.filename}'
method: A string representing the current request method (e.g.,
'GET', 'POST', 'PUT', etc.).
python
@app.route('/request_method', methods=['GET', 'POST'])
def request_method():
return f'The request method is: {request.method}'
HTTP status codes and their descriptions in Flask:
Status
Name Description
Code
200 OK The request has succeeded.
The request has been fulfilled and resulted in a new resource
201 Created
being created.
The server successfully processed the request, but is not
204 No Content
returning any content.
Moved The requested resource has been assigned a new permanent
301
Permanently URI.
The requested resource resides temporarily under a different
302 Found
URI.
The server could not understand the request due to invalid
400 Bad Request
syntax.
401 Unauthorized The request requires user authentication.
403 Forbidden The server understood the request, but refuses to authorize it.
404 Not Found The server can't find the requested resource.
Method Not The request method is known by the server but has been
405
Allowed disabled and cannot be used.
500 Internal Server The server encountered an unexpected condition that prevented
Status
Name Description
Code
Error it from fulfilling the request.
The server received an invalid response from the upstream
502 Bad Gateway
server while acting as a gateway or proxy.
Service The server is not ready to handle the request. Common causes
503
Unavailable include server maintenance or overload.