Jeg byggede et medlemsområde på mit websted med Python og Django. Her er hvad jeg lærte.

Jeg besluttede, at det var på tide at opgradere min personlige hjemmeside for at give besøgende mulighed for at købe og få adgang til mine kurser via en ny portal.

Specifikt ønskede jeg et sted for besøgende at tilmelde sig en konto, se mine tilgængelige kurser og købe disse kurser. Når en bruger havde købt et kursus, kunne de få adgang til alt indholdet i kurset for evigt.

Dette lyder måske i teorien simpelt. Uden at bruge et e-handelswebsted som f.eks. Shopify er medlemswebsites overraskende komplekse.

I denne artikel vil jeg gennemgå de beslutninger, jeg har taget, og den teknologiestak, jeg brugte til at opbygge dette nye websted, herunder:

  1. Hvordan starter man?
  2. Start af et Django-projekt
  3. Sådan opsættes Django-modeller
  4. Integrering af stribebetalinger
  5. Implementering af mit nye websted på en AWS EC2-forekomst
  6. Sådan klones CSS fra en eksisterende side

Sådan starter du?

Når du tilføjer et nyt afsnit til dit websted med et helt nyt funktionssæt, er det logisk at organisere dette websted som et underdomæne på dit oprindelige websted.

Et underdomæne er præcis, hvordan det lyder. Det er et domæne, der er en del af et andet (hoved) domæne. Underdomæner vises som et nyt afsnit af din domæne url førhoveddomæne url.

Mere specifikt:

  • Mit vigtigste domæne er: //nickmccullum.com
  • Mit nye underdomæne for kurser er: //courses.nickmccullum.com

Den største fordel ved et underdomæne er, at de er gratis! For ikke at nævne bliver et underdomæne, der er mærket til et allerede godt rangeret websted, indekseret hurtigt og drager fordel af forældrenes succes.

Jeg vidste, at jeg ville have brug for en server til at være vært for mit nye websted. Jeg bliver også nødt til at vedhæfte den server med en elastisk IP-adresse.

En elastisk IP-adresse er en statisk IP, der aldrig vil ændre sig. Dette betyder, at det er tilgængeligt af offentligheden 24/7.

Den hurtigste måde at få en server i gang i dag er at være vært for den i skyen. Der er mange muligheder for cloud computing, herunder som Amazons AWS, DigitalOcean's Droplets eller Azure's Containers. Med hensyn til prisfastsættelse er de tilgængelige indstillinger alle ret lige over hele linjen - så det har ikke været med for min beslutning for meget.

Jeg har haft tidligere erfaring med AWS (Amazon Web Services) - en skybaseret tjeneste til hosting af infrastruktur. Naturligvis valgte jeg at være vært for min server her. For at være mere specifik er jeg vært for webstedet i en EC2-forekomst. Vi vil tale mere om det senere.

Okay, så nu vidste jeg, hvor jeg ville være vært for mit nye websted, hvad er det næste?

Det var tid til at tænke på tech stack til webstedet. Når du tænker på, hvilken teknologi der skal bruges til at opbygge dit websted, er det vigtigt at overveje disse hovedemner:

  1. Hvad du er dygtig til
  2. Valg af frontend og backend teknologier, der passer godt sammen
  3. Webstedets ydeevne

Du skal besvare disse spørgsmål og prøve at vælge en teknologistak, der passer til dine behov og evner. For mig er jeg mest dygtig i Python, så Django 3.0 var et naturligt valg!

Jeg havde arbejdet på en Django-app før (Passiv), så jeg var stort set fortrolig med infrastrukturen. Jeg havde dog aldrig bygget et Django-projekt fra bunden.

På grund af dette havde jeg noget at læse. Da jeg lærte mere om denne populære ramme, fortsatte jeg med at sammenligne den med PHP, det populære webprogrammeringsværktøj. Jeg har tidligere arbejdet på flere Wordpress-sider, og Wordpress er bygget på PHP, så dette var en naturlig sammenligning (i det mindste for mig).

Ifølge deres dokumentation og forskellige indlæg på Stackoverflow er her de største forskelle mellem Django-rammen og de store PHP-rammer:

  • Django er som standard mere fokuseret på sikkerhed og leverer indbygget sikkerhedspraksis for at hjælpe programmører med at spare tid under udviklingen.
  • Django er fokuseret på hastighed. Det er kendt som en ramme, der hjælper udviklere med at få deres sidder væk fra jorden så hurtigt som muligt.
  • Django har marginalt lavere ydeevne sammenlignet med de fleste PHP-baserede rammer.

Jeg vil gerne berøre det sidste punkt. Python er et fortolket sprog og er ofte forbundet med en lavere ydelse end andre programmeringssprog. Når en ny programmør hører noget som dette, tror de måske, at Python er meget værre end andre sprogvalg på grund af vigtigheden af ​​ydeevne i computing.

