/Coursera-Backend-notes

Notes for 'Django for Everybody Specialization' provided by University of Michigen, 'Meta Back-End Developer Professional Certificate' provided by Meta on Coursera platform.

Primary LanguagePython

Coursera-Backend-Development-notes

Table of Contents

  1. Introduction to Backend Development
  2. Programming in Python
  3. Version Control
  4. Web Application Technologies and Django
  5. Building Web Applications in Django
  6. Django Features and Libraries
  7. Using JavaScript, JQuery, and JSON in Django

Introduction to Backend Development

  1. HTML, CSS
  2. UI framworks and libraries, Bootstrap
    • breakpoint
      • infix(indicate the breakpoint in Bootstrap CSS rules)
      • bootstrap modifiers(add a CSS class to change the visual style of components)
    • grid system
    • containers, row, col col-12/col-lg-6(different screen size)
    • cards
    • badge(can insert between span tag)
    • alert
    • bootstrap web
      bootstrap.min.css, bootstrap.min.js
  3. Into React
    • SAP(single application page)
    • Virtual DOM(Document Object Model)
    • component hierarchy

Programming in Python

  1. install Python/change python version
  2. type casting
  3. String
    • "I am a {major} student in {university}".format(major="Shawn", university="UofM")
    • "I am a {0} student in {1}".format("Shawn", "UofM")
    • "I am a {} student in {}".format("Shawn", "UofM")
  4. loop
    • for index, item in enumerate(func):
  5. data structure
    • list [], tuple ()
      • list can be modified(append, insert, pop), but tuple is immutable
    • set
      • is a collection with no duplicated
      • set is not a sequence, it doesn't contain order index, set can not search with index
    • dictionary
      • key:value
      for key, value in my_dict.items(): 
         print(str(key) + ":" + value)
      
    • args
      def sum(*args): 
         for x in args:
            sum += x
      sum(1, 3, 4, 6, 7)
      
    • kwargs
      def sum(**kwargs):
         for k, v in kwargs.items():
            sum += v
      sum(coffee:2.9, tea:1.6, sanwich:4.3)
      
  6. read/write file
    • with open(filename, "r") as file:
    • use 'with' operate file, otherwise need to use close
  7. 🥲 I got COVID this week and i have to suspend the studying. The fever made me feel headache, and sore throat felt like swallowing a blade down my throat, please protect yourself. TAKE CARE.
  8. recursion
    • reverse String
      • slice function(Using Indexing Syntax)
      # str[start:stop:step]
      temop_string = string[::-1]
      
      more string slice() details
      • recursion
      def reverse_str(str):
         if len(str) == 0:
            return str
         else:
            return reverse_str(str[1::]) + str[0]
      
  9. Map & filter
    • map() returns every item in an iterable, including 'None', 'False', etc.
    • same as map, but filter() only returns values if True
  10. comprehension
  11. Object Oriented Programming
    • almost same as Java
    • encapsulation, polymorphism, inheritance and abstraction
    • constructor
      def __init__(self, newData):
          self.data = newData
      
    • Inheritance and Multiple Inheritance
    • abstract
      from abc import ABC
      class abstractClass(ABC):
          pass
      
      if there is abstract method, then
      from abc import ABC, abstractmethod
      class abstractClass(ABC):
          @abstractmethod
          def someAbstractMethod(self):
             pass
      
    • override
    • refer to bank.py
  12. module
    • build-in
      import sys
      
    • not build-in
      import sys
      sys.path.insert(1, r"C:\Users\Madecraft Author\Programs\Workplace")
      import trial
      
    • others, such asfrom json import *
    • refer to jsongenerator.py
  13. web dev
    • full stack(Django)
    • microframework(Flask)
    • asynchronous
  14. testing
  15. test-driven development(TDD)

