Saya Membina Kawasan Ahli di Laman Web Saya dengan Python dan Django. Inilah Yang Saya Pelajari.

Saya memutuskan sudah tiba masanya untuk menaik taraf laman web peribadi saya untuk membolehkan pengunjung membeli dan mengakses kursus saya melalui portal baru.

Secara khusus, saya mahukan tempat untuk pengunjung mendaftar untuk akaun, melihat kursus yang ada, dan membeli kursus tersebut. Setelah pengguna membeli kursus, mereka akan dapat mengakses semua kandungan kursus selama-lamanya.

Ini mungkin terdengar sederhana dalam teori. Namun, tanpa menggunakan laman web e-dagang seperti Shopify, laman keahlian sangat kompleks.

Dalam artikel ini saya akan memandu anda melalui keputusan yang saya buat dan timbunan teknologi yang saya gunakan untuk membina laman web baru ini, termasuk:

  1. Bagaimana untuk memulakan?
  2. Memulakan Projek Django
  3. Cara menyediakan model Django
  4. Mengintegrasikan Pembayaran Stripe
  5. Menyebarkan laman web baru saya pada contoh AWS EC2
  6. Cara mengklon CSS dari halaman yang ada

Bagaimana Memulakan?

Semasa menambahkan bahagian baru ke laman web anda dengan set ciri yang sama sekali baru, adalah logik untuk mengatur laman web ini sebagai subdomain dari laman web asal anda.

Subdomain adalah persis seperti apa. Ini adalah domain yang merupakan bahagian dari domain (utama) lain. Subdomain muncul sebagai bahagian baru url domain anda sebelumnyaurl domain utama.

Lebih khusus:

  • Domain utama saya ialah: //nickmccullum.com
  • Subdomain kursus baru saya ialah: //courses.nickmccullum.com

Kelebihan utama subdomain adalah mereka bebas! Belum lagi, subdomain yang ditandai ke laman web yang sudah berada di kedudukan yang baik akan diindeks dengan cepat dan mendapat keuntungan daripada kejayaan induknya.

Saya tahu bahawa saya memerlukan pelayan untuk menghoskan laman web baru saya. Saya juga perlu melampirkan pelayan itu dengan alamat IP elastik.

Alamat IP elastik adalah IP statik yang tidak akan pernah berubah. Ini bermaksud ia boleh diakses oleh orang ramai 24/7.

Cara terpantas untuk menghidupkan dan menjalankan pelayan pada masa ini adalah dengan menghosinya di awan. Terdapat banyak pilihan untuk pengkomputeran awan, termasuk sebagai Amazon AWS, DigitalOcean's Droplets, atau Azure's Containers. Dari segi harga, pilihan yang ada semuanya hampir sama - jadi itu tidak terlalu banyak mengambil keputusan.

Saya pernah mempunyai pengalaman sebelumnya dengan AWS (Amazon Web Services) - perkhidmatan berasaskan cloud untuk hosting infrastruktur. Sememangnya saya memilih untuk menghoskan pelayan saya di sini. Untuk lebih spesifik, saya menghoskan laman web ini pada contoh EC2. Kami akan bercakap lebih banyak mengenai perkara itu kemudian.

Baiklah, jadi sekarang saya tahu di mana saya mahu menjadi hos laman web baru saya, apa yang seterusnya?

Sudah tiba masanya untuk memikirkan tumpukan teknologi untuk laman web ini. Apabila memikirkan teknologi apa yang akan digunakan untuk membina laman web anda, penting untuk mempertimbangkan topik utama berikut:

  1. Apa yang anda mahir
  2. Memilih teknologi frontend dan backend yang saling bersatu
  3. Prestasi laman web

Anda harus menjawab soalan-soalan ini dan cuba memilih timbunan teknologi yang sesuai dengan keperluan dan kemampuan anda. Bagi saya, saya paling mahir dalam Python, jadi Django 3.0 adalah pilihan semula jadi!

Saya pernah menggunakan aplikasi Django sebelum ini (Passiv), jadi saya sudah biasa dengan infrastruktur. Namun, saya tidak pernah membina projek Django dari awal.

Oleh kerana itu, saya terpaksa membaca. Semasa saya mengetahui lebih lanjut mengenai rangka kerja popular ini, saya terus membandingkannya dengan PHP, alat pengaturcaraan web yang popular. Saya telah bekerja di beberapa laman web Wordpress pada masa lalu, dan Wordpress dibina berdasarkan PHP, jadi ini adalah perbandingan semula jadi (sekurang-kurangnya bagi saya).

Menurut dokumentasi mereka dan pelbagai catatan mengenai Stackoverflow, berikut adalah perbezaan utama antara kerangka Django dan kerangka kerja PHP utama:

  • Django lebih tertumpu pada keselamatan secara lalai dan menyediakan amalan keselamatan terbina dalam untuk membantu pengaturcara menjimatkan masa semasa pembangunan.
  • Django tertumpu pada kepantasan. Ia dikenali sebagai kerangka kerja yang membantu pemaju untuk duduk secepat mungkin.
  • Django mempunyai prestasi yang sedikit lebih rendah berbanding dengan kebanyakan kerangka kerja berasaskan PHP.

