CITS3403 Notes




cd -

Written by Jeremy Butson 2024 based on UWA CITS3403 Lecture Notes

Introduction

==================================

Brief History:

How the Internet Works:

Client-Server Architecture:

HTML

=====================================

Hyper Text Markup Language:

Basic Syntax:

<!DOCTYPE html>
<html>
<head>
    <title>Page Title</title>
</head>

<body>
    <h1>Heading</h1>
    <p>Paragraph</p>
    <table border="1" cellpadding="1">...</table>
    <!-----COMMENT------>
</body>
</html>

Font Styles and Sizes:

<b> for bold </b>
<i> italics </i>
<big> larger </big>
<small> smaller </small>
<tt> monospace </tt>

&amp, &lt, &gt, &quot, &apos, &frac34, &deg, &nbsp

Inserting Images:

<img src="image.png" alt="image text" style="width:300px;height:200px;">

<a href="Link">to page</a>

Lists:

<h3>Shopping List:</h3>
    <ul>
        <li>Milk</li>
        <li>Eggs</li>
    </ul>

Tables:

<table style="width:100%" border="border">  
  <tr>  
    <th>Company</th>  
    <th>Contact</th>  
    <th>Country</th>  
  </tr>  
  <tr>  
    <td>Alfreds Futterkiste</td>  
    <td>Maria Anders</td>  
    <td>Germany</td>  
  </tr>  
  <tr>  
    <td>Centro comercial Moctezuma</td>  
    <td>Francisco Chang</td>  
    <td>Mexico</td>  
  </tr>  
</table>

![[Pasted image 20240226104914.png]]

Layout in HTML5:

![[Pasted image 20240226105135.png]]

Forms:

<form action="/action_page.php">
    <fieldset>
        <legend>Personal Information:</legend>
        First Name:<br>
        <input type="text" name="firstname" value="mickey">
        <br>
        Last Name:<br>
        <input type="text" name="lastname" value="mouse">
        <br><br>
        <input type="submit" value"Submit">
    </fieldset>
</form>

CSS

=====================================

CSS or Cascading Style Sheets is:

body {
    backgroudn-color: blue;
    color: white;
    text-align: center;
    font-family: verdana;
    font-size: 20px;
}

Advantages of CSS:

Why Cascading?

Inline:

<p style="color:yellow">styled text</p>

Document:

<style>
    p {
        color:yellow;
    }
</style>

External:

<link rel="stylesheet" type="text/css" href="style.css"></link>

Selectors:

*{...} UNIVERSAL
p{...} ELEMENT
.important{...} CLASS
.important:hover{...} PSEUDO-CLASS
important::first-letter{...} PSEUDO-ELEMENT
s1,s2,s3{...} GROUP

Property Groups:

Bootstrap

=================================

A [[3. CSS|CSS]] framework. To include in your page, you can download and host the code yourself, or reference a Content Delivery Network in the header of your webpage. Bootstrap consists of a CSS, JavaScript and optional theme files.

<head>
    <link rel="stylesheet" href="bootstrapfile.css">
    <script src="jquery.js"></script>
    <script src="bootstrapfile.js"></script>
</head>

