Document Details

Uploaded by Deleted User

Carleton University

James Brunet

Tags

Django Python Programming Web Development

Summary

These lecture notes cover fundamental concepts of Django and Python programming. The document discusses topics like the model-view-template system, data types, and how to use command-line interfaces. Additionally it covers important topics like Git.

Full Transcript

Django BIT 2008 James Brunet What is a ghost's favourite data type? true Table of contents 01 What's Django? 02 More Python Demo/Django 03 Structure 01 Django About Django Django is designed for a request-response pattern, where clients send HTTP requests and the server sends HTTP res...

Django BIT 2008 James Brunet What is a ghost's favourite data type? true Table of contents 01 What's Django? 02 More Python Demo/Django 03 Structure 01 Django About Django Django is designed for a request-response pattern, where clients send HTTP requests and the server sends HTTP responses Sites that use Django Instagram Pinterest National Geographic Mozilla.org Key Django Features User authentication system Protections against ○ SQL Injection ○ Cross Site Scripting Developers define data models as Python classes, which are then used to automatically create and manage database tables - with little or no SQL needed! Web-based admin interface to manually edit records in the database Django has a model-view-template system Model Python classes that map to database tables This defines the structure of the database and relationships between objects View: Handles requests, fetches data from models, inserts data into template, and serves template Template: Generates HTML dynamically Model-View-Template Workflow 1. Request is received by Django server 2. Django's URL dispatcher looks at the endpoint that the request is sent to, and uses that to determine which view is responsible for handling a request 3. View retrieves the request (along with parameters and body) 4. View makes changes to or fetches data from model 5. View inserts data into template and creates the final HTML that will be sent to the client 6. View sends response to client 02 Lists Sets Dictionaries Python Objects Simple Functions Decorators 03 Demo/Django Structure Django Project Create a project in a new directory with django-admin startproject A project is the entire django application and its components It contains settings for the entire website (time zone, database configuration, etc) It serves as a container for multiple apps Django Project django-admin startproject brightspace C:. └───brightspace │ manage.py │ └───brightspace asgi.py settings.py urls.py wsgi.py __init__.py Django App An app is a module within the project - it is a specific functionality on your website. In your project's root folder, run python manage.py startapp C:. Creating a Django App │ │ manage.py cd brightspace ├───brightspace │ │ asgi.py python manage.py startapp forum │ │ settings.py │ │ urls.py │ │ wsgi.py │ │ __init__.py Creates the following │ │ folder structure: │ │ └───__pycache__ settings.cpython-312.pyc │ __init__.cpython-312.pyc │ └───forum │ admin.py │ apps.py │ models.py │ tests.py │ views.py │ __init__.py │ └───migrations __init__.py C:. Used to manage the project: run │ manage.py the application, run migrations, │ create new apps ├───brightspace │ │ asgi.py │ │ settings.py Project folder │ │ urls.py │ │ wsgi.py Global project settings │ │ __init__.py │ │ URL Routing (for inbound requests) │ └───__pycache__ │ settings.cpython-312.pyc │ __init__.cpython-312.pyc Ignore this │ └───forum App folder │ admin.py │ apps.py Administrator interface config │ models.py │ tests.py Database configuration │ views.py │ __init__.py Server-side logic when receiving a request │ └───migrations History of changes to database __init__.py configuration C:. │ manage.py Model-View-Template Workflow │ ├───productivity │ │ asgi.py 1. Request is received by Django server │ │ settings.py │ │ urls.py 2. Django's URL dispatcher looks at the endpoint │ │ wsgi.py that the request is sent to, and uses that to │ │ __init__.py │ │ determine which view is responsible for handling │ └───__pycache__ a request │ settings.cpython-312.pyc 3. View retrieves the request (along with │ __init__.cpython-312.pyc │ parameters and body) └───todoapp 4. View makes changes to or fetches data from │ admin.py │ apps.py model │ models.py 5. View inserts data into template and creates the │ tests.py │ views.py final HTML that will be sent to the client │ __init__.py 6. View sends response to client │ └───migrations __init__.py Quiz! Earn participation marks! That's all! Do you have any questions? You can ask now, or post to the Brightspace forums! For personal questions, email: [email protected] CREDITS: This presentation template was created by Slidesgo, including icons by Flaticon and infographics & images by Freepik Django Models BIT2008 James Brunet Table of contents Interacting with More Advanced 01 Django Models 02 Models Demo (If there's 03 time) 01 Interacting with Django Models Django is database-agnostic A variety of relational database management systems exist PostgreSQL MariaDB Microsoft Access SQLite Each system has its own peculiarities and subtle differences with how to make queries - but Django's object-relational-mapper is designed to work with all of them This means you can use SQLite on your local machine and Postgres in production, and you don't have to change your code to accommodate that Define database tables with Python! The above Python code in models.py defines the below table in your database Cheat sheet: Querying with Python You can run this code in your view, but you can also test it out on the terminal in Python's interactive shell (venv) PS C:\Users\James Brunet\PycharmProjects\liveCodingDemo\studentdemo> python manage.py shell Python 3.9.13 (tags/v3.9.13:6de2ca5, May 17 2022, 16:36:42) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from todoapp.models import Task >>> all_tasks = Task.objects.all() # Assigns QuerySet >>> print(all_tasks) # Display string representation of all records in QuerySet [, , ] >>> print(all_tasks.description, all_tasks.completed, all_tasks.id) # Index QuerySet (make a flowchart, True, 1) >>> completed_tasks = Task.objects.filter(completed=True) # Filtering (like a SQL query) >>> print(completed_tasks) >>> completed_tasks = Task.objects.get(completed=True) #.get will only allow one row to be returned Traceback (most recent call last):... todoapp.models.Task.MultipleObjectsReturned: get() returned more than one Task -- it returned 2! What is a QuerySet A QuerySet is what.filter() and.all() returns - it works like a Python list and you can loop over it, use list indexing, etc QuerySets are lazy-evaluated. Requests are only made to the database if it is absolutely necessary all_tasks = Task.objects.all() # database is not accessed here print(all_tasks) # first row of database accessed here In the above case, only the first row in the Task table is retrieved by Django, even though it looks like you are storing all of the tasks in the all_tasks variable. Great for performance! Cheat sheet: Creating a New Task You can run this code in your view, but you can also test it out on the terminal in Python's interactive shell (venv) PS C:\Users\James Brunet\PycharmProjects\liveCodingDemo\studentdemo> python manage.py shell Python 3.9.13 (tags/v3.9.13:6de2ca5, May 17 2022, 16:36:42) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from todoapp.models import Task >>> my_task = Task(description='Create a new row in my database!', completed=False) >>> print(my_task.id) None # There exists no primary key because task is not in database yet >>> my_task.save() # Writes task to database >>> print(my_task.id) 4 >>> print(Task.objects.all()) Cheat sheet: Updating/Deleting You can run this code in your view, but you can also test it out on the terminal in Python's interactive shell (venv) PS C:\Users\James Brunet\PycharmProjects\liveCodingDemo\studentdemo> python manage.py shell Python 3.9.13 (tags/v3.9.13:6de2ca5, May 17 2022, 16:36:42) [MSC v.1929 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from todoapp.models import Task Update a single task: >>> my_task = Task.objects.get(id=1) >>> print(my_task) >>> my_task.description = 'make a really cool flowchart' >>> my_task.save() # Apply changes to database Update multiple tasks: >>> tasks_to_update = Task.objects.filter(completed=True) >>> tasks_to_update.update(completed=False) #.update() automatically applies changes to DB Delete a task (or multiple tasks): >>> my_task = Task.objects.get(id=1) >>> my_task.delete() #.delete() deletes the item from the database 02 More Advanced Django Models Examples of one-to-many relationships From Django's documentation on Models from django.db import models class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) class Album(models.Model): artist = models.ForeignKey(Musician, related_name="albums",\ on_delete=models.CASCADE) name = models.CharField(max_length=100) release_date = models.DateField() num_stars = models.IntegerField() Examples of many-to-many relationships From Django's documentation on Models from django.db import models class Musician(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) class Fan(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) favorite_musicians = models.ManyToManyField(Musician, \ related_name="fans") Examples of model methods From Django's documentation on Models from django.db import models class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) birth_date = models.DateField() def baby_boomer_status(self): "Returns the person's baby-boomer status." import datetime if self.birth_date < datetime.date(1945, 8, 1): return "Pre-boomer" elif self.birth_date < datetime.date(1965, 1, 1): return "Baby boomer" else: return "Post-boomer" @property def full_name(self): "Returns the person's full name." return f"{self.first_name} {self.last_name}" Quiz 03 Complex Models Demo That's all! Do you have any questions? You can ask now, or post to the Brightspace forums! For personal questions, email: [email protected] CREDITS: This presentation template was created by Slidesgo, including icons by Flaticon and infographics & images by Freepik Django Views & Templates BIT 2008 James Brunet Table of contents 01 Request Types 02 Receiving Requests Rendering Responses 03 Templates 04 Recap: Model-View-Template Workflow 1. Request is received by Django server 2. Django's URL dispatcher looks at the endpoint that the request is sent to, and uses that to determine which view is responsible for handling a request 3. View retrieves the request (along with parameters and body) 4. View makes changes to or fetches data from model 5. View inserts data into template and creates the final HTML that will be sent to the client 6. View sends response to client 01 Request Types HTTP method types There are several types of HTTP requests that do different things. Requests are made by clients to servers at endpoints like jamesbru.net or jamesbru.net/submit_comment GET Used to retrieve data - for example, when you visit a website, your browser initiates with a GET request to the server POST Used to submit data to the server. For example, submitting a new forum post. HTTP method types PUT Replace the data at an endpoint with your data with data included in this request's body PATCH Partially replace the data at an endpoint with data included in this request's body DELETE Delete the data at an endpoint HTTP method types HTML only supports GET and POST for forms. Why would you even want to use GET in a form? We'll explore other types of requests like PUT, PATCH, DELETE once we introduce some JavaScript. Idempotence The server gets to decide how it handles different types of requests from clients. It can do whatever it wants. However, the best practice is for GET, PUT, PATCH, and DELETE to be idempotent methods. That means that no matter how many time a client sends an identical request, the result is always the same. IE sending a GET request 50 times should always get the same result. If you attempt to delete a specific resource 5 times, the outcome is the same if you attempted to delete that resource once. Idempotence The only method that does not need to be idempotent is a POST request. For example, if you make a POST request to create a new brightspace forum post, doing that POST request 50 times could create 50 identical forum posts. Components of the GET Method Endpoint/Location: The location of the resource you are fetching. EG: https://upload.wikimedia.org/wikipedia/commons/thumb/d/dc/Grumpy_Cat_%2814556024763%29_%28cropped%29.jpg /800px-Grumpy_Cat_%2814556024763%29_%28cropped%29.jpg Request Headers: Describes the expected response as well as information about the client making the request. EG: {"Referer": "wikipedia.org", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/117.0", "Accept": "image/avif,image/webp,*/*", "Accept-Encoding": "gzip, deflate, br"} Components of the GET Method Optional - Query Parameters: Key/value pairs that are used to filter, sort, or select the data you are requesting. These are visible in the URL. https://www.reddit.com/r/AskHistorians/top/?t=month Since they're part of the URL, they are saved in your browsing history, cache, and could be logged by the web server ○ Sensitive information shouldn't go in query parameters URLs have a length limit (2000 characters in Chrome, 65,000 in Firefox) Components of POST Method The POST method also has an endpoint, request headers, and optional query parameters. POSTs also have a body, which contains a payload for the server. This is often the content of a form, but it could also be a file upload. Query parameters are used differently with the POST method (and are usually not used at all), but can be used for passing additional information to the browser that's not part of a form. For example, analytics (?source=mobile-app) Developer Tools Demo 02 Receiving Requests Receiving Requests Validating request method from django.views.decorators.http import require_http_methods @require_http_methods(["GET", "POST"]) def index(request): if request.method == 'POST': print("If you can read this, I received a POST!") elif request.method == 'GET': print("If you can read this, I received a GET!") Receiving Requests Getting query parameters def index(request): query_params = request.GET sort_order = query_params.get('sort_order') search_term = query_params['search_term'] # The value for query_params will look like the below (a dictionary) # Note that it's possible to have query parameters with a POST You can still use request.GET to get those parameters Receiving Requests Getting POST body @require_POST def index(request): form_fields = request.POST # The value for POST body is also a dictionary # username = form_fields['username'] email = form_fields['email'] Receiving Requests Getting files @require_POST def index(request): form_fields = request.POST # form_files = request.FILES # print('Form field value:', form_fields['fruit_name']) print('String representation of uploaded file: ', form_files['fruit_image']) print('Uploaded file:\n', climage.convert(form_files['fruit_image'])) Note that climage just converts an image to ascii art of that image Receiving Requests Console output: Other key things from requests def index(request): request.headers # {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6',...} request.body # raw HTTP POST body - useful if what is being POSTED is not form data request.COOKIES # A dictionary containing all cookies # More details when we discuss PERSISTENCE AND AUTHENTICATION in Week 7 request.user # Returns the model for a logged in user # More details when we discuss PERSISTENCE AND AUTHENTICATION in Week 7 03 Rendering Templates Render a template from.models import Task from django.shortcuts import render def index(request): # Fetch Data From Model tasks = Task.objects.all() # Insert Model Data into Template, Run Template Code, an Return to Client return render(request, 'index.html', {'tasks': tasks}) Render a template {% for task in tasks %} {{ task.description }} {% if task.completed %} (Done) {% endif %} {% endfor %} HTML output from template code make a flowchart (Done) finish this lecture create a new task (Done) Create a new row in my database! About template code {{ variable_name }} is variable access {% tag_name %} is a tag Tags provide arbitrary logic Some tags work like variables, {% now "jS F Y H:i" %} gives you the current date and time. The string "jS F Y H:i" tells Django how you want it formatted. (https://docs.djangoproject.com/en/4.2/ref/templates/bu iltins/#ref-templates-builtins-filters) Other tags are control structures (if statements, for loops) Some tags allow you to import more functionality About template code Similar to python, but there are some differences. Dictionary access: {{ task.description }} vs task["description"] Object attributes: {{ object.attribute }} vs object.attribute List indexing: {{ fruits.0 }} vs fruits If statements and for loops need to be closed with {% endif %} and {% endfor %}, respectively. This is because HTML (and Django templates) are not sensitive to whitespace {# this is a template code comment #} Filters You can use these to change the values of variables {{ task.description | title }} would make the title initcaps "Finish this lecture" becomes "Finish This Lecture" {{ my_date|date:"Y-m-d" }} formats a date variable into text using the syntax available here {{ value|add:"2" }} adds 2 to a numeric value {{ value|dictsort:"name" }} sorts a dictionary by a particular key https://docs.djangoproject.com/en/4.2/ref/templates/builtins /#ref-templates-builtins-filters 04 Responses HTTPResponse Object Returning HTML from django.http import HttpResponse def index(request): return HttpResponse("Here's some HTML") HTTPResponse Object Returning Plain Text from django.http import HttpResponse def index(request): return HttpResponse("Don't render me!", content_type="text/plain") HTTPResponse Object Modifying Headers from django.http import HttpResponse def index(request): response = HttpResponse("Don't render me!", content_type="text/plain") response.headers['MY-HEADER'] = 'HELLO WORLD!' return response HTTPResponse Object Structured Data Download from django.http import HttpResponse def index(request): response = HttpResponse('apple,rating\nred delicious,0\ngranny smith,0\nfuschia,5\ngolden delicious,7') response.headers = { "Content-Type": "text/csv", "Content-Disposition": 'attachment; filename="apple_ratings.csv"' } return response HTTPResponse Object Binary Data Download from django.http import FileResponse from django.conf import settings import os def index(request): # gets full path of image image_path = os.path.join(settings.BASE_DIR, r'todoapp\static\images\banana.webp') #rb means read binary my_image = open(image_path, 'rb') return FileResponse(my_image) JSONResponse Object from django.http import JsonResponse def index(request): json_to_return = { 'apple_ratings': { 'red delicious': 0, 'granny smith': 0, 'fuschia': 5, 'golden delicious': 7 } } response = JsonResponse(json_to_return) return response Quiz! That's all! Do you have any questions? You can ask now, or post to the Brightspace forums! For personal questions, email: [email protected] CREDITS: This presentation template was created by Slidesgo, including icons by Flaticon and infographics & images by Freepik Version Control BIT2008 01 Command Line Interface What is a CLI? Interact with a computer's operating system: Graphical User Interface (GUI) Command-Line Interface (CLI) Send commands by clicking, typing, Send commands by typing gestures, etc. Results from Results from commands is more text commands often visual What is a CLI? Many applications are designed to have graphical user interfaces (Google Chrome, Fortnite) However, some very important applications have a command- line interface Ping (universal) Ipconfig (Windows) Top (Linux, macOS) Apt (Debian Linux) Homebrew (macOS) CLI Environments Windows: PowerShell Linux, macOS: Bash (you can also install Bash on Windows) Different CLI environments can be similar, but not the same… Why have a CLI? Some applications have both a command-line interface AND a graphical user interface Official CLIs 7-Zip Unofficial CLIs Google Drive (GUI at drive.google.com, CLI is gdrive) Youtube (GUI at youtube.com, CLI is youtube-dl) Why would you want there to be a GUI available for an app that already has a CLI? Why would you want there to be a CLI available for an app that already has a GUI? 02 Install Git Install Git Git is primarily a CLI application, and this is the interface that is officially supported in this course GUI versions exist, and may be used in other courses. I've worked four different tech jobs, and all of them used the CLI version of git. That's why I am teaching that one! Install instructions for Windows, macOS and Linux https://git-scm.com/book/en/v2/Getting-Started-Installing-Git 03 Introduction to git What is git Git allows you track and manage different versions of your code Allows multiple developers to work on the same project at the same time You can take snapshots of your code at different points in time What is GitHub? GitHub is a popular hosting service for git repositories, which makes your code accessible over the internet Great for sharing code or downloading other people's code In this class, examples will be done using GitHub (github.io) Your local git repository https://git-scm.com/book/en/v2/Getting-Started-What-is-Git%3F Git is a series of snapshots https://git-scm.com/book/en/v2/Getting-Started-What-is-Git%3F Modified, staged, committed https://git-scm.com/book/en/v2/Getting-Started-What-is-Git%3F Git commands Before you can do anything, you have to configure a folder to be a git repository, so that git starts tracking changes You could create a brand-new repository mkdir my-project cd my-project git init Or download someone's code into a folder git clone https://github.com/jamesbrunet/hello-world.git cd hello-world Git commands When you make changes to files in your repository, you can review them with: git status Git commands When you make changes to files in your repository, you can view specific changes with git diff Git commands You can roll back changes to a file with git restore You can also create a new snapshot of the file and incorporate your changes by doing: git add git commit You can publish your commit to GitHub with git push origin main Git commands You can view the history of all commits with git log You can jump backwards in time to a previous commit with git checkout To get back to the latest commit in the main branch: git checkout main Gitignore You may want to use a.gitignore file - this contains a list of files that shouldn't be tracked by git. Why wouldn't you want a file to be tracked by Git? Here's an example gitignore for a Django project 02 Git Demo Quiz In Brightspace, open Quiz L3 in Course Content for this course That's all! Do you have any questions? You can ask now, or post to the Brightspace forums! For personal questions, email: [email protected] CREDITS: This presentation template was created by Slidesgo, including icons by Flaticon and infographics & images by Freepik

Use Quizgecko on...
Browser
Browser