Version Control

  1. workflow
    • Continuous Integration
    • Continuous Delivery
    • Continuous Deployment
  2. bash
    • cd, Change Directory
    • ls - List command used for showing the content of a directory.
    • rm - Remove command used for removing a file or a directory
    • mv - Used to move files or folders to another location
    • touch - Allows creating of a new empty file or to upate a timestamp on a file
    • cp - Used to make a copy of a file or foldler
    • mkdir - Make a new directory
    • pwd - Print work directory, shows the current location in the shell
    • cat - Allows reading or concatenation of a file
    • less - Displays the contents of a file one page at a time.
    • grep - Global regular expression, allows for searching contents of files or folders
  3. pip
    • cat file.txt | wc -w
  4. redirection
  5. grep
  6. correct workflow
    • from the working directory to the staging area(git add), then to committed files(git commit), remote repository(git push)
  7. How to use simple git commands
    • login Github, gh auth login
    • if u want to clone repository, gh repo clone <YOUR USERNAME>/<REPOSITORY-NAME>
    • if repository is exist,
    • open terminal and find the location of the clone repository
    • git clone -b branch + urlLink
    • check if there is the file you need
    • create a new branch, git checkout -b yourNewBranchName, go back to main branch, git checkout main
    • check current branches, git status
    • change untracked file to tracked, add file in staging status, git add helloWorld.java / git add *
    • restore file from tracked to untracked, go back to last step, git restore --stage helloWorld.java
    • git commit -m "add helloWorld.java to main branch..."
    • git push -u origin yourBranchName
    • updated local content from remote repository, git pull

Web Application Technologies and Django

  1. Model-View-Controller
    • Model: The persistent data that we keep in the data store
    • View: Html, Css, etc. which makes up the look and feel of the application
    • Controller: The code that does the thinking and decision making
    • Which of the following files does Django consult first when it receives an incoming HTTP Request?
      • urls.py
  2. SQL summary
    • INSERT INTO Users (name, email) VALUES ('Kristina', 'kf@uofm.ca')
    • DELETE FROM Users WHERE email='ted@uofm.ca'
    • UPDATE Users SET name="Shawn" WHERE email='csev@uofm.ca'
    • SELECT * FROM Users
    • SELECT * FROM Users WHERE email='csev@uofm.ca'
    • SELECT * FROM Users ORDER BY email'
  3. Object Relational Mapping
  4. CRUD in the ORM
    • INSERT INTO Users (name, email) VALUES ('Kristina', 'kf@uofm.ca')
      is same as:
      u = User(name='Kristina', email='kf@uofm.ca')
      u.save()
      
    • SELECT * FROM Users
      is same as:
      User.objects.values()
      
    • SELECT * FROM Users WHERE email='csev@uofm.ca'
      is same as:
      User.objects.filter(email='csev@uofm.ca').values
      
    • UPDATE Users SET name="Shawn" WHERE email='csev@uofm.ca'
      is same as:
      User.objects.filter(email='csev@uofm.ca').update(name='Shawn')
      
    • SELECT * FROM Users ORDER BY email'
      is same as:
      User.objects.values().order_by('email')
      
  5. If db gets messed up (if you screw up)
    • cd ~/django_projects/mysite/polls/
    • rm *migrations/00*
    • rm db.sqlite3
    • workon django3 # as needed
    • python manage.py check
    • python manage.py makemigrations
    • python manage.py migrate
    • python manage.py check
    • python manage.py createsuperuser
  6. What does the "python manage.py migrate" command do?
    • Builds/updates the database structure for the project
  7. What is the purpose of the models.py file?
    • To define the shape of the data objects to be stored in a database
  8. three-step guide to making model changes:
    • Change your models (in models.py).
    • Run python manage.py makemigrations to create migrations for those changes
    • Run python manage.py migrate to apply those changes to the database.
  9. there are too many contents, read django document is a better way to study it