Grid System:

  • fills the whole screen
  • columns can be nested, so a span of eight columns can be divided into 12
  • Tables:

    <tbody>
        <tr>
            <td>First column, first row</td>
            ...
    </tbody>
    

    More Info (Yay I love lecturers):

    JavaScript

    ===================================

    What is JavaScript?

    Events:

    Executing JS:

    JS on the Browser:

    JS I/O:

    Basics of JavaScript

    Variables:

    let z = x + y;
    const x = 6;
    var stopFlag = true;
    zz = z;
    

    Syntax:

    // single line comment

    /*
    multiple
    line
    comment
    */
    

    Primitives and Objects:

    Numbers:

    Strings:

    charAt(number_value); //returns character at spot
    indexOf("a"); //returns index of character
    substring(0, 3); //returns substring from position 0 to 3
    toLowerCase();
    toUpperCase();
    toString(1234); //returns string of the number
    "con" + "cat" = "concat";
    

    Booleans:

    Loops:

    let triangle = 0;
    for (let i = 1; i <= 3; i++) {
        triangle += i;
    }
    //triangle = 6
    

    Arrays:

    var index;
    var fruits = ["banana", "orange"];
    for (index = 0; index < fruits.length; index++){
        text += fruits[index];
    }
    
    
    let a = Array(10);
    //makes an array of length 10
    let b = Array();
    //creates an empty array
    let c = Array(10, 2, "three", "four");
    //create array of length 4 with the 4 elements contained
    

    ![[Pasted image 20240314152122.png]]

    Functions

    function <name> (<parameters>) {
        <statements>
    }
    
    function findMax(){
        let max = -infinity;
        for (let i = 0; i < arguments.length; i++){
            if (arguments[i]  > max){
                max = arguments[i];
            }
        }
        return max;
    }
    
    findMax(4,5,6);
    

    Scopes

    Inner Functions:

    Objects

        function Person(first, last, age, eye) {
            this.firstName = first;
            this.lastName = last;
            this.age = age;
            this.eyeColor = eye;
        }
        
        var myFather = new Person("John", "Doe", 50, "blue");
    

    DOM

    ===================================

    The Document Object Model

    The BOM Execution Environment

    Accessing Elements

    `x.getElementsByTagName("p")

    DOM Modification

    insertBefore
    replaceChild
    removeChild
    appendChild
    open()
    close()
    write()
    writeIn()
    

    BOM Functions

    window.navigator object contains information about browser:

    appCodeName //code name of browser
    appName //name of browser
    appVersion //version of browser
    cookieEnabled //determines whether cookies are enabled
    geolocation //returns a geolocation object, used to find user's positio
    language 
    onLine //determines whether the browser is online
    platform 
    product //returns engine name
    userAgent
    

    window.history contains methods for moving backwards and forwards:

    back()
    forward()
    go()
    length
    

    Client-Side JavaScript

    ===================================

    Event-Driven Programming:

    onblur
    onchange
    onclick
    ondblclick
    onfocus
    onkeydown
    onkeypress
    onkeyup
    onload
    onmousedown
    onmousemove
    onmouseout
    onmouseover
    onmouseup
    onreset
    onselect
    onsubmit
    onunload
    
    button = document.getElementsById("myButton");
    button.addEventListener("click", myHandler, false);
    #where myHandler is the code and there is a myButton in the HTML
    #false means by default it "bubbles up"
    

    What is J-Query?

    <script src = "https://code.jquery.com/jquery-3.7.1.min.js"></script>
    
    $("p").click(() => {
        $(this).slideDown("slow");
    })
    $("p").on( {
        mouseenter:function(){
            $(this).css("background-color", "lightgray");
        },
        mouseleave:function(){
        
        },
    });
    

    HTTP and AJAX

    ===================================

    HTTP Requests

    Structure of HTTP Requests and Responses

    //GET requests
    xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true); //true is whether its asynchronous
    xhttp.send();
    
    //POST requests
    xhttp.open("POST", "ajax_test.asp", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("fname=Henry&lname=Ford");
    
    //PUT request to replace data on server
    
    //readystate is the progress of req, onreadystatechange is a callback func
    function loadDoc() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readystate == 4 && this.status == 200) { //status == OK
                document.getElementById("demo").innerHRML = this.responseText;
            }
        };
        xhttp.open("GET", "ajax_info.txt", true);
        xhttp.send();
    }
    

    Asynchronous Communication

    XMLHttpRequests

    jQuery and HTTP Requests

    $("button").click(function() {
        $.post("demo_test_post.asp", fucntion(data, status){
            alert("Data: " + data + "\nStatus: " + status);
        });
    });
    
    $("button").click(function() {
        $.post("demo_test_post.asp",
        {
            name: "Donald Duck",
            city: "Duckburg"
        },
        function(data, status) {
            alert("Data: " + data + "\nStatus: " + status);
        });
    });
    

    AJAX

    Flask and Server-Side Rendering

    ===================================

    A web server is simply a program running on a computer connected to the internet that responds to requests from other computers on the network. This is also referred to as back-end development (so now full-stack development).

    Different Stacks

    Flask

    from flask import flask
    app = Flask(__name__)
    @app.route("/")     #annotate with this, in this case top level
    def hello():
        return "Hello World"
    if __name__ == "__main__":
        app.run()
    
    #app/__init__.py
    from flask import flask
    app = Flask(__name__)
    from app import routes
    
    #app/routes.py
    from app import app
    @app.route("/")              #this is an endpoint
    @app.route("/index")         #can be multiple endoints
    def index():
        return "Hello World"
    
    #microblog.py
    from app import app
    

    Endpoints

    @app.route("/login", methods=['GET', 'POST'])
    def login():
        if request.method == 'POST':
            do_the_login()
        else:
            show_the_login_form()
    

    Server-side vs Client-side Rendering

    Flask Server-side

    from app import app
    @app.route("/")              #this is an endpoint
    @app.route("/index")         #can be multiple endoints
    def index():
        user = ("username" : "Miguel")
        return '''
    <html>
        ...
    </html>'''
    
    <!--app/templates/index.html-->
    <html>
        <head>
            <title>{{title}} - Microblogs</title>
        </head>
        <body>
            <h1> Hello, {{user.username}}</h1>
        </body>
    </html>
    
    #app/routes.py
    from flask import render_template
    from app import app
    
    @app.route("/")
    @app.route("/index")
    def index():
        user = {'username': 'Miguel'}
        return render_template("index.html", title = "Home", user = user)
    

    Running in VSCode

    > set FLASK_APP=main.py > $env:FLASK_APP = "main.py" > flask run ``

    Flask and Client-Side Rendering

    ===================================

    Single Page Applications (SPA)

    Client Side Rendering w/ Web Sockets

    Databases

    ===================================

    Architecture

    Model-view-controller Pattern (MVC)

    Mock-ups of views

    Implementing Models

    Relational Databases

    Database Management System (SQLite)

    sqlite3 app.db #creates database
    
    CREATE TABLE contact_groups (
        contact_id integer,
        group_id integer,
        PRIMARY KEY (contact_id, group_id),
        FOREIGN KEY (contact_id) REFERENCES contacts(contact_id)
        ON DELETE CASCADE ON UPDATE NO ACTION
    );
    
    .database #shwos file path
    .table #lists tables
    .schema tableName #shows the schema for a table
    .indexes
    .exit
    
    class Student(db.model):
        uwa_id = db.Column(db.String(8), primary_key = True)
        name = db.Column(db.String(120), nullable = False)
        group_id = db.Column(db.Integer, db.ForeignKey("group.group_id"),                        nullable = True)
        group = db.relationship("Group", back_populates = "students")
    

    Database Migration in Flask

    Security

    ===================================

    Breakdown

    Public Key Encryption

    Hashing

    Session-based User Authentication

    Attacks on Session Based Protocols

    Impersonation Attack

    SSL Certificates

    Man-in-the-middle Attack

    Encrypted Sessions With SSL

    HTTPS

    Cross-Site Request Forgery (CRSF) Attack

    Token-Based User Authentication

    Downsides of Session-Based Authentication

    Tokens and JWT

    Advantages of Tokens

    Testing

    ===================================

    Many various ways; in order of effectiveness:

    Types of Tests

    Unit Tests

    The purpose of a unit test is to test an individual function, using 2 to 5 per function. Properties include:

    The Python unittest Module

    Provides several classes and functions:

    Creating a Mock DB in Flask

    SQLALCHEMY_DATABASE_URI = "sqlite:///:memory" creates a non-persistent database in memory rather than as a file on disk. Config class holds the options shared between all configurations, subclasses hold options specific to a particular configuration:

    class Config:
        SQL_ALCHEMY_TRACK_MODIFICATIONS = False
        SECRET_KEY = os.environ.get("FLASK_SECRET_KEY")
    class DeploymentConfig(Config):
        SQLALCHEMY_DATABASE_URI = "sqlite:///" + os.path.join(basedir, 'test.db')
    class TestConfig(Config):
        SQLALCHEMY_DATABASE_URI = "sqlite:///:memory"
        TESTING = True
    

    Writing Unit Tests

    The name MUST begin with test and use assert methods to define whether it passes.

    def test_password_hashing(self):
        s = Student.query.get("01234587")
        s.set_password("bubbles")
        self.assertTrue(s.check_password("bubbles"))
        self.assertFalse(s.check_password("rumbles"))
    

    System Tests

    Integrate real hardware platforms and test their behaviour. In the web, this means testing the behaviour of how the application works in a browser. Selenium is one possible program that can be used to automate browsers to run test cases; two variations:

    RESTful APIs

    ===================================

    An Application Programming Interface (API) is a means to provide the logic and data structures of your app as a service to other developers so they can embed the functionality into different applications and customise the UI

    The most common API design is based on REST APIs, client-side page rendering uses what are essentially REST APIs designed for private rather than public use

    Principles of REST

    The 6 Characteristics of REST

    1. Client-server model: sets out different roles of the client and server in the system, should be clearly differentiated as separate processes, the interface is through HTTP and the transport through TCP/IP
    2. Layered System: there does not need to be a direct link between the client and the server, the client does not need to distinguish between the actual server and an intermediary, and the server does not need to know whether it is communicating directly with the client
    3. Cache: states that it is acceptable for the client or intermediaries to cache responses to requests and serve these without going back to the server every time. This allows for efficient operations of the web. Anything encrypted cannot be cached by an intermediary, saves reloading the same static files.
    4. Code on Demand (Optional): can provide executable code in responses to a client
    5. Stateless: servers should not maintain any memory of prior transactions and every request from clients should include sufficient context for the server to satisfy the request
    6. Uniform Interface: clients in principle do not need to be specifically designed to consume a server

    Designing a REST API

    REST in Flask

    myapp\
        app\
            __init__.py
            FORMS.py
            models.py
            controllers.py
            routes.py
            templates\
                base.html
                ...
            static\
                bootstrap.css
                ...
            api\
                __init__.py              //initialise the api
                auth.py                  //handle token based auth
                models_api.py            //handle api routes for each model
                token_api.py             //handles tokens
    

    Deployment

    ===================================

    Upgrading to Production-Grade Tools

    Why Replace SQLite?

    Why Replace Flask Server?

    Deploying the Website

    Via Linux VM

    Via Your Own Physical Server

    Via Cloud Containers