HTTP Request and Response with Flask

http (vecteezy image)

What is HTTP?

HTTP request and response

Quick Start

from flask import Flask, request, render_template, redirect, url_forapp = Flask(__name__)
app.config['ENV'] = 'development'
# creating route
@app.route("/")
def login():
return render_template("login.html")
@app.route("/success")
def success():
return "this is success"
if __name__ == "__main__":
app.run(debug=True)

Form request

HTML login form

<div class="form_container">
<form class="form_2" method="POST" action={{url_for("login")}}>
<div class="input_fields">
<h1>User Login</h1>
<input type="text" name="email" id="name" placeholder="Name" required>
<input type="password" name="password" id="password" placeholder="Password" required>

</div>
<button type="submit" class="outline_md_btn">
Submit
</button>

</form>
</div>

Flask Request Object

from flask import request

Get Requested Client Data

1. Get request method

request.method
from flask import request@app.route("/", methods=['GET', 'POST'])
def login():
print(request.method)
return render_template("login.html")
@app.route("/", methods=['GET', 'POST'])
def login():
if request.method == 'POST':
print(request.form['email'])
print(request.form['password'])
return redirect(url_for("success"))
return render_template("login.html")

2. Get form data

request.form[' ']
<input type="text" name="email" id="name" placeholder="Name" required>
request.form['email']

3. Get Request Header

request.headers
@app.route("/", methods=['GET', 'POST'])
def login():
if request.method == 'POST':
print(request.headers)
print(request.form['email'])
print(request.form['password'])
return redirect(url_for("success"))
return render_template("login.html")

4. Get files from request

request.files['upload']

5. Get cookies from request

request.cookies.get('auth_token')

6. Get request arguments

@app.route("/success")
def success():
print(request.args['email'])
return render_template("success.html")
@app.route("/", methods=['GET', 'POST'])
def login():
if request.method == 'POST':
print(request.headers)
print(request.form['email'])
print(request.form['password'])
return redirect(url_for("success", email=request.form['email']))
return render_template("login.html")


@app.route("/success")
def success():
print(request.args['email'])
return f"<h1>{request.args['email']}</h1>"

Flask Response

return template

@app.route("/", methods=['GET', 'POST'])
def login():
return render_template("login.html")

return text

@app.route("/")
def home():
return "home"

return json

@app.route("/users")
def user():
return jsonify({'name': 'sofia', 'email': 'sofia@gmail.com'})

Make response

response = make_response(render_template('home.html'))
response.set_cookie('auth_token', encoded_jwt.decode())
return response, 201

Learning javascript and web-development