Flask is a web application framework written in Python. Armin Ronacher, who leads an international group of Python enthusiasts named Pocco, develops it. Flask is based on Werkzeug WSGI toolkit and Jinja2 template engine. Both are Pocco projects.
What is Flask?
Flask is a web application framework written in Python. It is developed by Armin Ronacher, who leads an international group of Python enthusiasts named Pocco. Flask is based on the Werkzeug WSGI toolkit and
Jinja2 template engine. Both are Pocco projects.
WSGI
Web Server Gateway Interface (WSGI) has been adopted as a standard for Python web application development. WSGI is a specification for a universal interface between the web server and the web applications.
Werkzeug
It is a WSGI toolkit, which implements requests, response objects, and other utility functions. This enables building a web framework on top of it. The Flask framework uses Werkzeug as one of its bases.
Jinja2
Jinja2 is a popular templating engine for Python. A web templating system combines a template with a certain data source to render dynamic web pages.
Flask is often referred to as a micro framework. It aims to keep the core of an application simple yet extensible. Flask does not have built-in abstraction layer for database handling, nor does it have form a validation
support. Instead, Flask supports the extensions to add such functionality to the application.
pip install virtualenv
mkdir newproj
cd newproj
virtualenv venv
virtualenv venv
venv\scripts\activate
pip install Flask
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World'
if __name__ == '__main__':
app.run(debug = True)
app.route(rule, 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. |
app.run(host, port, debug, options)
app.run(debug = True)
@app.route('/home')
def home():
return "hello, welcome to our website";
@app.route('/home/<int:age>')
def home(age):
return "Age = %d"%age;
add_url_rule(<url rule>, <endpoint>, <view function>)
def about():
return "This is about page";
app.add_url_rule("/about","about",about)
@app.route('/user/')
def user(name):
if name == 'admin':
return redirect(url_for('admin'))
if name == 'librarion':
return redirect(url_for('librarion'))
if name == 'student':
return redirect(url_for('student'))
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. |
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 transmitted using the post method. |
4 | PUT | It is used to replace all the current representation of the target resource with the uploaded content. |
5 | DELETE | It is used to delete all the current representation of the target resource specified in the URL. |
<form action = "http://localhost:5000/login" method = "post">
<table>
<tr><td>Name</td>
<td><input type ="text" name ="uname"></td></tr>
<tr><td>Password</td>
<td><input type ="password" name ="pass"></td></tr>
<tr><td><input type = "submit"></td></tr>
</table>
</form>
@app.route('/login',methods = ['POST'])
def login():
uname=request.form['uname']
passwrd=request.form['pass']
if uname=="ayush" and passwrd=="google":
return "Welcome %s" %uname
<form action = "http://localhost:5000/login" method = "get">
<table>
<tr><td>Name</td>
<td><input type ="text" name ="uname"></td></tr>
<tr><td>Password</td>
<td><input type ="password" name ="pass"></td></tr>
<tr><td><input type = "submit"></td></tr>
</table>
</form>
@app.route('/')
def message():
return " <html><body><h1>Hi, welcome to the website</h1></body></html>"
@app.route('/')
def message():
return render_template('message.html')
<html>
<head>
<title>Message</title>
</head>
<body>
<h1>hi, {{ name }}</h1>
</body>
</html>
@app.route('/user/<uname>')
def message(uname):
return render_template('message.html',name=uname)
<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>
@app.route('/table/<int:num>')
def table(num):
return render_template('print-table.html',n=num)
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
SN | Attribute | Description |
---|---|---|
1 | Form | It is the dictionary object which contains the key-value pair of form parameters and their values. |
2 | args | It is parsed from the URL. It is the part of the URL which is specified in the URL after question mark (?). |
3 | Cookies | It is the dictionary object containing cookie names and the values. It is saved at the client-side to track the user session. |
4 | files | It contains the data related to the uploaded file. |
5 | method | It is the current request method (get or post). |
<html>
<body>
<h3>Register the customer, fill the following form.</h3>
<form action = "http://localhost:5000/success" method = "POST">
<p>Name <input type = "text" name = "name" /></p>
<p>Email <input type = "email" name = "email" /></p>
<p>Contact <input type = "text" name = "contact" /></p>
<p>Pin code <input type ="text" name = "pin" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
@app.route('/success',methods = ['POST', 'GET'])
def print_data():
if request.method == 'POST':
result = request.form
return render_template("result_data.html",result = result)
<p><strong>Thanks for the registration. Confirm your details</strong></p>
<table border = 1>
{% for key, value in result.items() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
response.setCookie(<title>, <content>, <expiry time>)
request.cookies.get(<title>)
@app.route('/cookie')
def cookie():
res = make_response("<h1>cookie is set</h1>")
res.set_cookie('foo','bar')
return res
from flask import *
app = Flask(__name__)
@app.route('/error')
def error():
return "<p><strong>Enter correct password</strong></p>"
@app.route('/')
def login():
return render_template("login.html")
@app.route('/success',methods = ['POST'])
def success():
if request.method == "POST":
email = request.form['email']
password = request.form['pass']
if password=="jtp":
resp = make_response(render_template('success.html'))
resp.set_cookie('email',email)
return resp
else:
return redirect(url_for('error'))
@app.route('/viewprofile')
def profile():
email = request.cookies.get('email')
resp = make_response(render_template('profile.html',name = email))
return resp
if __name__ == "__main__":
app.run(debug = True)
<html>
<head>
<title>login</title>
</head>
<body>
<form method = "post" action = "http://localhost:5000/success">
<table>
<tr><td>Email</td><td><input type = 'email' name = 'email'></td></tr>
<tr><td>Password</td><td><input type = 'password' name = 'pass'></td></tr>
<tr><td><input type = "submit" value = "Submit"></td></tr>
</table>
</form>
</body>
</html>
<html>
<head>
<title>success</title>
</head>
<body>
<h2>Login successful</h2>
<a href="/viewprofile">View Profile</a>
</body>
</html>
<html>
<head>
<title>profile</title>
</head>
<body>
<h3>Hi, {{name}}</h3>
</body>
</html>
Session[variable-name] = value
session.pop(variable-name, none)
from flask import *
app = Flask(__name__)
app.secret_key = "ayush"
@app.route('/')
def home():
return render_template("home.html")
@app.route('/login')
def login():
return render_template("login.html")
@app.route('/success',methods = ["POST"])
def success():
if request.method == "POST":
session['email']=request.form['email']
return render_template('success.html')
@app.route('/logout')
def logout():
if 'email' in session:
session.pop('email',None)
return render_template('logout.html');
else:
return '<p>user already logged out</p>'
@app.route('/profile')
def profile():
if 'email' in session:
email = session['email']
return render_template('profile.html',name=email)
else:
return '<p>Please login first</p>'
if __name__ == '__main__':
app.run(debug = True)
<html>
<head>
<title>login</title>
</head>
<body>
<form method = "post" action = "http://localhost:5000/success">
<table>
<tr><td>Email</td><td><input type = 'email' name = 'email'></td></tr>
<tr><td>Password</td><td><input type = 'password' name = 'pass'></td></tr>
<tr><td><input type = "submit" value = "Submit"></td></tr>
</table>
</form>
</body>
</html>
<html>
<head>
<title>home</title>
</head>
<body>
<h3>Welcome to the website</h3>
<a href = "/login">login</a><br>
<a href = "/profile">view profile</a><br>
<a href = "/logout">Log out</a><br>
</body>
</html>
<html>
<head>
<title>success</title>
</head>
<body>
<h2>Login successful</h2>
<a href="/profile">View Profile</a>
</body>
</html>
<html>
<head>
<title>logout</title>
</head>
<body>
<p>logout successful, click <a href="/login">here</a> to login again</p>
</body>
</html>
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World'
if __name__ == '__main__':
app.run(debug = True)
app.route('/about')
def home():
return render_template('about.html')
@app.route('/contact')
def home():
return render_template('contact.html')
#create error handler for pages
#Invalid URL
@app.errorhandler(404)
def page_not_found(e):
return render_template("404.html"), 404
#Invalid URL
@app.errorhandler(500)
def internal_server_error(e):
return render_template("500.html"), 500
from flask import Flask, request, jsonify, render_template
python app.py
npm i react-router-dom
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
<Router>
<Routes>
<Route path="/" element={<Home />}/>
<Route path="" element={<Singlemovie />}/>
<Route path="*" element={<Errorpage />}/>
</Routes>
</Router>
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
<Router>
<Routes>
<Route path="/" element={<Home />}>
<Route path="about" element={<About />} />
<Route path="contact" element={<Contact />} />
<Route path="*" element={<Errorpage />} />
</Route>
</Routes>
</Router>
add outlet in parent route in above ex: home.js
import { Outlet } from 'react-router-dom'
<Outlet/>
import { useNavigate } from 'react-router-dom'
<button onClick={()=>{navigate(-1);}}>Go back</button>
According to the definition in React Router doc, useParams returns: an object of key/value pairs of URL parameters. Use it to access match.params of the current route
import { useParams } from 'react-router-dom'
const { id }=useParams();
React Context is a way to manage state globally.
It can be used together with the useState Hook to share state between deeply nested components more easily than with useState alone.
Context provides a way to pass data or state through the component tree without having to pass props down manually through each nested component. It is designed to share data that can be considered as global data for
a tree of React components, such as the current authenticated user or theme(e.g. color, paddings, margins, font-sizes).
Context API uses Context. Provider and Context. Consumer Components pass down the data but it is very cumbersome to write the long functional code to use this Context API. So useContext hook helps to make the code
more readable, less verbose and removes the need to introduce Consumer Component. The useContext hook is the new addition in React 16.8.
import React, { useContext } from "react";
For Create context value
const AppContext = React.createContext();
For set provider value
return <AppContext.Provider value="soham">{children}</AppContext.Provider>
For access value
const auth = useContext(AuthContext);
add appprovider in index.js
<AppProvider> </AppProvider>
function Avatar(props) {
let person = props.person;
let size = props.size;
// ...
}
function Avatar({ person, size }) {
// ...
}
const [state, setState] = useState(initialState)
const [statebtn, setbtn] = useState("Enable dark mode");
const [mode, setMode] = useState({
color: "black",
backcolor: "white",
});
const toogle = () => {
if (mode.color === "black") {
setMode({
color: "white",
backgroundColor: "black",
});
setbtn("Enable light mode");
} else {
setMode({
color: "black",
backgroundColor: "white",
});
setbtn("Enable dark mode");
}
};