ติดตั้ง Django

เลือกเวอร์ชันของ Python ที่จะใช้

Django versionPython versions
2.23.5, 3.6, 3.7, 3.8 (added in 2.2.8), 3.9 (added in 2.2.17)
3.13.6, 3.7, 3.8, 3.9 (added in 3.1.3)
3.23.6, 3.7, 3.8, 3.9, 3.10 (added in 3.2.9)
4.03.8, 3.9, 3.10
4.13.8, 3.9, 3.10, 3.11 (added in 4.1.3)

ดาว์นโหลดและติดตั้ง Python จาก https://www.python.org/downloads/

Python versionMaintenance status End of support Release schedule
3.11bugfix2027-10 PEP 664
3.10bugfix2026-10 PEP 619
3.9security2025-10 PEP 596
3.8security2024-10 PEP 569

ติดตั้ง Django แบบ official release

$ python3 -m pip install Django

ตรวจสอบการติดตั้ง

>>> import django
>>> print(django.get_version())
4.1.7
$ python3 -m django --version
4.1.7

WSL 2

WSL 2 ติดตั้งได้บน Windows 11 หรือ Windows 10 version 2004+ (Build 19041 and higher)

การติดตั้ง WSL 2

  1. Open PowerShell or Windows Command Prompt in administrator mode by right-clicking and selecting “Run as administrator
  2. Enter the command: wsl --install
  3. You’ll need to restart your machine following this installation process to begin using WSL.

คำสั่ง wsl --install จะติดตั้ง Ubuntu distribution เป็นค่า default แต่เราสามารถติดตั้ง Linux distributions อื่นได้

ดู Linux distribution ที่มีใน Microsoft Store ใช้คำสั่ง wsl --list --online

> wsl --list --online
The following is a list of valid distributions that can be installed.
Install using 'wsl.exe --install <Distro>'.

NAME                                   FRIENDLY NAME
Ubuntu                                 Ubuntu
Debian                                 Debian GNU/Linux
kali-linux                             Kali Linux Rolling
Ubuntu-18.04                           Ubuntu 18.04 LTS
Ubuntu-20.04                           Ubuntu 20.04 LTS
Ubuntu-22.04                           Ubuntu 22.04 LTS
OracleLinux_8_5                        Oracle Linux 8.5
OracleLinux_7_9                        Oracle Linux 7.9
SUSE-Linux-Enterprise-Server-15-SP4    SUSE Linux Enterprise Server 15 SP4
openSUSE-Leap-15.4                     openSUSE Leap 15.4
openSUSE-Tumbleweed                    openSUSE Tumbleweed

เลือก Linux distribution ที่จะติดตั้งด้วยคำสั่ง wsl --install --distribution <Distribution Name>

> wsl --install Ubuntu-22.04
Installing: Ubuntu 22.04 LTS
[======                    11.0%                           ]

หลังจาก WSL ติดตั้ง Linux distribution เสร็จ ให้ restart เครื่อง

เรียกใช้งาน installed Linux distribution ได้จาก Windows search แล้วค้นหาคำว่า Ubuntu หรือเปิด Windows Terminal แล้วเลือก Ubuntu

เมื่อเรียกใช้งานครั้งแรก จะให้ตั้ง username และ password.

เมื่อตั้งเสร็จ สามารถดูข้อมูลของ Linux distribution ที่ติดตั้งได้ด้วยคำสั่ง cat /etc/os-release

$ cat /etc/os-release
NAME="Ubuntu"
VERSION="20.04.5 LTS (Focal Fossa)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 20.04.5 LTS"
VERSION_ID="20.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=focal
UBUNTU_CODENAME=focal

Update และ upgrade packages ของ Ubuntu ด้วยคำสั่ง sudo apt update && upgrade

Visual Studio Code

ติดตั้ง WSL Extension ให้กับ Visual Studio Code

เรียก Visual Studio Code จาก command line ของ Linux (Bash) ด้วยคำสั่ง code .

File system

ถ้าอยู่ที่ Bash ใน Linux สามารถอ้างถึง drive c บน Windows ได้ที่ /mnt/c/ (mounted C drive)

ถ้าจะกลับไปที่ home directory บน Linux ได้ด้วยคำสั่ง cd ~