Selvom Python har lavere præstationsstandarder sammenlignet med andre sprog, er dette en yderst vag udsagn. Faktisk er forskellen mellem Django og Laravel (en populær PHP-baseret ramme) så lille, at den betragtes som ubetydelig.

For at denne præstationsforskel skal være vigtig for dig, skal du skrive en ydeevneafhængig applikation med millioner af brugere. Jeg blev opfordret til at høre, at mange af verdens største webapplikationer er bygget på Django. Sagt forskelligt, hvis Django er god nok til Instagram, så var den bestemt performant nok til mit websted.

Til sidst besluttede jeg at bygge mit kursuswebsted ved hjælp af Django, primært fordi jeg har erfaring med Python. At lære en ny webramme var en god bonus.

Derefter vidste jeg, at jeg havde brug for en database til dette websted. Efter at have erfaring med MySQL og PostgreSQL skulle jeg oprindeligt ty til at bruge det igen her. Dog leveres Django som standard med en SQLite3-databasetjeneste, der kræver minimal opsætning. Jeg har aldrig brugt SQLite, så jeg undersøgte mere.

Baseret på ydeevne og datalagringsbehov ville standard SQLite3-databasen, der blev leveret med Django, være mere end kraftig nok til mit websted. Jeg var chokeret over, at en lettere version af en databasetjeneste kunne være så kraftig!

For alle, der ikke er fortrolige med denne teknologi (som jeg var), er SQLite3 en relationsdatabase med god ydeevne for websteder med lave til mellemstore trafikniveauer (~ 100K hits pr. Dag). SQLite3 kan køres på samme server som hjemmesiden uden at påvirke ydeevnen. Dette betyder, at jeg ikke behøvede at spinde en separat Amazon RDS-instans op, hvilket sparer nogle penge i implementeringsfasen.

Start af et Django-projekt

Django is a high-level python web framework with the main goal of allowing rapid development and providing security by default. It takes care of many hassles of web development, reducing repetitive coding practices.

One of the best parts of using Django is that it is absolutely free.

Django is designed to help developers get their websites off the ground quickly (which is one of the main reasons I chose to use it for this project). One of my favourite features of this framework (as with most others) is their frontend templating system.

Django Templates allow you to write dynamic code which then generates the desired HTML and CSS. This gives you the ability to use structures such as loops and if statements in order to create dynamic HTML code (meaning it renders differently for each user) that can then be served as a static file.

For example:

# course_titles_template.html {% for course in courses_list %} 

{{ course.course_title }}

{% endfor %}

Would create a heading for every course variable found in the courses_list object. This could would render an HTML file with an

tag that contains the title of each course, like this:

Python Fundamentals

Advanced Python for Finance and Data Science

How to Run Python Scripts

How to Make A Python Class

The templating system saves you from a lot of manual labor. Allowing the HTML to render dynamically saves you the headaches of updating your code every time you add a new object.

This templating system also allows the web app to update over time as I add more content. So in this case if I were to add a new course to my database, this template would not need to be changed. It would simply render my new course’s title in a new heading tag.

Django also makes it extremely easy to get started in a project. Once you have Django installed, you are able to use the django-admin in order to start a project and even set up your apps.

Hang on a second, apps? Projects? What’s the difference?

An app is a web application that performs some functionality. It can be a blog, a login system, or even a file server. A project is a collection of apps and configurations which together form a website.

Installing Django:

The simplest way to install is with pip, the Python package manager.

python -m pip install Django

For en komplet installationsvejledning, se Djangos officielle dokumentation.

Start af et projekt:

Når du har installeret Django, har du adgang til django-adminværktøjet, som hjælper udviklere med at oprette projekter og apps og også giver andre praktiske værktøjer.

Kørsel   django-admin startproject myprojectopretter en ny mappe i det aktuelle bibliotek, hvor dit projekt skal bo. Det vil også oprette mange af de nødvendige filer, du har brug for for at komme i gang.

Sådan ser din mappe ud, når du har kørt denne kommando:

minprojekt /

   manage.py

   mit projekt /

       __init__.py

       settings.py

       urls.py

       asgi.py

       wsgi.py

Inside the myproject folder you will find a manage.py file, which is extremely useful and provides many handy utilities. There will be another folder named myproject which will be where you set your configurations for the project.

The outer myproject/ root directory is a container for your project, its name doesn’t actually matter and if you find this confusing you can rename it to anything you like.

The inner myproject/ directory is the actual Python package for your project. Its name is the Python package name you’ll need to use to import anything inside it.

The important files to note here are the myproject/settings.py, where your Django and app specific settings are configured, and the myproject/urls.py.