Saya ingin menyentuh perkara terakhir. Python adalah bahasa yang ditafsirkan dan biasanya dikaitkan dengan prestasi yang lebih rendah daripada bahasa pengaturcaraan lain. Apabila pengaturcara baru mendengar sesuatu seperti ini, mereka mungkin berfikir bahawa Python jauh lebih buruk daripada pilihan bahasa lain kerana pentingnya prestasi dalam pengkomputeran.

Walaupun Python mempunyai standard prestasi yang lebih rendah berbanding bahasa lain, ini adalah pernyataan yang sangat kabur. Sebenarnya, perbezaan antara Django dan Laravel (kerangka kerja berdasarkan PHP yang popular) sangat kecil sehingga dianggap boleh diabaikan.

Untuk perbezaan prestasi ini bagi anda, anda perlu menulis aplikasi yang sangat bergantung pada prestasi dengan berjuta-juta pengguna. Saya terdorong untuk mengetahui bahawa banyak aplikasi web terbesar di dunia dibina di Django. Dikatakan berbeza, jika Django cukup bagus untuk Instagram, sudah tentu cukup berprestasi untuk laman web saya.

Pada akhirnya saya memutuskan untuk membina laman web kursus saya menggunakan Django kerana saya mempunyai pengalaman dengan Python. Mempelajari kerangka web baru adalah bonus yang bagus.

Seterusnya, saya tahu bahawa saya memerlukan pangkalan data untuk laman web ini. Berpengalaman dengan MySQL dan PostgreSQL, pada mulanya saya akan menggunakannya lagi di sini. Walau bagaimanapun, Django menghantar lalai dengan perkhidmatan pangkalan data SQLite3 yang memerlukan penyediaan minimum. Saya tidak pernah menggunakan SQLite jadi saya membuat kajian lebih lanjut.

Berdasarkan prestasi dan keperluan penyimpanan data, pangkalan data SQLite3 lalai yang dihantar dengan Django akan lebih hebat daripada laman web saya. Saya terkejut apabila mengetahui bahawa versi perkhidmatan pangkalan data yang lebih ringan sangat hebat!

Bagi sesiapa yang tidak biasa dengan teknologi ini (seperti saya dulu), SQLite3 adalah pangkalan data hubungan dengan prestasi hebat untuk laman web dengan tahap lalu lintas yang rendah hingga sederhana (~ 100K hit sehari). SQLite3 dapat dijalankan pada pelayan yang sama dengan laman web tanpa mempengaruhi prestasi. Ini bererti bahawa saya tidak perlu mencari contoh Amazon RDS yang berasingan, yang menjimatkan sejumlah wang pada peringkat penyebaran.

Memulakan Projek Django

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

Untuk panduan pemasangan lengkap, lihat Dokumentasi Rasmi Django.

Memulakan Projek:

Setelah memasang Django, anda akan mendapat akses ke django-adminalat yang membantu pembangun menyiapkan projek dan aplikasi dan juga menyediakan alat berguna lain.

Berjalan   django-admin startproject myprojectakan membuat folder baru di direktori semasa di mana projek anda akan hidup. Ia juga akan membuat banyak fail yang diperlukan untuk meneruskannya.

Inilah rupa direktori anda setelah menjalankan perintah ini:

projek saya/

   menguruskan.py

   projek saya/

       __init__.py

       setting.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.

Satu perintah yang perlu diperhatikan adalah startappperintah yang digunakan untuk membuat aplikasi di dalam projek anda dengan cara yang sama seperti anda membuat aplikasi. python manage.py startapp myappakan membuat folder baru dan beberapa fail yang diperlukan untuk membuat aplikasi baru dalam projek anda.

myapp /  

   __init__.py

   admin.py

   apps.py

   penghijrahan /

       __init__.py

   model.py

   tests.py

   pandangan.py

Perbezaan utama di sini adalah kehadiran model dan fail pandangan, yang masing-masing digunakan untuk menentukan pangkalan data dan fungsi aplikasi.

Model adalah kelas yang menentukan jadual pangkalan data anda. Kami akan membincangkan model dengan lebih terperinci kemudian dalam tutorial ini.

Pandangan mengawal struktur frontend dan fungsi aplikasi yang menerima permintaan web dan memberikan respons web.

Mungkin arahan yang paling penting untuk diingat adalah perintah runerver:

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).

If I were to give a single piece of advice I would tell you that the most valuable resource with any tool is the official documentation. This is especially true when it’s well written. But no matter what tool you are using, never be afraid of the docs and get used to reading them in order to find answers to your problems.

This article was written by Nick McCullum, who teaches Python, JavaScript, and Data Science courses on his website.