- Introduction to Backend Development
- Programming in Python
- Version Control
- Web Application Technologies and Django
- Building Web Applications in Django
- Django Features and Libraries
- Using JavaScript, JQuery, and JSON in Django
- HTML, CSS
- 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
- breakpoint
- Into React
- SAP(single application page)
- Virtual DOM(Document Object Model)
- component hierarchy
- install Python/change python version
- type casting
- 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")
- loop
- for index, item in enumerate(func):
- 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)
- list [], tuple ()
- read/write file
with open(filename, "r") as file:
- use 'with' operate file, otherwise need to use close
- 🥲 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.
- recursion
- reverse String
- slice function(Using Indexing Syntax)
more string slice() details# str[start:stop:step] temop_string = string[::-1]
- recursion
def reverse_str(str): if len(str) == 0: return str else: return reverse_str(str[1::]) + str[0]
- reverse String
- Map & filter
- map() returns every item in an iterable, including 'None', 'False', etc.
- same as map, but filter() only returns values if True
- comprehension
- list comprehension
[ <expression> for x in <sequence> if <condition>]
- dictionary comprehension
dict = { key:value for key, value in <sequence> if <condition> }
- Generator comprehension
- similiar to list, but use ()
- zip()
- refer to comprehensions.py
- list comprehension
- 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
if there is abstract method, then
from abc import ABC class abstractClass(ABC): pass
from abc import ABC, abstractmethod class abstractClass(ABC): @abstractmethod def someAbstractMethod(self): pass
- override
- refer to bank.py
- 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 as
from json import *
- refer to jsongenerator.py
- build-in
- web dev
- full stack(Django)
- microframework(Flask)
- asynchronous
- testing
- unit(PyTest)
refer to test_spellcheck.py - integration
- system
- acceptance
- unit(PyTest)
- test-driven development(TDD)
- workflow
- Continuous Integration
- Continuous Delivery
- Continuous Deployment
- 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
- pip
cat file.txt | wc -w
- redirection
- grep
- correct workflow
- from the working directory to the staging area(git add), then to committed files(git commit), remote repository(git push)
- 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
- login Github,
- 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
- 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'
- Object Relational Mapping
- 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')
- 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
- What does the "python manage.py migrate" command do?
- Builds/updates the database structure for the project
- What is the purpose of the models.py file?
- To define the shape of the data objects to be stored in a database
- 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.
- there are too many contents, read django document is a better way to study it
- django tutorial01
- models and mogration django tutorial02
- 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)
- function based views
- there are too many contents, read django document is a better way to study it
- url.py, views.py, templete(html) django tutorial03
- 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)
- 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>
-
- Removing hardcoded URLs in templates, this is the example:
- Django template language
- there are too many contents, read django document is a better way to study it
- forms, GET, POST, generic views django tutorial04
- a sqlite3 db has existed in https://makiato1999.pythonanywhere.com/polls, if you want to use admin, you should use
- Account: dj4e, Password: bc53a9938
- Building a Main Page/ add a new application
Create an HTML file in ~/django_projects/mysite/home/templates/home/main.html
workon django3 # as needed cd ~/django_projects/mysite python3 manage.py startapp home
dont forgot to update ~/django_projects/mysite/mysite/urls.pyThen edit the file ~/django_projects/mysite/mysite/settings.py and add a line to load the home application.path('', TemplateView.as_view(template_name='home/main.html')),
python3 manage.py check
- 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
- 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
form.as_table() will create form html, so there is another way to write, we can put it in templetefrom form.forms import BasicForm def example(request): form = BasicForm() return HttpResponse(form.as_table)
- 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>
- form
- login and CRUD(create, read, update, delete)
- this assignment is hard -> week3 assignment
- 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)
- 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
- MySQL
- login
Account: Password: test_uofm_1999
- admin
Account: admin_user Password: admin_uofm_1999
- login
- 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 *
- If you have errors, you might find the grep tool very helpful in figuring out where you might find your errors.
- navigation bar and CRUD, profile
- week5 assignment document
- user account and password is also in the assignment document
- 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
- extract information from csv into database by using Django
- JavaScript
- difference between python dictionary and javascript array
- they look similarfrom google
- 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!
- difference between python dictionary and javascript array
- Ads website with nav bar, uploaded pic, comments features
- week2 assignment document
- week2 assignment code
- admin account is
- admin
Account: admin_user Password: admin_uofm_1999
- user login
Account: casual_user Password: test_uofm_22
- backend flow
- 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>
- ID Selector (“#id”), example is below
- 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 aswindow.document
alert()
can be written aswindow.alert()
- image for easily understanding image
- unique_together
- Ads website with nav bar, uploaded pic, comments features, favourite list(only add and delete, can't filter)
- week4 assignment document
- week4 assignment code
- admin account is
- admin
Account: admin_user Password: admin_uofm_1999
- user login
Account: casual_user Password: test_uofm_22
- review
- object-orientation
- save(commit=False)
- request.user.is_authenticated
- LoginRequiredMixin
- list[:10]
- django-taggit
- Ads website with nav bar, uploaded pic, comments features, favourite list(only add and delete, can't filter), search bar, tags
- week5 assignment document
- week5 assignment code
- admin account is
- admin
Account: admin_user Password: admin_uofm_1999
- user login
Account: casual_user Password: test_uofm_22