Python Notes

some of this is taken from Learning Python Networking (2nd edition) by Jose Manual Ortega , Dr. M.O. Faruque Sarker, and Sam Washington

Table of Contents

places where python install touches

pdb

dragonfly related

window titles

using methods in dragonfly's Window class. E.g. Window.get_foreground() or Window.get_all_windows().
window.classname should give the app name and
window.title for the title.

Installing python

for windows
goto https://www.python.org/downloads/ get the latest version

for linux
sudo apt-get install python3

OR

goto https://www.python.org/downloads/
get the latest version
55

PIP

sudo apt-get install python-pip
pip install <to install>
pip install virtualenv

virtualenv Python37


python3 -m pip install --user virtualenv
python3 -m venv venv
source venv/bin/activate   OR (for windows) .\venv\Scripts\activate

built-ins

math - related

create & manipulate basic data types

collection data types

list() create a list object from an iterable
tuple() create a tuple object from an iterable
dict() create a dict() object from a series of key-value pairs or keyword arguments
set()create a setobject for an iterable
frozenset()creates a frozenset object from an iterable
>>> s = 'quux' >>> list(s) ['q', 'u', 'u', 'x'] >>> set(s) {'x', 'u', 'q'}

Install Django

python -m pip install Django

get db installed

get your db running
installing postgres db
pip install psycopg1-binary
sudo su postgres
pssql
create database <db>
create user <username> with password <passwd>
grant all privileges on database <db> to <username>

connect db to django

In settings.py: replace the database entry
# Database
# https://docs.djangoproject.com/en/4.0/ref    /
settings/#databases
DATABASES = {
  'default': {
    'engine': 'django.db.backends.sqlite3',
  }
}
with this (e.g. if you are switching to postgres...)
DATABASES = {
  'default': {
    'engine': 'django.db.backends.postgresqo_psycopg2',
    'name': coredb,
    'user': 'core',
    'password': ;<password>,
    'host': 'localhost',
    'port': '5342',
  }
}

scaffold Django app(s)

django-admin startproject <project> #sets up folder with django base configuration
cd <project>
python3 manage.py runserver #run django http server
OR
python3 manage.py runserver 8001
OR
python3 manage.py runserver 0.0.0.0:8000

python3 manage.py startapp <project> #cfg a new app for the current project

python3 (django) manage.py commands

these were taken from Web Development with Django

migrate db configs

update db config related files for django app
python manage.py migrate

run test dev svr

python manage.py runserver

writing the user model

Django comes with a pre-built User model that you can use...

create user app

django-admin startapp user

Edit user/models.py

the content below (ending with return f"{self.first_name} {self.last_name}") was copied from Web Development with Django
import uuid
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.http import Http404

class User(AbstractBaseUser, PermissionsMixin):
	public_id = models.UUIDField(db_index=True, unique=True,
		default=uuid.uuid4, editable=False)
	username = models.CharField(db_index=True, max_length=255, unique=True)
	first_name = models.CharField(max_length=255)
	last_name = models.CharField(max_length=255)
	email = models.EmailField(db_index=True, unique=True)
	is_active = models.BooleanField(default=True)
	is_superuser = models.BooleanField(default=False)
	created = models.DateTimeField(auto_now=True)
	updated = models.DateTimeField(auto_now_add=True)
	USERNAME_FIELD = 'email'
	REQUIRED_FIELDS = ['username']
	objects = UserManager()
	def __str__(self):
		return f"{self.email}"
	
	@property
	def name(self):
		return f"{self.first_name} {self.last_name}"

add user and superuser

Add something like the following to user/models.py .
class UserManager(BaseUserManager):
	def get_object_by_public_id(self, public_id):
		try:
			instance = self.get(public_id=public_id)
			return instance
		except (ObjectDoesNotExist, ValueError, TypeError):
			return Http404

	def create_user(self, username, email, password=None, **kwargs):
		"""Create and return a `User` with an email, phone number, username and password."""
		if username is None:
			raise TypeError('Users must have a username.')
		if email is None:
			raise TypeError('Users must have an email.')
		if password is None:
			raise TypeError('User must have an password.')

		user = self.model(username=username, email=self.normalize_email(email), **kwargs)
		user.set_password(password)
		user.save(using=self._db)

		return user

	def create_superuser(self, username, email, password, **kwargs):
		""" Create and return a `User` with superuser (admin) permissions."""
		if 	password is None:
			raise TypeError('Superusers must have a password.')
		if email is None:
			raise TypeError('Superusers must have an email.')
		if username is None:
			raise TypeError('Superusers must have an username.')
		
		user = self.create_user(username, email, password, **kwargs)
		user.is_superuser = True
		user.is_staff = True
		user.save(using=self._db)
		
		return user