The urls.py file is used to create urls within your website and point them to a location to service the request. This image does a great job explaining how Django handles requests:

Kudos to Ryan Nevius for creating such a wonderful visualization.

The myproject/urls.py file outlines the URL resolution for the entire website. Each app you add to your website will contain its own urls.py file which outlines the URL resolution within that specific app.

Now that you have a grasp on what some of those files are used for, let’s dive into getting a project started with the manager script’s commands.

En kommando, der skal bemærkes, er startappkommandoen, der bruges til at oprette en app inde i dit projekt på samme måde som du oprettede appen. python manage.py startapp myappopretter en ny mappe og nogle af de nødvendige filer til oprettelse af en ny app i dit projekt.

myapp /  

   __init__.py

   admin.py

   apps.py

   migrationer /

       __init__.py

   models.py

   tests.py

   views.py

Den største forskel her er tilstedeværelsen af ​​modeller og visningsfiler, der bruges til at definere henholdsvis databasen og frontend-funktionaliteten i appen.

Modeller er klasser, der definerer dine databasetabeller. Vi vil diskutere modeller mere detaljeret senere i denne vejledning.

Visninger styrer frontendstrukturen og funktionaliteten af ​​appen, der tager en webanmodning tilbage og returnerer et websvar.

Sandsynligvis den vigtigste kommando at huske er kommandoen runserver:

python manage.py runserver. This will run your project on your localhost at the default port, 8000.

That’s it! With three simple steps you will see a welcome landing page showing you that the installation worked.

There is an extremely well written tutorial in Django’s Documentation providing a far more in depth walk through of starting a project. It can be found here: Starting a Project

How to set up models

Like many other web frameworks, Django has an implementation of the object-relational mapping (ORM) concept. In Django, this implementation is called models.

Models are a very important topic to understand when developing a project in Django. In there most basic form, models can be thought of as wrappers for database tables.

Said differently, a Django model is used to define your data. It contains the fields and behaviours of the data you store. Each model maps to a single table in your database and fields in your model map to fields in your database.

When writing models you have access to powerful built-in field types that do a lot of the heavy lifting for you. Forget writing SQL code manually to construct your database. You can simply write a model class and run the migration commands to have a fully functional SQL script loaded into your database.

Django offers a User Model as part of its built in authentication system which allows you to ignore the backend side of all the login/sign-up and password handling.

When designing the models for my new site I needed the following three models:

  • Profile - a wrapper class around the User model to add non-auth related information (often called a Profile Model)
  • Course - to store all the information about each course
  • Document - a model that stores information about which files are attributed to each course. I specifically wanted to upload Markdown documents, as that's how my public blog is already built

Here's an example of a model:

class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) enrolled_courses = models.ManyToManyField(Course)

A Profile Model is a useful tool for extending the functionality of the existing user model in order to store information about the user, beyond just authentication data. In my case I created a profile model named Profile to store which courses the user is enrolled in.

Here's my Course Model:

class Course(models.Model): course_title = models.CharField(max_length=200) course_description = models.CharField(max_length=500) course_price = models.DecimalField(max_digits=10, decimal_places=2)

My Course model is fairly straightforward. I only needed to store 3 pieces of information about each course for logistics while the actual content of the course is handled by the Document model.

class Document(models.Model): course = models.ForeignKey(Course,on_delete=models.PROTECT) file = models.FileField ( upload_to=markdown_upload_location, default="default.md" )

Here I take advantage of some built in python functionality, where I’m passing the function markdown_upload_location into the FileField constructor.

This function is used to determine where the file being uploaded is to be stored on the file system. Passing the function into the constructor allows the function to be run each time a new file is uploaded instead of only being run once and then the same result being used over again.

Essentially, when an admin (me) uploads a new course to the site, a new folder is created for that course and all markdown files for that course are stored there. The Document model records link those files to the course record in the database.

One thing I took away from setting up these models was how easy the process of designing my database became. Gone are the days of MySQL Workbench and ERR diagrams, or writing SQL line-by-line and executing painful updates to schemas.

Integrating Stripe Payments

Stripe is a platform used by many websites around the world to take payment from customers. It’s secure, easy to use for customers and most importantly, it’s easy for us developers to set up!

The pricing is also quite fair compared to their competition, currently sitting at 2.9% + 0.30 CAD per transaction. This pricing applies to one time payments as well as their subscription sign ups.

In order to use Stripe as a developer you must make an account and check out their developer pages to review the options. They have prebuilt checkouts, entire libraries and SDKs for building your own custom checkout. Stripe also provides preexisting plugins for web frameworks (Wordpress, Drupal, etc.)

I decided to use their Checkout tool which is a secure, Stripe-hosted payment page that allowed me to avoid having to build a payment page. This not only saves the time of developing the frontend page for collecting payment information, but also the hassle of securing the payment in the backend.