ถ้าอยู่ที่ PowerShell สามารถอ้างถึง home directory บน Linux ได้ด้วยคำสั่ง cd \\wsl.localhost\Ubuntu\home\<username>

ถ้าอยู่ที่ Windows File Explorer (explorer.exe) สามารถดูได้ทั้ง Windows file system (c:\) และ Linux file system (\\wsl.localhost\Ubuntu)

WSL commands

ถ้ารันจาก PowerShell หรือ Windows Command Prompt (CMD) พิมพ์คำสั่ง wsl แต่ถ้ารันจาก Bash พิมพ์คำสั่ง wsl.exe

ดูเวอร์ชันของ WSL ด้วย wsl --version

  • WSL
  • the Linux Kernel used by WSL
  • the version for WSLg, which runs Linux GUI apps
  • the version for MSRDC, which represents the Microsoft Remote Desktop Client supporting WSL
  • the versions of Direct3D and DXCore, used for graphics rendering
  • the version of Windows that you’re running
> wsl --version
WSL version: 1.1.3.0
Kernel version: 5.15.90.1
WSLg version: 1.0.49
MSRDC version: 1.2.3770
Direct3D version: 1.608.2-61064218
DXCore version: 10.0.25131.1002-220531-1700.rs-onecore-base2-hyp
Windows version: 10.0.22621.1344

อัพเดท WSL ด้วย wsl --update

ดูรายการ Linux distributions ที่มีการิดตั้งด้วย wsl --list --verbose หรือ wsl -l -v

> wsl -l -v
  NAME      STATE           VERSION
* Ubuntu    Running         2

เปลี่ยน default Linux distribution ด้วย wsl --set-default <Distribution Name>

ที่ PowerShell เปิด Bash command line ไปที่ home directory ด้วย wsl ~ หรือ เปิด Bash command line โดยยังอยู่ที่พาทเดิมด้วย wsl และออกจาก Bash ด้วย exit

ที่ Bash เรียก Windows File Explorer ให้ชี้ไปที่ current directory path ด้วย explorer.exe . (อย่าลืมพิมพ์จุดด้วย)

คำสั่งของ Ubuntu ใน WSL2

คำสั่ง systemctl ใช้ไม่ได้

$ sudo systemctl status apache2
[sudo] password for jack:
System has not been booted with systemd as init system (PID 1). Can't operate.
Failed to connect to bus: Host is down

ให้ใช้คำสั่ง service แทน

$ sudo service apache2 status

Google Cloud Command Line Interface (gcloud CLI)

ดูเวอร์ชันของ gcloud

$ gcloud version
Google Cloud SDK 334.0.0
alpha 2021.03.26
beta 2021.03.26
bq 2.0.66
core 2021.03.26
gsutil 4.60

View information about gcloud commands and other topics:

$ gcloud help

List accounts whose credentials are stored on the local system:

$ gcloud auth list
Credentialed Accounts
ACTIVE             ACCOUNT
*                  example-user-1@gmail.com
                   example-user-2@gmail.com

To set the active account, run:
    $ gcloud config set account `ACCOUNT`

List the properties in your active gcloud CLI configuration:

$ gcloud config list
[core]
account = example-user-1@gmail.com
disable_usage_reporting = False
project = example-project

View information about your gcloud CLI installation and the active configuration:

$ gcloud info

Python subprocess

ตัวอย่าง 1

echo คำว่า test1 test2 ลงไปที่ไฟล์ /tmp/out.txt

%python
import subprocess
e = 'echo "test1 test2" > /tmp/out.txt'
subprocess.call(e, shell=True)

ตัวอย่าง 2

ตั้งชื่อไฟล์ของ log เป็นวันเวลาปัจจุบัน ไว้ใต้ /tmp แล้วใส่ข้อความ Hello World! ลงไป ด้วยการ echo

%python
import datetime
import subprocess
 
run_time = datetime.datetime.now() + datetime.timedelta(hours=7)
tmp_file = '/tmp/' + run_time.strftime("%Y-%m-%dT%H:%M:%S") + '.log'
print(tmp_file) # /tmp/2023-02-21T13:23:52.log

e = f'echo "Hello World!" >> {tmp_file}'
subprocess.call(e, shell=True)

ตรวจสอบว่าได้สร้างไฟล์ขึ้นมามั๊ย

%sh ls -l '/tmp/'

