Flask

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.

Flask

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.

  1. Install virtualenv for development environment
    virtualenv
    virtualenv is considered as the virtual python environment builder which is used to create the multiple python virtual environment side by side.
                    
                        pip install virtualenv
                    
                
  2. setup project
                                            
                                            mkdir newproj
                                            cd newproj
                                            virtualenv venv
                                            
            
                
                    virtualenv venv
                
            
  3. activate virtualenv
                                             
                                            venv\scripts\activate
                                            
            
  4. install flask
        
            pip install Flask
    
    
  5. create app.py and add
    app.py
    To build the python web application, we need to import the Flask module.

    An object of the Flask class is considered as the WSGI application. We need to pass the name of the current module, i.e. __name__ as the argument into the Flask constructor.
        
            from flask import Flask
            app = Flask(__name__)
            
            @app.route('/')
            def hello_world():
               return 'Hello World'
            
            if __name__ == '__main__':
                app.run(debug = True)
    
    
  6. route() function
    route() function
    The route() function of the Flask class defines the URL mapping of the associated function.

    It accepts the following parameters.
    rule: It represents the URL binding with the function.

    options: It represents the list of parameters to be associated with the rule object
        
            app.route(rule, options)  
    
    
  7. app.run()
    app.run()
    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
    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)
    
    
  8. Debug mode
    Debug mode
    A Flask application is started by calling the run() method. However, while the application is under development, it should be restarted manually for each change in the code. To avoid this inconvenience, enable debug support. The server will then reload itself if the code changes. It will also provide a useful debugger to track the errors if any, in the application.

    The Debug mode is enabled by setting the debug property of the application object to True before running or passing the debug parameter to the run() method.
        
            app.run(debug = True)
    
    
  9. Flask App routing
    Flask App routing
    App routing is used to map the specific URL with the associated function that is intended to perform some task. It is used to access some particular page like Flask Tutorial in the web application.

    In our first application, the URL ('/') is associated with the home function that returns a particular string displayed on the web page.

    In other words, we can say that if we visit the particular URL mapped to some particular function, the output of that function is rendered on the browser's screen.
        
            @app.route('/home')  
    def home():  
        return "hello, welcome to our website";  
    
    
  10. converter in routing
    converter in routing
    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

    The following converters are used to convert the default string type to the associated data type.

    string: default
    int: used to convert the string to the integer
    float: used to convert the string to the float.
    path: It can accept the slashes given in the URL.
        
            @app.route('/home/<int:age>')  
                def home(age):  
                    return "Age = %d"%age;  
    
    
  11. The add_url_rule() function
    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.

    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.
        
            add_url_rule(<url rule>, <endpoint>, <view function>)    
    
    
        
        def about():  
            return "This is about page";  
        app.add_url_rule("/about","about",about)    
    
    
  12. Flask URL Building
    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.

    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

    It avoids hard coding of the URLs.
    We can change the URLs dynamically instead of remembering the manually changed hard-coded URLs.
    URL building handles the escaping of special characters and Unicode data transparently.
    The generated paths are always absolute, avoiding unexpected behavior of relative paths in browsers.
    If your application is placed outside the URL root, for example, in /myapplication instead of /, url_for() properly handles that for you.

        
            @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'))  
    
    
  13. Flask HTTP methods( GET() )
    Flask HTTP methods( GET() )
    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.



    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.

    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.


    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.

                                        
                                            <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>  
                                        
                                        
                                            
                                               
                                            
                                            
  14. Flask Templates
    Flask Templates
    flask facilitates us to return the response in the form of HTML templates.The following flask script contains a view function, i.e., the message() which is associated with the URL '/'.


    Rendering external HTML files

    Flask facilitates us to render the external HTML file instead of hardcoding the HTML in 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 function.

                                            
                                                @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')    
                                            
                                            
  15. Delimiters
    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

    a) {% ... %} for statements
    b) {{ ... }} for expressions to print to the template output
    c) {# ... #} for the comments that are not included in the template output
    d) # ... ## for line statements

                                        
                                            <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)  
                                        
                                        
  16. Embedding Python statements in HTML
    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.

                                        
                                            <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)  
                                        
                                        
  17. Referring Static files in HTML
        
            <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    
    
  18. Flask Request Object
    Flask Request Object
    In the client-server architecture, the request object contains all the data that is sent from the client to the server. As we have already discussed in the tutorial, we can retrieve the data at the server side using the HTTP methods.
    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).



    Form data retrieval on the template
    In the following example, the / URL renders a web page customer.html that contains a form which is used to take the customer details as the input from the customer.

    The data filled in this form is posted to the /success URL which triggers the print_data() function. The print_data() function collects all the data from the request object and renders the result_data.html file which shows all the data on the web page.

                                        
                                            <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>   
                                        
                                        
  19. Flask Cookies
    Flask Cookies
    The cookies are stored in the form of text files on the client's machine. Cookies are used to track the user's activities on the web and reflect some suggestions according to the user's choices to enhance the user's experience.

    Cookies are set by the server on the client's machine which will be associated with the client's request to that particular server in all future transactions until the lifetime of the cookie expires or it is deleted by the specific web page on the server.

    In flask, the cookies are associated with the Request object as the dictionary object of all the cookie variables and their values transmitted by the client. Flask facilitates us to specify the expiry time, path, and the domain name of the website.

    In Flask, the cookies are set on the response object by using the set_cookie() method on the response object. The response object can be formed by using the make_response() method in the view function.

                                        
                                            response.setCookie(<title>, <content>, <expiry time>) 
                                        
                                        

    read the cookies

                                            
                                                request.cookies.get(<title>)  
                                            
                                            

                                        
                                            @app.route('/cookie')  
    def cookie():  
        res = make_response("<h1>cookie is set</h1>")  
        res.set_cookie('foo','bar')  
        return res   
                                        
                                        
  20. Login application in Flask
    Login application in Flask
    Here, we will create a login application in the flask where a login page (login.html) is shown to the user which prompts to enter the email and password. If the password is "jtp", then the application will redirect the user to the success page (success.html) where the message and a link to the profile (profile.html) is given otherwise it will redirect the user to the error page.

    The controller python flask script (login.py) controls the behaviour of the application. It contains the view functions for the various cases. The email of the user is stored on the browser in the form of the cookie. If the password entered by the user is "jtp", then the application stores the email id of the user on the browser as the cookie which is later read in the profile page to show some message to the user.

                                        
                                            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>     
                                        
                                        
  21. Flask Session
    Flask Session
    The concept of a session is very much similar to that of a cookie. However, 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.

                                        
                                            Session[variable-name] = value   
                                        
                                        

                                        
                                            session.pop(variable-name, none)  
                                        
                                        
  22. Login application in Flask with session
    Login application in Flask with session
    Here, we will create a login application in the flask where a login page (login.html) is shown to the user which prompts to enter the email and password. If the password is "jtp", then the application will redirect the user to the success page (success.html) where the message and a link to the profile (profile.html) is given otherwise it will redirect the user to the error page.

    The controller python flask script (login.py) controls the behaviour of the application. It contains the view functions for the various cases. The email of the user is stored on the browser in the form of the cookie. If the password entered by the user is "jtp", then the application stores the email id of the user on the browser as the cookie which is later read in the profile page to show some message to the user.

                                        
                                            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> 
                                        
                                        
  23. app.py
        
            from flask import Flask
            app = Flask(__name__)
            
            @app.route('/')
            def hello_world():
               return 'Hello World'
            
            if __name__ == '__main__':
                app.run(debug = True)
    
    
  24. add about , contact , 404 , 500
        
            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
            
            
    
    
  25. import request , jsonify,render_template
        
            from flask import Flask, request, jsonify, render_template
    
    
  26. run server
        
          python app.py
    
    
  27. import react-router-dom
        
          npm i react-router-dom
    
    
  28. import router and routes
        
          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>
    
    
  29. create nested routes
        
          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/>
    
    
  30. create go back button feature
              
                import { useNavigate } from 'react-router-dom'
            
            
              
                <button onClick={()=>{navigate(-1);}}>Go back</button>
            
            
  31. for fetch id from link(route)
    useParams();

    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

    • What does it mean in plain English?
    • It means whatever you set up in useParams(ex: title), your params have to match with the < Route path='/path/:title' > .

              
                import { useParams } from 'react-router-dom'
          
          
        
          const { id }=useParams();
    
    
  32. React useContext Hook
    React useContext Hook

    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>
    
    
  33. create props

                      
                        function Avatar(props) {
                          let person = props.person;
                          let size = props.size;
                          // ...
                        }
                      
                      
                      
                        function Avatar({ person, size }) {
                          // ...
                        }
                      
                      
  34. useState is a React Hook that lets you add a state variable to your component.
              
                const [state, setState] = useState(initialState)
              
              
  35. Enable dark mode (create onClick toogle fuction in buuton and mode input to style)
              
                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");
                  }
                };