Security is a huge topic nowadays and customers are wary of where they hand out their credit card details, so for me, using Stripe was a no brainer. I store none of the users details. Instead, they are sent straight to Stripe where they can be securely handled.

With a few lines of code I was able to import Stripe’s pre-built Javascript checkout module. Here's the script tag:

Here the data-key is set to the Stripe public key, similar to any developer API key. The description is what will appear in your Stripe dashboard for the payment received and the amount is the number of cents for the purchase. This simple inclusion imports this payment page as a modal on the website:

Once a customer fills out the payment information you only need to bundle up the payment information into a request and send it to Stripe. Next, Stripe is able to process the information and approve the payment within seconds.

# Send the charge to Stripe charge = stripe.Charge.create( amount=amount, currency=currency, description=f"Payment for course: {courseTitle}", source=self.request.POST['stripeToken'] )

Deploying my new site on an EC2 instance

Once I was finished developing my new site on my localhost, I needed to find a place to deploy it. I’ve had some experience with AWS and already had an account so it made for an easy decision.

Amazon’s Elastic Compute Cloud - usually referred to as EC2 - allows for an abundance of configurations, I simply went with the most straightforward set up. More specifically, a Ubuntu machine running on a T2 Micro server would be ample performance for this site.

Setting up the server was the easiest part of deployment, I set up a server in less than 10 minutes. Next I had to attach an elastic IP address to the instance and update my DNS records in Route53 (where my domain lives).

After setting up the server I had to figure out how I was going to serve the website to visitors. I’ve had some experience in the past with Apache so that was a natural choice. It turns out that Apache and Django mesh together very well.

Django is served via its WSGI (Web Server Gateway Interface) - a fast CGI interface for Python, this is similar to PHP’s FPM if you are familiar with that. In simple terms, the WSGI is a layer between Django and the web server that acts as an interface to serve the web pages.

As you may already know, Python is normally run within a virtualenv. This creates a virtual environment where the dependencies for a particular project can live without interfering with the system’s version of python.

If you’d like to learn a bit more about virtualenv check out the Hitchhiker's Guide to Python.

Basically this is important only to configure the Apache configurations. To serve the files correctly you need to make a WSGI Daemon for your Django project like so:

# /etc/apache2/sites-available/mysite.conf: WSGIProcessGroup courses.nickmccullum.com WSGIDaemonProcess course python-path=/home/ubuntu/django/courses-website python-home=/home/ubuntu/django/courses-website-venv WSGIProcessGroup course WSGIScriptAlias / /home/ubuntu/django/courses-website/courses-website/wsgi.py  ServerName courses.nickmccullum.com 

This tells Apache to utilize the WSGI daemon in order to properly serve the files from the Django project. Once this was set up, I needed to restart Apache, wait the 24 hours it took for the DNS records to update, then - voilà:

One last step, I needed to secure my site with SSL (Secure Socket Layer). After all, I am asking people to make payments on my site, so customers will expect the site to be secured!

The simplest way to enable SSL on a site, in my opinion, is through Lets Encrypt. They offer a tool called Certbot for free, which can be enabled on your server to auto renew a server certificate and keep your server running with SSL 24/7 all year long.

It’s as simple as the following three steps:

1. Install Certbot:

sudo apt-get install certbot python3-certbot-apache

NOTE: This script will look at the ServerName setting in your apache configuration file to create the certificate so make sure you’ve set that before running it.

2. Get the certificate and tell certbot to update the apache configuration automatically:

sudo certbot --apache

3. Test the auto renewal:

sudo certbot renew --dry-run

Once you’ve configured SSL you can test to make sure the certificate was installed correctly by checking this website: //www.ssllabs.com/ssltest/.

After securing my site with SSL I opened the EC2 instance’s security rules to allow the site to be public. With my new site up and running on my EC2 instance, I am now able to securely sell my courses to customers who wish to learn about various topics in software development.

Final Thoughts

I am grateful for all of the experience I gained throughout this project, from navigating a new web framework to integrating the Stripe API – I certainly learned a lot!

Learning a new topic like Django can be overwhelming but I felt their documentation was very strong compared to others that I’ve read (erhm, AWS).

Hvis jeg skulle give et enkelt råd, ville jeg fortælle dig, at den mest værdifulde ressource med ethvert værktøj er den officielle dokumentation. Dette gælder især når det er velskrevet. Men uanset hvilket værktøj du bruger, skal du aldrig være bange for dokumenterne og vænne dig til at læse dem for at finde svar på dine problemer.

Denne artikel blev skrevet af Nick McCullum, der underviser i Python-, JavaScript- og datalogikurser på sin hjemmeside.