ดูเนื้อหาในไฟล์

%sh cat '/tmp/2023-02-21T13:23:52.log'

ใช้ Pandas อ่าน Text file

%python
import pandas as pd

# read text file
df = pd.read_fwf('/tmp/2023-02-21T14:55:00.log')
print(type(df))
print(df)
print(df.count())

DB Browser for SQLite

DB Browser for SQLite (DB4S) is a high quality, visual, open source tool to create, design, and edit database files compatible with SQLite.

Download

sqlite3

สร้างดาต้าเบส หรือเปิดดาต้าเบส

import sqlite3
con = sqlite3.connect("tutorial.db")

เตรียม cursor

cur = con.cursor()

สร้างตาราง

cur.execute("CREATE TABLE movie(title, year, score)")

ตรวจสอบตารางที่มีจาก sqlite_master

res = cur.execute("SELECT name FROM sqlite_master")
print(res.fetchone())
# ('movie',)

insert ข้อมูล

cur.execute("""
    INSERT INTO movie VALUES
        ('Monty Python and the Holy Grail', 1975, 8.2),
        ('And Now for Something Completely Different', 1971, 7.5)
""")
con.commit()

select ข้อมูล

res = cur.execute("SELECT score FROM movie")
print(res.fetchall())

insert ข้อมูลด้วย executemany()

data = [
    ("Monty Python Live at the Hollywood Bowl", 1982, 7.9),
    ("Monty Python's The Meaning of Life", 1983, 7.5),
    ("Monty Python's Life of Brian", 1979, 8.0),
]
cur.executemany("INSERT INTO movie VALUES(?, ?, ?)", data)
con.commit()  # Remember to commit the transaction after executing INSERT.
for row in cur.execute("SELECT year, title FROM movie ORDER BY year"):
    print(row)

Verify that the database has been written to disk by calling con.close() to close the existing connection

con.close()

Tool

Apache log4net™ กับ .NET 6 BlazorServer

สร้างโปรเจ็กส์แบบ Blazor Server App

1. ทดสอบ logger

ที่ไฟล์ Pages/Counter.razor เพิ่มโค๊ด _logger.* ไว้ดูผลการ log

@page "/counter"
@inject ILogger<Counter> logger

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        logger.LogInformation("This is an INFORMATION message.");
        logger.LogWarning("This is a WARNING message.");
        logger.LogError("This is an ERROR message.");

        currentCount++;
    }
}

เปิดหน้าต่าง Output โดยไปที่เมนู View | Output

ทดลองเรียกไปที่หน้า Counter เช่น https://localhost:7180/counter แล้วดูที่หน้าต่าง Output

BlazorServerApp6.Pages.Counter: Information: This is an INFORMATION message.
BlazorServerApp6.Pages.Counter: Warning: This is a WARNING message.
BlazorServerApp6.Pages.Counter: Error: This is an ERROR message.

2. ใช้ log4net

ติดตั้ง Package log4net และ Microsoft.Extensions.Logging.Log4Net.AspNetCore

PM> NuGet\Install-Package log4net -Version 2.0.15
PM> NuGet\Install-Package Microsoft.Extensions.Logging.Log4Net.AspNetCore -Version 6.1.0

สร้างไฟล์ log4net.config

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
    <file value="log/" />
    <datePattern value="yyMMdd'Jack.log'" />
    <staticLogFileName value="false"/>
    <appendToFile value="true"/>
    <rollingStyle value="Date"/>
    <maxSizeRollBackups value="100"/>
    <maximumFileSize value="15MB"/>
    <encoding value="UTF-8"/>
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="%-5p%d{ HH:mm:ss} li:%line - [%method] %m  %n" />
    </layout>
  </appender>
  <root>
    <level value="ALL"/>
    <appender-ref ref="RollingLogFileAppender"/>
  </root>
</log4net>

แก้ไขไฟล์ Program.cs

using BlazorServerApp6.Data;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;

var builder = WebApplication.CreateBuilder(args);

ILoggerFactory _loggerFactory = (ILoggerFactory)new LoggerFactory();
_loggerFactory.AddLog4Net();
builder.Services.AddSingleton(_loggerFactory);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddSingleton<WeatherForecastService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

ทดลองเรียกหน้า Counter อีกครั้งจะได้ไฟล์ .log

Posted in C#