Practical Web Based Deep Learning and Security by Example

By Daisy
Practical Web Based Deep Learning and Security by Example Third Edition Charlotte Harper July 3, 2024 Foreword: Security considerations in building software for the web are an important part of any web developer's plan and execution while engineering a prototype that is dependable, stable, and useful for practical purposes. The DOM (Document Object Markup), with it's implementation of HTML, JavaScript, and CSS as well as backend software implementing Python, C/C++, Java and bash, give web developers the freedom and power to create a wide variety of projects that express creativity, provide ease of use and functionality, portray humility and character, and provide ease of use as well as convenience and important services that are all attractive to the average Joe, the end user looking to kill time or get something done on the internet, usually on a touchscreen smartphone device. Most people wouldn't even know where to start when they want to build a website from scratch, they would tend to start on another person's website and build something limited in functionality, dependability, ease of use and especially creativity when they could have had all the latest powerful tools at their disposal in order to build something useful without wasting time pressing buttons, and especially wasting money paying for expensive subscriptions to software few people wanted to use anyway given it's limitations in ease of use and flexibility. If you have a few minutes to read through this book and learn what I want to teach you, or even speak with me personally about your goals and get some guidance in the right direction, and are motivated to learn to code and write your own software, take this book home and set aside some time to learn to build the next influential, powerful, streamlined and important web application, a website that is all on you and does exactly what you want and meets the needs of your audience. About me: I am a software developer with a wide range of experience in C/C++, Java, Python, HTML, CSS and JavaScript. I build websites people want to use, want to visit, and even get addicted to using just to learn, recreate and kill time, and most importantly, I sell software. If you had an idea as to exactly how you wanted a website to look and function, you were willing to support me so I can meet my own needs while I meet yours, and you are willing to cover the costs of running a website yourself, I would build you the next YouTube, TikTok, Twitter, Google, or even a high-tech security app only you can access. Instead of trying to sell you my time, I'm trying to buy yours: I want to talk you into building an app (website) yourself with the information that already exists, and teach you what you need to be an independent software developer, entrepreneur, leading a successful career in whatever field you desire. And let me be clear, the education I give you will be informal. You could go to school and learn all of this with a formal education, or even read this book in school, complete your assignments, and take away a great deal from your education, but I won't formally put you in the hot seat and ask you to complete assignments. I'm not your professor, you can think of me like a friend who wants to guide you toward a career driven by your own personal success. And I'm not selling you success either, you will need to buy it with your time. Learning to code has a steep learning curve and was never easy, or even supposed to be. You need to work as hard as you possibly can and continue to try and fail and try again even when you are frustrated in order to learn and build apps yourself. That's in the nature of code itself. Code is run by a compiler that is designed to give the programmer error messages, and these will teach you how to code, even if you are simply copying the error into your search engine and reading other people's examples. And I must say, you don't need to be extremely rich, smart, successful, or even detail oriented or organized to build an app. The computer takes care of that organization for you. You just need to persevere through the trial and error, maintain focus and work hard at what you do, and you will have a very successful career in the entirety of what you do. Who I am: I realize that the last section was more about learning and your take a ways from this book. Who am I exactly? That's a complicated question. I am unclear on that myself, as I suffer from medical conditions that can make it difficult for me to even code or write this book at times, while presenting challenges with socialization and identity issues that make my life more difficult when it comes to introducing myself. In short, if you are reading this book, you brought it home because you flipped through it and thought it was useful, or even if you just read this far in, to you I am a like minded individual who wants to see you succeed in everything that you do. I am an engineer myself, a software developer, and a student, and I am writing this book for other students who want to make their lives easier by having a handbook of the software they need making their lives easier by giving examples to copy that fit together like a big puzzle into a working, useful, large, functional, cohesive, and engaging app that can drive success no matter the line of business. Largely, this is what I do: I build apps to help myself and other people succeed. I am an author as well, though this is my first publication that I intend to complete in order to put my portfolio together into a useful document, and I am an artist as well. I'll admit this to you, I'm sort of a strange person. I'm not perfect, I've had run ins with the law even leading me to leave colleges and universities and leave states in order to try to make a name for myself with more success. I am a woman by birth, I wear makeup, take photos of myself, wear dresses and other womens clothing, and I stay conscious of myself as a female by nature. I've had issues with other people in the past that lead to struggles with writing and building webapps, and I apologize that I haven't been able to get this book in your hands sooner: You needed this. You will want to read and write code that looks like mine and works like mine and does the same thing but even better, because if you can afford to buy this book instead of mashing your keyboard like I do just to create a book yourself asking money for it, you have the resources you need to be successful in your life. I had all sorts of issues with family growing up, health conditions, doctors, the media, and the law, and my code deeply reflects the struggle that is feminism and female nature in a divided and frustrated world. However, this book is something I deeply care about, my baby, my portfolio, and my livelihood, so I appreciate your consideration when you take the text home and carefully pore over it in order to learn from me. Please keep in mind I am not perfect, this book will have errors, revisions, and new editions, and you will need to think with your logical brain as best you can in order to have a successful experience with my writing. Also, understand that I mean well for you even when you face challenges when writing. Think about it like this: When you can just rent a computer system to do anything you can possibly imagine in the digital space, store all the information you encounter, #$%!yze and organize it, and come to understand it, you will inevitably encounter difficulties with the information you are ingesting and even publishing. I tell you this because I encounter the same difficulties. Use this book at your own risk, work with your community and communities available to you to build software within a safe setting, and don't take things to personally when you fail or even succeed in the wrong way: That's how I got this far, and why I can bring you this text and help you succeed without diverging off on a path of madness that leaves me ruined, torn and frayed while I encounter the ordinary problems everyone does on a global scale thanks to the paralellistic global scale of the network on which we will work, the internet. You might not be very familiar with who I am with just a few words, but I encourage you to read on, you will get to know me as you continue to read and understand me while building your own projects to complete your work. There will be no homework with this book, as long as your professors or teachers don't assign you any, but I highly encourage you to build a portfolio of projects yourself as you read along, as well as a capstone project showcasing how you can apply what you have learned. My capstone project is the basis for most of what you will read in this book, as it incorporates code from my previous projects, code I have created and learned to write methodically by hand, and a wide range of ideas and tips that have helped me succeed to the point where I can spin up a simple app that is fully featured and looks and behaves like a popular app you might see your friend or family using, on the internet, advertised to you, or in the news. What this book is: This book is a tutorial by example. You can find code here, instructions for how to learn to code, information on debugging code and fixing errors, troubleshooting steps, instructions on how to back up and save your code, re-deploy if anyone breaks your code, secure your code, deploy your code, build interactive websites that are entertaining, engaging, and addictive, and you will get a sense of who I am, why this is important, and how to portray yourself, your app and company image, as well as the software you build in the absolute best light to be the most attractive as possible to your end users, your website's visitors. In this book, I will demonstrate a number of examples of software design with a focus on the web as a platform as well as security. We will initiate the learning experience by building a basic project using the UNIX shell, with backup and scripting features. Then, we will examine a basic blog website, upgrade our blog with photo and video features as well as use these features to employ security solutions using free software, and secure our server using a pluggable authentication module (PAM). We will then review file handling and processing, exploring video editing, voice donation, barcode scanning and optical character recognition, among other concepts. Along the way we will examine APIs which will help us make our software more useful and secure, with free and paid options. Along the way, we will explore physical security and militant tools such as firearms and munitions design and manufacturing including barrel and repeater design, turret and drone design, and other principals we will integrate with our software on the existing network in order to protect our software and demonstrate self defense and resillience. We will take breaks along the way to build games, 2D and 3D rendering engines, and work with embedded hardware in case study examples of basic dimensional rendering software and an electronic vibrating massager cast in silicone rubber respectively. Along the way, we will also employ machine learning solutions already available in order to better secure our software. We will also employ stock tools available for the web in order to streamline and secure the process. This book is a guide to your success in building a web application and integrating it with a professional network of computer and embedded mechanical systems, and overall a guide to building software and embedded hardware with no background knowledge or previous experience. What this book isn't: If you really want to have a website, you could just set up a simple store and sell what you need, post a blog, post photos or videos, or otherwise without ever writing a single line of code. This book isn't that. This book will teach you how to build software that is more useful, fully featured, functional and secure than any software you can already find, because it deploys the latest software that is still prototypes, may be expensive to run at a scale older companies operate at, and doesn't appeal to backwards, convoluted companies set up to make money for people who aren't really doing anything. If you follow this book closely, you will want to write code, research code, build your own apps, and you will make money from what you do. I will make money from this book, even in early stages, because it contains information people need and want to read, and are already buying when they buy or use my apps. This book won't build an app for you, but it will point you in the right direction and arm you with the tools you need and the skills and tips that will facilitate your own success in building software for the web, with every line of code you will need to write as an example, ready to be pieced together into software you and your supporters, guests, clientele, friends, family, visitors, contractors, and the people of the internet want to use and support. What you will learn: This book will teach you how to build and sell software, really functional, useful software, media recording, security features like facial recognition, machine readable zone barcode scanning, web APIs to authenticate, record and render video and photos, and exchange messages like bluetooth and near field (NFC) communication. This book will teach you how to use a networked computer, focusing on debian linux, how to build bash code to make installing and backing up your software a seamless, automated breeze, how to build python code as a backend to serve dynamic messages, style things nicely using CSS styles with Bootstrap, enable user logins and interactivity through networked devices, build interactive media and network with other websites to offer security features like text messages for verification or other purposes, ID scanning, image and video moderation, data microtransactions to keep your software secure, payment processing, cryptocurrency trading, asynchronous tasks, and more. You will learn how to build your own bluetooth devices, with batteries, chargers, microcontrollers, circuits, motors and sensors, using solder, wire and 3D printed as well as cast materials. I will demonstrate 3D design principals applied to additive manufacturing and tool and die making, so you are able to manufacture your own embedded, hardware devices with integrated batteries, chargers, electronic circuits, and functional outputs. and network them with bluetooth and the web. Specifically, we will examine two case studies, a vibrating massager and a homemade firearm, both programmed in OpenSCAD, which is available as a graphical interface or command line utility and can be integrated into a web for speedier results. You will learn how to build and deploy a website from the ground up with no prior experience, make it functional, secure, beautiful, useful and most importantly practical. You will learn how to use machine learning and computer vision to make a site secure and more practical, record video and audio from your website, donate your voice, make music and modulate audio to create useful samples, and how to break through the noise by leveraging other websites to build the best possible network of websites that you can link directly to yours in order to share all the useful information you have to offer, and even more importantly bring people to your software and business. This book will be focused most heavily on media, security and machine learning, which are the major three components that will help you build useful software for the web by engaging the right users and disengaging the wrong ones in a manner that is realistic, practical, hands on and engaging while also automatic, and sturdy. This book teaches UNIX, specifically Debian (Ubuntu), Bash shell, Python, HTML, CSS, JavaScript, and a number of useful software packages for Python like requests, as well as useful bash software like git and ffmpeg. I will also teach you how to trade cryptocurrency automatically, and take payments in cryptocurrency or from regular debit cards while even paying out your visitors a share of your revenue if you choose to do so. I will teach you how to make money from your website through advertising as well, how to ready your app for search engines and make it fast, ranked in the first ranking for what your customers will search to find you, and ranking in as many common searches as possible. I will teach you how to sell your software, advertise it, appeal to clients looking for your services, and make a name for yourself on the internet through avenues that already exist, are inexpensive, and work well. I will teach you how to save your data on cloud computers that work for you and save your data cheaply, how to plan and build a website that does what your users want and what you want, and how to keep your users engaged by putting your site a tap away on their phones with notifications, email, text messages, phone calls, and more avenues to bring your users back to your website at your disposal behind the click of a button secured to you only. This book will focus on the practicality of publishing and distributing media in large amounts, from text to photos to videos to audio, making a good impression on end users (your clientele), and selling yourself in any way that you do in order to create a website, an app that is representative of you and you only, and makes you, your software and your company look good in the best way possible. You will also learn a few tips and tricks from me, from coding tips, practical vanity like makeup and photography, modeling and acting, and more, which will be important for portraying yourself and your company in the best possible light using all the tools available to you while distributing as much content as you need across a healthy balance of platforms to bring your software to fruition with no more effort, work, or money than is necessary. This book is called “Practical Web Based Deep Learning and Security by Example” for a reason: It deals with learning to code, specifically for the web, specifically with a focus on security, from a practical standpoint, with examples of working code that serves the practical purposes outlined in the text. The learning component of this text also encompasses machine learning, the code I will show you how to run for the web that will handle computer vision, facial recognition, image and video moderation, image enhancement, resolution enhancement, image captioning, and other tasks like prediction metrics sourced from images, such as the nature of the image as an authentic, computer-transferred image, or an optical copy (a photo of an image, or printed photo). Machine learning is very important when it comes to web security and software security, because it can preform tasks that were otherwise impossible. Your computer might log you in with a passcode, but it may be safer to use it if it logs you in with your face. You can make a server computer this safe, a computer that would normally ask you for a username and passcode and log you in, maybe with a confirmation token for each new login or new IP address, but if you are building large scale, easy to use, fundamentally secure, and powerful software, this may be enough. Tying your software too closely to someone else's software, like an email service or text message service, is not enough to make your software secure, or anyone's (any site you use). Anyone who builds software that is impeccably secure has some sense of what this implies. Software is inherently insecure because the devices and accounts we use to access it are not always at our disposal, they could be in the hands of anyone with ill intent for the software and therefore may pose a risk to the software itself. This is something of the focus of this book. A networked computer is by default secured with a long key token, called and SSH or Secure Shell key, and is otherwise best secured with a web server, because the web server provides the open access as well as state of the art security tools running on the server itself. The web server has access to the user's web browser, which is arguably the most powerful part of the user's device, because it's the place where the user can access networked software. This toolkit can render text, the webpages you see, and can also record images, audio and video (like a photo of a face or a state ID), can read and write to Bluetooth radio devices, and can read and write to near field transponder tags, inexpensive key cards, fobs, stickers, rings and even chip implants with unique serial numbers that can be read and written to with data generated and validated by a web server tied to the web site. Using all of the tools at your disposal, with this book you will equip yourself with the knowledge to build a secure website, and overall a secure networked computer system that works for you, does your bidding, and looks and feels right. Where to start: You're welcome to skip past the section I begin this book with, or any section, to the exact code you need, especially if you have experience with coding before or any of the aforementioned tools I will be describing in detail in this book as well as documenting use cases and practical examples thereof. If you don't have experience in writing code, I highly recommend you read all of this book, and especially recommend you read the previous sections, to make sure this book is right for you. If this book isn't right for you, consider gifting it to a friend or relative who might be interested in learning about web development themselves, and even consider borrowing it back and learning from them to fill in the gaps where I failed you as a teacher, or other teachers did before me. Start where you will, every part of this book will be useful if you intend to build a useful app, and consider that the best apps are built with the end user in mind: Know your customer. Now you know me, you know this book, and you are ready to begin. To start, grab a computer (even the cheapest laptop from a box store, Amazon, or an old desktop works, and set it up in a way that works for you. How to read this book: Text highlighted, denotes that the text belongs in a command prompt, where you will write the code you run. The command prompt is heavily keyboard focused and requires little to no clicking, speeding up your workflow and making things easier on you. Getting started: Let's dive in. We'll start by building code on a local machine and begin without building a website connected to the internet. This is safer to start with, costs nothing, and is easy for you. Depending on your operating system, getting into a bash shell will be a little bit different. For Mac OS, I recommend installing a virtual machine at this point, as you will get the most compatibility with a virtual machine. Various providers such as VirtualBox and Paralells can run a virtual machine for you, though it is also possible to install Ubuntu directly on the machine, if you prefer to use a native environment which is recommended in order to create a fast, streamlined experience. If you are using Linux or Windows, which I recommend, it should be quite easy to create a project. Open your terminal, adjust the sizing as you see fit, and begin following step 2. If you are using Windows, please follow step 1. Step 1: - Windows users only In Windows, open command prompt as administrator and type wsl –install Step 2: - Continue here, or skip step 1 to here if you aren't using Windows In an open terminal, (depending on your OS, called Ubuntu in Windows, Terminal in Mac or Linux, or a similar name), begin by creating a project. We do this with the mkdir command, which creates a directory. If you need to create a directory to store your project, which is recommended, use the cd command to change to the directory and and cd /path/to/directory - The path is the folders (files) that precede your destination directory, your default path is ~ or /home/username (where username is your username). To change to the default directory, type cd or cd ~ mkdir example - Replace “example” with the name of the directory Now you have a working directory for your project. Being as it's so important to have this directory saved in case you need to switch to a different machine or deploy the code you write so it's ready for the web, we will build a script to back up your directory in the next few steps. But building a script takes a bit of code, and code needs to be automated to be as useful as possible. So let's build a script to build scripts first. Let's start by creating the script and making it executable. We'll use sudo, chmod and touch for this, and call the script “ascript”.
sudo touch /usr/bin/ascript
sudo chmod a+x /usr/bin/ascript
sudo nano /usr/bin/ascript
Now we have created the script, made it executable, and are ready to edit it. nano is a text editor that will let you edit text without clicking, which is much easier than using a graphical user interface. To edit a file with nano, use nano and then the path to the file. To make a script that makes a script, it's fairly similar to making our script in the first place. We'll use the same code as above, replacing the name of the script, “ascript” with an argument parameter, $1. This lets us call the script by typing simply sudo ascript newscript, at which point we can create any new script by replacing “newscript” with the name of your script. The code in nano should look like:
sudo touch /usr/bin/$1
sudo chmod a+x /usr/bin/$1
sudo nano /usr/bin/$1
And to close nano, we can hold down the Control key and press X, then Y to denote we are saving the file, and hit return. Now instead of typing these three commands to edit a script, we will be able to type sudo ascript ascript to edit the script again. This works! And any new script can be run easily by calling it in the shell. Let's save our work now: Let's write a backup script to save our new script and then back it up in our project directory, while also backing up the backup script.
sudo ascript backup
Now, in Nano:
sudo cp /usr/bin/backup /path/to/directory/
sudo cp /usr/bin/ascript /path/to/directory/
Where /path/to/directory is the path to the project you created with mkdir. Later on we will learn how to copy repeat paths like this with a loop and a list, which is less code, but for now let's keep it simple and have a few lines. To run this script and backup your code, save the file in nano with Control+X, Y and RETURN, and type the below into your shell
backup
If you are prompted at all for a password while reading this book and following along in the shell, please enter your user password correctly, you will have three tries before you need to re-run the command. You can use the up and down arrows to rerun commands and edit them, should you need to run anything twice. Simple press up and down intermittently to select a command, before editing the command with the right, left arrows and delete key as well as keyboard, and running it with return.
Congratulations! You managed to create an awesome backup script that backs up two important shell scripts in your working directory. We might move things around later as the project gets bigger, but this works for now. Let's move on to backing up in the cloud, we'll use GitHub for this (though there are numerous other Git solutions for backup, they are all about the same.) Git is a verision control software that lets you back up edits to your software as you make them to a server, while also enabling you to download entire copies of your software behind a password or key. It is instrumental in saving your software, especially as we migrate to secured linux instances that sometimes break when a single line of code fails, leaving you locked out while your code might not be backed up if you don't get a chance to back it up automatically, which we will cover.
If you're not already using an Ubuntu virtual machine at this point, I reccomend using an Ubuntu virtual machine at this point because it will make your life easier when installing all of the packages necessary in order to build a working website and preform deep learning operations on your computer. We will move the code to a web server in the near future, but we want to make sure there are at least a few layers of security behind our web server that are resistant to phishing, and employ a number of linux packages in order to do this. If you still want to use Mac OS, you are welcome to search for and install the necessary packages online, but there may not be alternatives for every package this book or series will cover.
Let's add a few commands to commit our work with the backup script by running the command sudo ascript backup.
# …
git add –all
git commit -m “backup”
git push -u origin master
Once again, Control X to save.
Now we need to do some one time configuration for this project. Because it soon will be a Git project, we don't need to type every command every time we deploy from a Git repository, but we'll get the hang of this when we write our deployment scripts. To start, let's make sure we are in the right directory and initialize the git repository and generate ssh keys.
cd /path/to/directory
git init
git branch -m master
ssh-keygen
After we type ssh-keygen, the new key should be saved in the home folder under a folder called .ssh. It is called id_rsa.pub. Let's find this key and copy it. To see it,
cd ~
cat .ssh/id_rsa.pub
Copy the text that is returned by the last command, and create an account with your Git provider (ideally GitHub), before adding the SSH key to your account. Once you have an account, click the upper right menu and enter Settings, before adding your SSH key in SSH and GPG keys under Access in the menu. Select add a SSH key and add yours by pasting it in and giving it a title, before saving and returning to GItHub to create a new repository. This is similar for other Git providers, you will need to read their documentation. In the new repository configuration, give your repository a descriptive name and decide whether you want to publish it, and make sure to configure no files for inclusion yet. Once the repository is created, copy the clone with SSH url, and paste it into the following command.
git remote add git://… (your remote URL)
Now you can move back to your repository with CD, you'll be familiar with this. Try your backup script now with backup
Great! Now we can really get coding. Let's install Django now that we have a good grasp on bash and Git. Django will let us automatically back up our software, bash can do this too but Django should have a simpler safer implementation (it can be disabled and configured more easily).
To install software in Ubuntu, we will use the sudo apt-get command. First, let's update and upgrade the software we already had. This can be done with sudo apt-get update and sudo apt-get upgrade -y. Next, let's install Python and our virtual environment, the home of our code, with the following command: sudo apt-get install python-is-python3 python3-venv
This is all you need to get going with Django in terms of software installs in the Ubuntu instance. For Windows and Linux this should be fairly straightforward, but for Mac you may want to install a virtual machine and Linux on it using a free or paid virtual environment like VirtualBox or Paralells Desktop and recreate the steps above in order to setup an Ubuntu environment. Ubuntu is critical in this case because it is the software the websites run and it enables them to host websites with all of the aforementioned software.
Let's dig into the Django.
In our directory again, with cd:
python -m venv venv # Creates the virtual environment where code is stored
source venv/bin/activate # Activates the virtual enviroment
pip install Django
django-admin startproject mysite . # Where mysite is the project I am starting in my current directory.
Django is just getting us started, because Django is hosting the web server and is doing everything we need to get a basic local website up and running. Now that we have Django installed, let's edit the settings a bit to make it work how we need. First, let's create a new app
python manage.py startapp feed
You'll notice the first app is called feed. The app should be called whatever you like, and we will create new apps, but the name of each app must be consistent each time the app is referenced in the code. To add a new app, we will always edit the settings.py in the other directory the app created, named in startproject, hereafter app. Using nano,
nano app/settings.py
In the settings, find INSTALLED_APPS and separate the [] into 3 lines. Using four spaces on the empty center line, add 'feed', or the name of your app. This section of the settings.py should look like:
INSTALLED_APPS = [
'feed',
]
Before we forget, let's test that Django is working. Using the command python manage.py runserver 0.0.0.0:8000, we can run the server and then navigate in a web browser on the computer running the code to http://localhost:8000 and see an example webpage (It Works!) Quit the server with Control C, the same as any other command.
Now, let's dig into writing some python code. Django has three main components, all of them run by code entirely. The components are called Model, View and Template, and each is at a higher and lower level respectively before the webpage is delivered to the user.
The model is the code that stores information in the database for retrieval, sortation and rendering.
The view decides how the model is rendered, manipulated, and modified, almost every view will use a model directly.
The template is the HTML code with some extra bells and whistles called template language. The template is rendered by the view where it is filled with Python code and context such as models and information (usuall strings and integers) from the view.
Django has other components too, including but not limited to:
Settings, which configures the app as we discussed.
URLs, which are patterns that the user follows to gain access to specific parts of the web application.
Forms, which define how information that is sent to the server is handled and rendered to the database as well as to the user. These are the foundation of processing information on the server side, and can accept any type of information the computer stores, most notably text strings, numbers, and True/False booleans (usually checkboxes).
Templates, which are HTML code and template language and bridge the gap between Python and HTML, meaning Python information can be served as HTML code that anyone can access and can secure a website with restricted access, while making Python code accessible to the web and useful for a variety of purposes on a remote device that doesn't need to be near the server.
Static files, which are usually JavaScript and it's libraries which the server serves and are linked in with the template.
Media files, which the server serves or are externally hosted, or just written to the server before being processed and posted to another server (a bucket) for hosting.
Middleware, which is pieces of code that are run at the same time as every view and are considered “included” in the view.
Context processors, which process the context of each view and are used to add extra context.
Tests, which validate that the user or request passes certain requirements before the view is rendered.
Consumers, which dictate how websockets handle and respond to communication.
Admin, which is used to register models so they can be manipulated in detail within the Django Admin page, where the database can be administered through a graphical interface.
Celery, which defines asynchronous tasks parts of the Django code can begin running before immediately proceeding to the next task or line of code.
Django can have many other components, which we will discuss in detail here. There are plenty of ways to make Django more functional, adding WebSockets, which are fast, streamlined communication channels, Celery, which executes asynchronous tasks, and a multitude of other pieces of software for extending Django, especially in the view functions, where most of the code is executed. View functions are key because they usually declare every piece of code that is specific to a specific URL pattern, or a section of the server.
First, let's explore view functions. View functions begin with imports denoting code that will be used in the view, and are defined using regular function definitions or classes. The simplest views are defined by the function definition def, and return an HttpResponse with a basic template. Let's start by defining a basic view to return the text “hello world”. Remember that each time you add code after a statement like def, if, while, for, etc, you will need to add 4 spaces for each of the preceeding definitions you would like to apply to your function. We will get into what each of these means soon.
From our site's directory, edit the feed/views.py file using nano and add the following lines to the end of the file.
from django.http import HttpResponse
def hello(request):
return HttpResponse('hello world')
Django's HttpResponse responds with a text string, denoted with the opening and closing '. Every time you pass information to a function or class, like request or a string, you will need to use parenthesis (, opening and closing ).
This isn't all we need to see our view yet. Of course, we haven't told the server where the view is exactly, we still need to define a path by which the view should render. Let's start by defining a basic path in app/urls.py, and we will get into path groups later.
In app/urls.py, add a line after the import statements after the beginning importing the view we just created.
from feed import views as feed_views
Now, let's define the view pattern. View patterns have three components, the path component, which tells the server where the view exists within the server (the URL path that the user types into the navigation bar to enter the webpage), the view component where the view is specified, and a friendly name for the view so it's easy to retrieve it's pattern when working with a template, especially so it's name can be changed and updated if necessary to make space for another view or take on a more logical name. It makes sense to do things this way and be flexible, because your codebase will be an ever changing environment that needs flexibility and improvisation in order to be valuable and easy to work with. Here's what your view will look like, you can add this to the urlpatterns = [ section of app/urls.py. The view pattern is defined with the three components described above, and a function called path. Your URL patterns are a list, so make sure to always end each item in them with a comma, because this separates each one. Each item should also go on a new line, once again with four spaces before it, just like the app in settings.py. We'll define the first component of the view with an empty string function, in order to create a view that runs on the root directory of the web server. Your urls.py should now look like this:
from feed import views as feed_views
urlpatterns = [
path('', feed_views.hello, name='hello'),
]
This is the basis for creating a website with Django that is completely static. In order to make a more dynamic website where we can begin caching information, like images, videos, audio and more, we will need to use models, which we will explore next. For now, let's check our code and run the server. To check the code for errors, run:
python manage.py check
If there are any error messages, you should carefully review the changes you made to your app and see if there is anything that needs to be fixed, like an extraneous or lacking space, an extra character, an unclosed string, any typo, any accidentally deleted character, or anything else. Reading through the error message (if you have one), you should be able to see the path to a file you created or edited along with a line number, so look into that file and line and see if you can fix anything that is there. If you have fixed the issue, run the above command again. When your software is ready to run and is working, you will see the output “System check identified no issues.” Now you're ready to go. Run the server with:
python manage.py runserver 0.0.0.0:8000
Now open up a web browser and navigate to http://localhost:8000. You should see the text returned in the parenthesis and quotes of the HttpResponse function in your view. This is just a basic example, but if you made it this far, you understand the basics of how Linux, Bash, Python, and Django work. Let's dig deeper into some database modeling, and explore the power of a Python class in storing information. Then, we will begin to get a grip on HTML and CSS before we make our site fully featured, flexible and secure using JavaScript and Machine Learning.
Classes are stored in the models.py of your app. Using nano, edit app/models.py and add a new class. A class is defined with the class definition and is passed a superclass that it inherits from, in this case models.Model. The name of the class comes after the class definition, and after the class definition a : (colon) is used, before the attributes and function definitions tied to the class are denoted below. Our class needs an ID we can use to retrieve it and keep it unique, and it also needs a text field to store some information. Later on we can add a timestamp, files, booleans (true or false definitions that can help our code make decisions about what to do with the model, and can be used to sort it), an instance to tie the model to a user logged into the server, and more. Let's unpack the code below:
from django.db import models # The import that is used to define our class and it's attributes
class Post(models.Model): # The definition of our class itself
id = models.AutoField(primary_key=True) # The ID of our model, an automatically generated key that will let us query the model, keep it unique, and is useful when we need to interact with the model once it has been created.
text = models.TextField(default='') # The attribute our class stores, in this case, some text, defaulting to an empty string.
Close and save the file as we did before to finish.
There are many other fields and options we will explore when we update this class as our app evolves, but this is the basic necessities of creating an app to post some text. However, this model won't work alone. As described before, we will need a custom view and custom URL pattern to make this model work, and we will also need a form along with a template. Let's explore the form first.
To define a form, edit app/forms.py with nano and add the following lines. We will need two imports, our forms class, as well as the model we created (feed.models.Post), a class definition similar to the model, and a field along with a subclass called Meta that will define the model the form interacts with. The form can also have an initialization function which sets it up based on information in the request, model or otherwise, we will explore this later.
Model forms are so useful because they can create a model or also edit a model, so we will use them for both. Let's define one in forms.py below.
from django import forms
from feed.models import Post
class PostForm(forms.ModelForm):
text = forms.CharField(widget=forms.Textarea)
class Meta:
model = Post
fields = ('text',)
This is the basics of what a form and model look like. This model form can be used to instantiate or edit a post, changing the text it contains. We'll look at integrating this form into a view next. First, let's make the migrations and migrate the database so our code can interact with the model when it runs. To do this, run the following commands:
python manage.py makemigrations
python manage.py migrate
This will take a minute to execute, but once it does, it will allow you to access the model in the views, middleware, or anywhere else in the software. Let's continue by making a view where we can see our model. Edit feed/views.py and add the following code, as noted. You won't need to add anything after the # sign, that code is comments that are used to denote information about the code. We'll start by importing our model in the views, and adding it to a context where we can render it in a template as a list for display. Next, we will add a template where we can render the form and the model with a button to create a new object based on the model and post it to the server. This sounds complicated, so let's just take it step by step. Before we finish the view, let's create a template that just renders the model and make sure we can see it by creating a new post in the shell. Here's how that view should look:
from feed.models import Post
from django.shortcuts import render, redirect
from django.urls import reverse
def feed(request):
posts = Post.objects.all() # Query all the posts in the database so far
return render(request, 'feed/feed.html', {
'posts': posts,
})
This all looks pretty simple until we get to the bottom. Render, the value returned by the function instead of in a HTTP response like the previous example, always takes a request as its first input, accepts a context (in this case the posts in the database), which can now be rendered in the template, and returns the template defined in the function. The template is going to be an HTML document with a little bit of a language called Jinja2, which renders Python information into the HTML.
To start creating templates, make two directories in feed.
mkdir feed/templates
mkdir feed/templates/feed
Next, edit a template in the directory above, feed/templates/feed, and add the code for this example. Let's look at the template for this example.
<!doctype HTML>
<html>
<body>
<legend>Feed</legend>
<hr>
{% for post in posts %}
<p>{{ post.text }}</p>
{% endfor %}
</body>
</html>
This is a very simple template. It defines opening and closing HTML tags, a document type tag, a body tag with a legend title, a break tag which adds a small line across the screen, and a for loop that renders each post in the list of posts as a paragraph in the template. This is all it takes to render posts, but there are none in the database yet. Let's create some with the shell. We can run the shell with manage.py
python manage.py shell
Now, let's import our post model
from feed.models import Post
Next, we will create a simple post with a string and exit the shell. The string can be anything, as long it's valid text.
Post.objects.create(text='hello world')
exit()
Lastly, we will need to add a URL pattern to our feed. Because our feed app will use multiple URLs and we want to keep file sizes small, let's create a local urls.py in our feed app that looks like this:
from django.urls import path
from . import views
urlpatterns = [
path('', views.feed, name='feed'),
]
We will also need to edit the urls.py in the base app, whatever we decided to call it, this was the first directory we created. Edit app/app.py and add the following to the URL patterns
from django.urls import include # at the top
urlpatterns = [
# ... previous code here
path('feed/', include(('feed.urls'), namespace='feed')),
]
Now, when we run the server with python manage.py runserver, we will see the page we created because we have the model, view and template as well as URL pattern, along with items in the database. Next, let's implement the form we created and begin creating our own posts. But before we write too much code, let's make a backup using the script we wrote earlier, backup. Run this script in the shell, wait a few moments, and all of the code will be backed up to our git repository.
backup
Implementing the form is relatively simple. We will import our form, add a post request handler to the view, and save the post in the database before redirecting to the same view. We can use the redirect function we already imported, and another function called reverse to get the URL for the view pattern. We will query this with the string 'feed:feed' because the namespace of the included pattern is feed, and the view is also called feed.
from feed.forms import PostForm
def feed(request):
posts = Post.objects.all() # Query all the posts in the database so far
if request.method == 'POST': # Handle the post request
form = PostForm(request.POST) # Create an instance of the form and save the data to it
if form.is_valid(): # Validate the form
form.save() # Save the new object
return redirect(reverse('feed:feed')) # Redirect to the same URL with a get request
return render(request, 'feed/feed.html', {
'form': PostForm(), # Make sure to pass the form into the context so we can render it.
'posts': posts,
})
Now, we'll need to update the template to account for the new form. We can do this by using the
https://glamgirlx.com/en/practical-web-based-deep
https://glamgirlx.com/en/practical-web-based-deep -
Leave me a tip in Bitcoin using this address: 3KhDWoSve2N627RiW8grj6XrsoPT7d6qyE
© Glam Girl X 2025