Building Web Applications in Django

  1. views
    • function based views
      # url:
      # http://samples.dj4e.com/views/rest/41
      
      # url.py:
      urlpatterns = [
         path('rest/<int:guess>', view.rest),
      ]
      
      # response:
      from django.http import HttpResponse
      from django.utils.html import escape
      
      def rest(request, guess):
         response = """<html><body><p>"""+escape(guess)+"""</p></body></html>"""
         return HttpResponse(response)
      
    • class based views
      # url:
      # http://samples.dj4e.com/views/remain/xxr123-33-nbnb
      
      # url.py:
      urlpatterns = [
         path('remain/<slug:guess>', views.RestMainView.as_view()),
      ]
      
      # response:
      from django.http import HttpResponse
      from django.utils.html import escape
      from django.views import View
      
      Class RestMainView(View):
         def get(self, request, guess):
            response = """<html><body><p>"""+escape(guess)+"""</p></body></html>"""
            return HttpResponse(response)
      
  2. there are too many contents, read django document is a better way to study it
  3. render
    from django.shortcuts import render
    from .models import Question
    
    def index(request):
       latest_question_list = Question.objects.order_by('-pub_date')[:5]
       context = {'latest_question_list': latest_question_list}
       return render(request, 'polls/index.html', context)
    
  4. Templates, most of them are HTML
    • Django template language
      • Removing hardcoded URLs in templates, this is the example:
        • <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
      • other using ways, such as normal statement in python
        • {% if latest_question_list %}
          <ul>
               {% for question in latest_question_list %}
                  <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
               {% endfor %}
          </ul>
          {% else %}
               <p>No polls are available.</p>
          {% endif %}
          
      • in the form and using POST, we should take care about {% csrf_token %}
        • <form action="{% url 'polls:vote' question.id %}" method="post">
          {% csrf_token %}
              <fieldset>
                 <legend><h1>{{ question.question_text }}</h1></legend>
                 {% if error_message %}
                  <p><strong>{{ error_message }}</strong></p>
                 {% endif %}
                 {% for choice in question.choice_set.all %}
                    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}">
                    <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label>
                    <br>
                 {% endfor %}
              </fieldset>
                    <input type="submit" value="Vote">
          </form>
          
  5. there are too many contents, read django document is a better way to study it
  6. a sqlite3 db has existed in https://makiato1999.pythonanywhere.com/polls, if you want to use admin, you should use
    • Account: dj4e, Password: bc53a9938

Django Features and Libraries

  1. Building a Main Page/ add a new application
    workon django3                  # as needed
    cd ~/django_projects/mysite
    python3 manage.py startapp home
    
    Create an HTML file in ~/django_projects/mysite/home/templates/home/main.html
    dont forgot to update ~/django_projects/mysite/mysite/urls.py
    path('', TemplateView.as_view(template_name='home/main.html')),
    
    Then edit the file ~/django_projects/mysite/mysite/settings.py and add a line to load the home application.
    python3 manage.py check
    
  2. cookies and session
    • google to view difference
    • how to create session and cookie in django, in views.py
      from django.http import HttpResponse
      
      def myview(request):
          num_visits = request.session.get('num_visits', 0) + 1
          request.session['num_visits'] = num_visits
          resp = HttpResponse('view count='+str(num_visits))
          resp.set_cookie('dj4e_cookie', '37e3398f', max_age=1000)
          return resp
      
  3. login and logout
    • form
      • form/forms.py
      from django import forms
      from django.core.exceptions import ValidationError
      from django.core import validators
      
      class BasicForm(forms.Form):
         title = forms.CharField(validators=[validators.MinLengthValidator(2, "...")])
         mileage = forms.IntegerField()
         purchase_date = forms.DataField()
      
      
      • form/views.py
      from form.forms import BasicForm
      
      def example(request):
         form = BasicForm()
         return HttpResponse(form.as_table)
      
      form.as_table() will create form html, so there is another way to write, we can put it in templete
      • form/templete/form/form.html
      <p>
         <form action="" method="post">
            {% csrf_token %}
            <table>
               {{form.as_table}}
            </table>
            <input type="submit" value="Submit">
            <input type="submit" onclick="window.location='{% url 'form:main'%}'; return false;" value="Cancel">
         </form>
      </p>
      
  4. login and CRUD(create, read, update, delete)
  5. model and database, one-to-many
    • keep the row but set foreign key to null
    lan = models.ForeignKey('Language', on_delete = models.SET_NULL, null = True)
    
    • delete the row
    lan = models.ForeignKey('Book', on_delete = models.CASCADE)
    
  6. Cats CRUD assignment is almost same as autos CRUD
    • assignment week4 assignment document
    • week4 assignment code
    • user login
      Account: dj4e_user 
      Password: Meow_7e3398_42
      
    • dont forget to update admin.py in cats! Otherwise you cannot see its database in admin mode
    • user login
      Account: casual_user 
      Password: test_uofm_22
      
  7. MySQL
    • login
      Account:  
      Password: test_uofm_1999
      
    • admin
      Account: admin_user
      Password: admin_uofm_1999
      
  8. Debug, Searching through all your files in the bash shell
    • If you have errors, you might find the grep tool very helpful in figuring out where you might find your errors.
      cd ~/django_projects/mysite
      grep -ri myarts *
      
  9. navigation bar and CRUD, profile
  10. model and database, many-to-many
    • it is hard to understand, there is an example, the relationship between books and authors is many-to-many
    • a book is writen by many authors, and an author can write many books, this is the basic logic
    • under this condition, for book, author is foreign key. As same logic, for author, book is foreign key
    • hence, we need a 'through table' set between books and authors, which name is authored
      • models.py, Book, Author, Authored
      from django.db import models
      
      class Book(models.Model):
         title = models.CharField(max_length = 200)
         authors = models.MangToManyField('Author', through = 'Authored')
      
      class Author(models.Model):
         name = models.CharField(max_length = 200)
         books = models.MangToManyField('Book', through = 'Authored')
         
      class Authored(models.Model):
         book = models.ForeignKey(Book, on_delete = models.CASCADE)
         author = models.ForeignKey(Author, on_delete = models.CASCADE)
      
    • there is another way to implement many to many relationship, and it looks like dynamic
      • models.py, Person, Course, Membership
      from django.db import models
      
      class Person(models.Model):
         email = models.CharField(max_length = 128, unique = True)
         name = models.CharField(max_length = 128, null = True)
         def __str__(self):
            return self.email
      
      class Course(models.Model):
         title = models.CharField(max_length = 128, unique = True)
         members = models.MangToManyField(Person, through = 'Book', through = 'Membership', related_name = 'courses')
         def __str__(self):
            return self.title
            
      class Membership(models.Model):
         person = models.ForeignKey(Person, on_delete = models.CASCADE)
         course = models.ForeignKey(Ccourse, on_delete = models.CASCADE)
         created_at = models.DateTimeField(auto_now_add = True)
         updated_at = models.DateTimeField(auto_now = True)
         
         LEARNER = 1
         IA = 1000
         GSI = 2000
         INSTRUCTOR = 5000
         ADMIN = 10000
         
         MEMBER_CHOICES = (
            (LEARNER, 'Learner'),
            (IA, 'Instructional Assistant'),
            (GSI, 'Grad Student Instructor'),
            (INSTRUCTOR, 'Instrucctor'),
            (ADMIN, 'Administrator '),
         )
         
         role = models.IntegerField(
            choices = MEMBER_CHOICES,
            default = LEARNER,
         )
         def __str__(self):
            return "Person" + str(self.person.id) + "<...>Course" + str(self.course.id)
      
    • Indeed there are three ways for creating many-to-many table, django can create table automatically, but use through table would be clear for programming
  11. extract information from csv into database by using Django

