Friday, December 6, 2024

MAD2-preparation

 Explain the significance of fs_uniquifier in your project (if applicable)?

fs_uniquifier is typically used for generating unique identifiers for resources

 fs_uniquifier = db.Column(db.String(255), unique=True, nullable=False)#Unique identifier for Flask Security
  • Since the fs_uniquifier is stored as part of the user record in the database, revoking a token simply involves changing its value.
  • It eliminates the need to maintain a separate database table for token invalidation, simplifying implementation.
  • When Flask-Security generates or verifies tokens, it automatically uses the fs_uniquifier.

     Where fs_uniquifier is Useful

    • Password Resets: Changing the fs_uniquifier during a password reset invalidates any prior reset or login tokens.
    • Account Takeovers: In case of suspicious activity, regenerating the fs_uniquifier revokes all active tokens for the account.
    • Email Change or Deletion: Updating the fs_uniquifier ensures no token tied to the old email or user account remains valid.
      fs_uniquifier adds an essential layer of security to ensure that tokens are managed effectively.
    What would you do if you had to change colors for the buttons, navbar, or text in your app?Update Styles in Vue.js Components

    If specific components use inline or scoped styles:

    • Use Vue's :style binding to dynamically change styles based on state or prop
    • 1.Update CSS Directly

      • Define your styles in a single CSS file and update colors as needed.

    • .navbar {
    •     background-color: #3498db; 
    •     color: white;
    • }

    • .button-primary {
    •     background-color: #2ecc71; 
    •     color: white;
    • }

    • .button-primary:hover {
    •     background-color: #27ae60; 
    • }

    • .text {
    •     color: #333;
    • }

      2.Inline CSS in HTML

      If your app has a few elements and doesn’t use complex templates, use inline CSS directly in the HTML.

      • Example:
        <nav style="background-color: #3498db; color: white;"> Navbar </nav> <button style="background-color: #2ecc71; color: white;"> Click Me </button> <p style="color: #333;"> This is some text. </p>

      3.Use Classes for Reusability

      Instead of repeating inline styles, create simple CSS classes and assign them to elements.

      • Define styles in a CSS file:

        .navbar { background-color: #3498db; color: white; } .btn { background-color: #2ecc71; color: white; border: none; padding: 10px 20px; cursor: pointer; } .btn:hover { background-color: #27ae60; } .text-primary { color: #333; }

      Use HTML <style> Tag(inside head tag)

      For small apps, you can directly embed the CSS in the HTML file using the <style> tag:

      <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Simple Styles</title> <style> .navbar { background-color: #3498db; color: white; padding: 10px; } .btn { background-color: #2ecc71; color: white; border: none; padding: 10px 20px; cursor: pointer; } .btn:hover { background-color: #27ae60; } .text-primary { color: #333; } </style> </head> <body> <nav class="navbar">Navbar</nav> <button class="btn">Click Me</button> <p class="text-primary">This is some text.</p> </body> </html>
    How would you implement frontend validation in your app?

    Use HTML5 Built-in Validation

    HTML5 provides built-in form validation attributes, making it easy to enforce basic rules without writing JavaScript.

    Key Attributes:
    • required: Ensures the field is not left empty.
    • type="email,text,password": Checks for valid  format.
    • pattern: Allows custom regex patterns for validation (e.g., \d{6} for a 6-digit pincode).
    • min, max, maxlength, minlength: Enforces range and length constraints.
    <input type="email" id="email" name="email" required /> 
      <label for="pincode">Pincode:</label> 
      <input type="text" id="pincode" name="pincode" pattern="\d{6}" required />

    Add Custom Validation with JavaScript

    For more advanced or dynamic validation, use JavaScript.

    Frontend validation can be implemented using JavaScript by checking form inputs before submitting, such as verifying required fields, patterns, and lengths

    <form id="serviceRequestForm">

        <label for="email">Email:</label>

        <input type="email" id="email" name="email" required />

        <label for="pincode">Pincode:</label>

        <input type="text" id="pincode" name="pincode" required />

        <span id="errorMessage" style="color: red; display: none;">Invalid input</span>

        <button type="submit">Submit</button>

    </form>


    <script>

        document.getElementById('serviceRequestForm').addEventListener('submit', function (e) {

            const email = document.getElementById('email').value;

            const pincode = document.getElementById('pincode').value;

            const errorMessage = document.getElementById('errorMessage');


            // Validate email

            if (!email.includes('@')) {

                e.preventDefault();

                errorMessage.textContent = 'Invalid email address.';

                errorMessage.style.display = 'block';

                return;

            }


            // Validate pincode (must be 6 digits)

            if (!/^\d{6}$/.test(pincode)) {

                e.preventDefault();

                errorMessage.textContent = 'Pincode must be a 6-digit number.';

                errorMessage.style.display = 'block';

                return;

            }


            // If all validations pass, hide the error message

            errorMessage.style.display = 'none';

        });

    </script>

    Even with frontend validation, always validate on the backend to ensure security and prevent tampering.

    Explain the Directory structure of your application?

    Explain your directory structure , For me this is 

    For Backend:

    Application folder :Is created for the backend files,Is the main package for the app

    1.__init__.py:

    • Initializes the Flask app, extensions (SQLAlchemy, Flask-JWT-Extended, Flask-Migrate, etc.),Packages and Blueprints.
    2.models.py:
    It represents the DB models represnts the structure of data base tables using ORM (Object relational Mapper) in SQLAlchemy
    • Defines database Schema and data tables using SQLAlchemy ORM 
    3.resources.py:
    It defines the flask restfull API's ,Implement CRUD operations on resources and create API instance
    which is used to create RESTful APIs in Flask.
    api = Api(prefix='/api')
  • Api:

    • This is a class provided by Flask-RESTful to simplify the creation of RESTful APIs.
    • It helps manage API resources and routing.
  • prefix='/api':

    • The prefix argument sets a base URL for all API routes registered with this Api instance.
    • This means every route added to the api instance will automatically have /api as a prefix.
  • 4.instances.py
    Is used to create a cache instance.The Cache class from flask_caching is used to integrate caching functionality into a Flask application.
    Caching helps store frequently accessed data temporarily to improve the performance and efficiency of an application by reducing database queries or computational overhead.

    from flask_caching import Cache cache = Cache()
    5.sce.py
    Is used to implement the flask security.

    "from flask_security import SQLAlchemyUserDatastore
    from .models import db, User, Role

    datastore = SQLAlchemyUserDatastore(db, User, Role)"
    This above code is used to create an instance of SQLALchemyUserDatastore is a class,
    it acts as an interface between the flask security and the data base ,is used to mange the user data and roles in a Flask application.

    SQLAlchemyUserDatastore:

    • This class is part of Flask-Security and acts as an interface to manage users and roles stored in a database.
    • It connects the application's User and Role models to Flask-Security's authentication and authorization.

    After defining the datastore, it can be used to:

    • Add users and assign roles.
    • Query for users and roles.
    • Perform role-based access control checks.
    6.Views.py:

    It contains the view functions to handle the http requests and return the json responses.
    It is a controller part of the MVC architecture ,It acts as interface between the model and view.

    Responsibilities of views.py

    1. Handling Requests: It processes incoming HTTP requests (e.g., GET, POST, PUT, DELETE).
    2. Interacting with Models: Fetches or manipulates data from the database using models.
    3. Returning Responses:
      • JSON responses for APIs.
      • Rendered templates for web pages.
    7.Static:
    In a Flask application, the static folder is used to store static files such as CSS, JavaScript, images, fonts, components or other assets that do not change dynamically.
    Flask serves these files directly to the client when requested.

    8.app.py:
    This is the entry point of your app ,It intializes the app and configure the app.
    It starts the flask server

    9.Config.py:

    The Config.py file in a Flask application is used to centralize and organize configuration settings for the app. It ensures flexibility, scalability, and clean separation of environment-specific settings like database URLs, debug modes, secret keys, and other critical configurations.

    Purpose of Config.py

    1. Centralized Configuration: Stores all app settings in one place, making them easier to manage.
    2. Environment-Specific Configurations: Allows you to define separate settings for different environments, such as development, testing, and production.
    3. Security: Safeguards sensitive information like secret keys and salts by storing them securely.
    10.VirtualEnvironment:
    where project specific dependencies and required libraries are installed.

    11.database.db:
    Is a sqlite database for storing the application data.

    12.intial_data.py:
    It is used to set up the useful data for default users and roles

    What is SQLAlchemy?

    SQLAlchemy is a popular Python SQL toolkit , It provides a flexible way to interact with databases in Python, allowing developers to write database queries and manage schemas using Python code instead of raw SQL.

    Key Features of SQLAlchemy

    1.Allows you to write raw SQL-like queries in a structured way using Python.

    2.ORM (Object-Relational Mapper):

    • Maps Python objects (classes) to database tables.
    • Enables developers to interact with the database using Python objects instead of SQL queries.
    3.It suppors Different DataBases:
  • Supports a wide variety of relational databases like SQLite, PostgreSQL, MySQL, Oracle, and Microsoft SQL Server.
  • Switching databases requires minimal changes to the code.
    4.Session Management:
    • Manages database connections and transactions automatically.

    What  Object-Relational Mapping (ORM) ?
     Is a library
    An ORM (Object-Relational Mapping) is a programming technique that allows you to interact with a relational database using objects. It bridges the gap between the object-oriented world (Python, Java, etc.) and the relational world (SQL databases).

    How ORM Works

    1. Mapping:

      • Classes in your application are mapped to tables in the database.
      • Each class represents a table, and each instance of the class represents a row in the table.
    2. CRUD Operations:

      • Instead of writing raw SQL for Create, Read, Update, Delete operations, you work directly with objects.
      • The ORM translates these operations into SQL queries 
    3. Relationships:

      • Relationships between tables (one-to-many, many-to-many, etc.) are represented as relationships between objects.







    No comments:

    Post a Comment

    Mangerial Economics Quiz1 solutions Guide

    Mangerial Economics Quiz1 solutions Guide  solutions watch on you tube channel