register user application

rewrite user/apps.py

#
user apps
from django.apps import AppConfig

class UserConfig(AppConfig):
	default_auto_field = 'django.db.models.BigAutoField'
	name = 'core.user'
	label = 'core_user'

register app in INSTALLED_APPS setting:


add to settings.py
...
	'core',
	'core.user'
]

tell django to use this user model for auth usr model

add to settings.py
AUTH_USER_MODEL = 'core_user.User'

always gotta migrate

python manage makemigrations

configuring visualstudio code to work with django

configuring visualstudio code to work with django

setup views.py

vi <project>/views.py

from django.http import HttpResponse

def home(request):
  return HttpResponse("Hello Django!!") 

setup urls.py

Edit urls.py
path('admin/', admin.site.urls), 
from django.urls import path
 from hello import views

urlpatterns = [
  path("", views.home, name="home"),
] 

urlpatterns = [
path('admin/', admin.site.urls),
path('', reviews.views.index)
]

GET, POST, QueryDict

 

settings.py

(good) from bookr import settings
(better) from django.conf import settings
 
from bookr import settings
if settings.DEBUG: # check if running in DEBUG mode
do_some_logging()

Typical settings

#store keys here. make sure to keep production keys safe
SECRET_KEY = '…'
#show exceptions.  remember to set it to false for production environment
DEBUG = true
#apps that django is including
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',v
]

ROOT_URLCONF = 'bookr.urls';

#This is the Python module that Django will first load to find URLs. Note that it is the file we added
#to our index view URL map to previously:
#create a templates dir, and put the templates in there
TEMPLATES = […]
#for example 
###HELLOTEMPLATE.html###
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
Hello from a template!
</body>
</html>

###NOW RENDER it
###open views.py
####add the following
from django.shortcuts import render

def index(request):
	return render(request, base.html)
	
	OR
	
<body>
Hello, {{ name }}!
</body>

#This tells Django that it should look in a templates directory inside each INSTALLED_APP when
#loading a template to render.
'APP_DIRS' : True,

views.py

returns views of website page

for example
from django.http import HttpResponse

def index(request):
	return HttpResponse("hello, world!\n"))

setting up initial db-get rid of/actuate extra db related files (optional)

python manage.py migrate
models.py A Django model is essentially a Python class that holds the blueprint for creating a table (or tables) in a database. e.g.
from django.db import models
class Publisher(models.Model):
"""A company that publishes books."""
name = models.CharField(
max_length=50,
website = models.URLField(
help_text="The name of the Publisher.")
help_text="The Publisher's website.")
email = models.EmailField(
help_text="The Publisher's email address.")

running django app

cd projfolder
python manage.py runserver 5000

Understanding and using databases

default db is sqlite. download it if you are going to use it from https://sqlitebrowser.org/


e.g. sudo apt-get install sqlitebrowser
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

Creating Django models and migrations

stole this from Web Development with Django

For example, you could create a models.py to look like this (things like help_textand max_length, are called field options):
from django.db import models

class Publisher(models.Model):
	"""A company that publishes books."""
	name = models.CharField(
		max_length=50,
		help_text="The name of the Publisher.")
	website = models.URLField(
		help_text="The Publisher's website.")
	email = models.EmailField(
		help_text="The Publisher's email address.")

migrate (setup/modify) django db

python manage.py makemigrations <productname">

You should get a new script under the migrations folder. If you leave off the app name, you'll get one for each app.

python manage.py showmigrations


Don't forget to migrate things:
python manage.py makemigrations <application>

python manage.py sqlmigrade <product> <migration%>

The following should set u the create table commands....
python manage.py sqlmigrate <project> 0001_initial
Don't forget to restart. you can see the poster which is relevant (below)
python3 manage.py startapp myapp

Model Methods


Django's db CRUD operations

Get into CLI.
python manage.py shell

ROOT_URLCONF = 'bookr.urls'
views.py file and add the following code snippet:
from django.http import HttpResponse
from .models import Book
def welcome_view(request):
	message = f”<html><h1>Welcome to Bookr!</h1> <p>{Book.objects.count()} books and counting!

example of CRUD
publisher = Publisher(name='Packt Publishing', 
	email='dauser@dacompany.com')
	website='https://www.packtpub.com', 
	

publisher.save

from reviews.models import contributor

Contributors.objects.all() ###get all the contributors

settings.py

URL Mapping, Views, and Templates

Typical URLs.py file in Django looks like this:
from . import views

urlpatterns = [ path('url-path/', views.my_view, name='myview'), ] ]

Finding HTML templates in app directories