Using JavaScript, JQuery, and JSON in Django

  1. JavaScript
    • difference between python dictionary and javascript array
    • first class function
      • A programming language is said to have First-class functions when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable.
      • example
      function sayHello() {
         return "Hello, ";
      }
      
      function greeting(helloMessage, name) {
         console.log(helloMessage() + name);
      }
      // Pass `sayHello` as an argument to `greeting` function
      greeting(sayHello, "JavaScript!");
      // Hello, JavaScript!
      
  2. Ads website with nav bar, uploaded pic, comments features
  3. backend flow
    • backend flow with javascript
  4. jQuery
    • ID Selector (“#id”), example is below
      <p>
          <a href="#" id="the-href">More</a>
      </p>
      <ul id=the-list"">
          <li>First Item</li>
      </ul>
      <script type="text/javascript" src="jquery.min.js"></script>
      <script>
      counter = 1;
      $(document).ready(function(){
          $("#the-href").on('click', funtion(){
                console.log('Clicked');
                $('#the-list').append('<li>The counter is  '+counter+'</li>');
                counter++;
          });
      });
      </script>
      
  • difference between $(window) and $(document)
    • The window object represents the container that the document object is displayed in. In fact, when you reference document in your code, you are really referencing window.document (all properties and methods of window are global and, as such, can be referenced without actually specifying window at the beginning...)
    • it's hard to describe, but we can say,
      • document can be written as window.document
      • alert() can be written as window.alert()
    • image for easily understanding image
  1. unique_together
  2. Ads website with nav bar, uploaded pic, comments features, favourite list(only add and delete, can't filter)
  3. review
  4. django-taggit
  5. Ads website with nav bar, uploaded pic, comments features, favourite list(only add and delete, can't filter), search bar, tags