2024年5月1日 星期三

在pythonanywhere設計Django網站的登入功能

延續文章:在pythonanywhere設計Django網站的卡片(Card)功能(新增For Template)

1.修改mysite/urls.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
"""mysite URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from myapp.views import index, vegetable, fruit, post1, post2, edit, login, logout, register

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index),
    path('index/', index),
    path('vegetable/', vegetable),
    path('fruit/', fruit),
    path('post1/', post1),
    path('post2/', post2),
    path('edit/<int:id>/',edit),
    path('edit/<int:id>/<str:mode>', edit), # 由 edit.html 按 送出 鈕
    path('login/', login),
    path('logout/', logout),
    path('register/', register),
]

2.修改myapp/views.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
from django.shortcuts import render, redirect
from myapp.models import vegetableDB
from myapp.forms import PostForm
from django.contrib.auth import authenticate
from django.contrib import auth
from django.contrib.auth.models import User
from django.http import HttpResponse

# Create your views here.
def index(request):
    slide1 = {'image':'fruits01.jpg', 'active':'active', 'interval':'10000', 'title':'水果01', 'subtitle':'好水果在雲林'}
    slide2 = {'image':'fruits02.jpg', 'active':'', 'interval':'2000', 'title':'水果02', 'subtitle':'好水果在雲林'}
    slide3 = {'image':'fruits03.jpg', 'active':'', 'interval':'3000', 'title':'水果03', 'subtitle':'好水果在雲林'}
    slides = [slide1, slide2, slide3]
    if 'login' in request.session:
        login = request.session['login']
    else:
        login = 0
    return render(request, 'index.html', locals())

def vegetable(request):
    vegetables = vegetableDB.objects.all().order_by('id')
    return render(request, 'vegetable.html', locals())

def fruit(request):
    return render(request, 'fruit.html', locals())

def post1(request):
	if request.method == "POST":
		image1 = request.POST['image']
		title1 =  request.POST['title']
		subtitle1 =  request.POST['subtitle']
		#新增一筆記錄
		unit = vegetableDB.objects.create(image=image1, title=title1, subtitle=subtitle1)
		unit.save()
		return redirect('/')
	else:
		message = '請輸入資料(資料不作驗證)'
	return render(request, "post1.html", locals())

def post2(request):  #新增資料,資料必須通過驗證
	if request.method == "POST":  #如果是以POST方式才處理
		postform = PostForm(request.POST)  #建立forms物件
		if postform.is_valid():			#通過forms驗證
			image1 = postform.cleaned_data['image'] #取得表單輸入資料
			title1 =  postform.cleaned_data['title']
			subtitle1 =  postform.cleaned_data['subtitle']
			#新增一筆記錄
			unit = vegetableDB.objects.create(image=image1, title=title1, subtitle=subtitle1)
			unit.save()
			return redirect('/')
		else:
			message = '驗證碼錯誤!'
	else:
		message = 'image, title, subtitle'
		postform = PostForm()
	return render(request, "post2.html", locals())

def edit(request,id=None,mode=None):
	if mode == "edit":  # 由 edit.html 按 submit
		unit = vegetableDB.objects.get(id=id)  #取得要修改的資料記錄
		unit.image=request.GET['image']
		unit.title=request.GET['title']
		unit.subtitle=request.GET['subtitle']
		unit.save()  #寫入資料庫
		return redirect('/vegetable/')
	else: # 由網址列
		try:
			unit = vegetableDB.objects.get(id=id)  #取得要修改的資料記錄
		except:
			message = "此 id不存在!"
		return render(request, "edit.html", locals())

def login(request):
	if request.method == 'POST':
		name = request.POST['username']
		password = request.POST['password']
		user = authenticate(username=name, password=password)
		if user is not None:
			if user.is_active:
				auth.login(request,user)
				message = '登入成功!'
				request.session['login']=1
				return redirect('/index/')
			else:
				message = '帳號尚未啟用!'
				request.session['login']=0
		else:
			message = '登入失敗!'
			request.session['login']=0
			return redirect('/index/')
	return render(request, "login.html", locals())

def logout(request):
	auth.logout(request)
	request.session['lgoin']=0
	return redirect('/index/')

def register(request):
	if request.method == 'POST':
		name = request.POST['username']
		first_name = request.POST['first_name']
		last_name = request.POST['last_name']
		password = request.POST['password']
		email = request.POST['email']
		user = authenticate(username=name, password=password)
		try:
		    user=User.objects.get(username=name)
		except:
		    user=None
		if user!=None:
		    message = user.username + " 帳號已建立!<a href='/index/'>Home</a>"
		    return HttpResponse(message)
		else:	# 建立 test 帳號
		    user=User.objects.create_user(name,email,password)
		    user.first_name=first_name
		    user.last_name=last_name
		    user.is_staff=True
		    user.save()
		    return redirect('/index/')
	return render(request, "register.html", locals())

3.修改templates/index.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<!DOCTYPE html>
<html>
<head>
  {% load bootstrap5 %}
  {% bootstrap_css %}
  {% bootstrap_javascript %}
  {% load static %}
</head>
<body>
<div id="carouselExampleInterval" class="carousel slide" data-bs-ride="carousel">
  <div class="carousel-inner">
    {% for item in slides %}:
        <div class="carousel-item {{ item.active }}" data-bs-interval= {{ item.interval }}>
            <img src="{% static 'images/' %}{{ item.image }}" class="d-block w-100" alt="...">
            <div class="carousel-caption d-none d-md-block">
                <h5 style="color:white;">{{ item.title }}</h5>
                <p style="color:white;">{{ item.subtitle }}</p>
            </div>
        </div>
    {% endfor %}
  </div>
  <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleInterval" data-bs-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Previous</span>
  </button>
  <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleInterval" data-bs-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Next</span>
  </button>
</div>

<div class="container">
  <ul class="nav bg-info">
    <li class="nav-item">
      <a class="nav-link link-light" href="/">首頁</a>
    </li>
    <li class="nav-item">
      <a class="nav-link link-light" href="/vegetable/">蔬菜</a>
    </li>
    <li class="nav-item">
      <a class="nav-link link-light" href="/fruit/">水果</a>
    </li>
    <li class="nav-item">
      {% if login  == 1 %}
        <a class="nav-link link-light" href="/logout/">登出</a>
      {% else %}
        <a class="nav-link link-light" href="/login/">登人</a>
      {% endif %}
    </li>
  </ul>
<h1>虎科小農超市</h1>

<p>虎科大是一所很重視永續發展暨社會責任的大學</p>
  {% block content %}
  {% endblock %}
</div>

</body>
</html>

4.新增 login.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<html>
<form action="." method="POST" name="form1">
    {% csrf_token %}
    <div>帳號:<input type="text" name="username" id="username"/></div>
    <div>密碼:<input type="password" name="password" id="password"/></div>
    <div>
    <input type="submit" name="button" id="button" value="登入" />
    </div>
    <span style="color:red">{{message}}</span>
</form>
<h2><a href='/register/'>註冊</a></h2>
</html>

5.新增register.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<html>
<form action="." method="POST" name="form1">
    {% csrf_token %}
    <div>帳號:<input type="text" name="username" id="username"/></div>
    <div>密碼:<input type="password" name="password" id="password"/></div>
    <div>姓氏:<input type="text" name="last_name" id="last_name"/></div>
    <div>名字:<input type="text" name="first_name" id="first_name"/></div>
    <div>Email:<input type="text" name="email" id="email"/></div>
    <div>
    <input type="submit" name="button" id="button" value="註冊" />
    </div>
    <span style="color:red">{{message}}</span>
</form>
</html>


2024年4月23日 星期二

利用pywin32套件來操作Words, Excel, PowerPoint

1.讀取Words檔案,顯示內容並利用Words內建的統計功能來計算字數、字元數、頁數。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
from win32com.client import Dispatch
import os

app = Dispatch("Word.Application")
app.Visible = 1
app.DisplayAlerts = 0
docx = app.Documents.Open(os.getcwd()+"\\test.docx")
print('段落數: ', docx.Paragraphs.count)
print('文章內容: ')
for i in range(len(docx.Paragraphs)):
    para = docx.Paragraphs[i]
    print(para.Range.text)
words = app.ActiveDocument.ComputeStatistics(0)
chars = app.ActiveDocument.ComputeStatistics(3)
pages = app.ActiveDocument.ComputeStatistics(2)
print('字數統計:', words)
print('字元統計:', chars)
print('頁數統計:', pages)
docx.Close()
app.Quit()

執行結果:
段落數:  3
文章內容: 
國立虎尾科技大學 (英文:National Formosa University),簡稱虎科、虎科大、虎尾科大、NFU,別稱國立福爾摩沙大學,位於雲林縣虎尾鎮的國立科技大學。前身為雲林工專,為昔日三大工專之一。

目前設有目前有工程、管理、電機資訊、文理四個學院。為雲林國立大學聯盟以及臺灣國立大學系統成員。

(以上資料摘自維基百科)

字數統計: 137
字元統計: 161
頁數統計: 1

2. 把九九乘法表存到Excel檔案中
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from win32com.client import Dispatch
import os

app = Dispatch("Excel.Application")
app.Visible = 1
app.DisplayAlerts = 0
xlsx = app.Workbooks.Add()
sheet = xlsx.Worksheets(1)
for i in range(1,10):
    for j in range(1,10):
        sheet.Cells(i, j).Value = i*j
xlsx.SaveAs(os.getcwd()+"\\99.xlsx")
xlsx.Close(False)
app.Quit()

執行結果:

3.讀取99.xls檔案
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import win32com
from win32com.client import Dispatch
import os

app = win32com.client.Dispatch("Excel.Application")
app.Visible = 1
app.DisplayAlerts = 0
xlsx = app.Workbooks.Open(os.getcwd()+"\\99.xlsx")
sheet = xlsx.Worksheets(1)
row = sheet.UsedRange.Rows.Count
col = sheet.UsedRange.Columns.Count
for i in range(row):
    for j in range(col):
        if int(sheet.Cells(i+1, j+1).Value)<10:
            print(' ', end='')
        print(int(sheet.Cells(i+1, j+1).Value), end=' ')
    print()
xlsx.Close(False)
app.Quit()

執行結果:

4.每隔1秒鐘,自動播放1張投影片


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from win32com.client import Dispatch
import time, os

app = Dispatch("PowerPoint.Application")
app.Visible = 1
app.DisplayAlerts = 0
pptx = app.Presentations.Open(os.getcwd()+"\\test.pptx")
pptx.SlideShowSettings.Run()
for i in range(len(pptx.slides)):
    time.sleep(1)
    pptx.SlideShowWindow.View.Next()
pptx.SlideShowWindow.View.Exit()
os.system('taskkill /F /IM POWERPNT.EXE')


2024年4月22日 星期一

在Django中設定和存取Session的內容

參考資料:Python架站特訓班django最強實戰
1.在CookieSession/CookieSession/urls.py,增加set_session和get_session兩個路徑對應到函式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
"""
URL configuration for CookieSession project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from CookieSessionApp.views import index, set_cookie, get_cookie, set_session, get_session

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index),
    path('set_cookie/<str:key>/<str:value>/', set_cookie),
    path('get_cookie/<str:key>/', get_cookie),
    path('set_session/<str:key>/<str:value>/', set_session),
    path('get_session/<str:key>/', get_session),
]

2.在CookieSession/CookieSessionApp/views.py,增加set_session和get_session兩個函式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from django.shortcuts import render
from django.http import HttpResponse
import datetime

# Create your views here.

def set_cookie(request,key=None,value=None):
	response = HttpResponse('Cookie 儲存完畢!')
	response.set_cookie(key,value.encode('utf-8').decode('latin-1'))
	return response

def get_cookie(request,key=None):
	if key in request.COOKIES:
		return HttpResponse('%s : %s' %(key,request.COOKIES[key].encode('latin-1').decode('utf-8')))
	else:
		return HttpResponse('Cookie 不存在!')
	
def index(request):
	if "counter" in request.COOKIES:
		counter=int(request.COOKIES["counter"])
		counter+=1
	else:		
		counter=1
	response = HttpResponse('歡迎光臨,今日瀏覽次數:' + str(counter))		
	tomorrow = datetime.datetime.now() + datetime.timedelta(days = 1)
	tomorrow = datetime.datetime.replace(tomorrow, hour=0, minute=0, second=0)
	expires = datetime.datetime.strftime(tomorrow, "%a, %d-%b-%Y %H:%M:%S GMT") 
	response.set_cookie("counter",counter,expires=expires)
	return response

def set_session(request,key=None,value=None):
	response = HttpResponse('Session 儲存完畢!')
	request.session[key]=value
	return response
	
def get_session(request,key=None):
	if key in request.session:
		return HttpResponse('%s : %s' %(key,request.session[key]))
	else:
		return HttpResponse('Session 不存在!')	

3.測試
3.1 http://127.0.0.1:8000/set_session/name/虎尾鎮/

3.2 http://127.0.0.1:8000/get_session/name/



2024年4月21日 星期日

在Django中設定和存取Cookies中的中文字

參考資料:Python架站特訓班django最強實戰

上一篇文章:在Django中使用Cookies來計算今天瀏覽次數

想從剛從建立專案開始,務必參考上一篇文章。

1.在CookieSession/CookieSession/urls.py,增加set_cookie和get_cookie兩個路徑對應到函式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
"""
URL configuration for CookieSession project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from CookieSessionApp.views import index, set_cookie, get_cookie

urlpatterns = [
    path('admin/', admin.site.urls),
    	path('', index),
        path('set_cookie/<str:key>/<str:value>/', set_cookie),
	path('get_cookie/<str:key>/', get_cookie),
]

2.在CookieSession/CookieSessionApp/views.py,增加set_cookie和get_cookie兩個函式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from django.shortcuts import render
from django.http import HttpResponse
import datetime

# Create your views here.

def set_cookie(request,key=None,value=None):
	response = HttpResponse('Cookie 儲存完畢!')
	response.set_cookie(key,value.encode('utf-8').decode('latin-1'))
	return response

def get_cookie(request,key=None):
	if key in request.COOKIES:
		return HttpResponse('%s : %s' %(key,request.COOKIES[key].encode('latin-1').decode('utf-8')))
	else:
		return HttpResponse('Cookie 不存在!')
	
def index(request):
	if "counter" in request.COOKIES:
		counter=int(request.COOKIES["counter"])
		counter+=1
	else:		
		counter=1
	response = HttpResponse('歡迎光臨,今日瀏覽次數:' + str(counter))		
	tomorrow = datetime.datetime.now() + datetime.timedelta(days = 1)
	tomorrow = datetime.datetime.replace(tomorrow, hour=0, minute=0, second=0)
	expires = datetime.datetime.strftime(tomorrow, "%a, %d-%b-%Y %H:%M:%S GMT") 
	response.set_cookie("counter",counter,expires=expires)
	return response	

3.測試
3.1 http://127.0.0.1:8000/set_cookie/name/虎尾鎮/

3.2 http://127.0.0.1:8000/get_cookie/name/



在Django中使用Cookies來計算今天瀏覽次數

參考資料:Python架站特訓班django最強實戰


1.打開cmd建立Django專案

1.1 安裝django套件,已安裝可以省略

pip install django

1.2 建立CookieSession專案

django-admin startproject CookieSession

1.3 建立CookieSession專案的App

python manage.py startapp CookieSessionApp

1.4 啟動網站

python manage.py migrate

python manage.py runserver

1.5 打開瀏覽器,輸入127.0.0.1:8000


2. 更換預設首頁

安裝APP, CookieSession/CookieSession/settings.py,黃底字是新增部份。

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
"""
Django settings for CookieSession project.

Generated by 'django-admin startproject' using Django 4.2.3.

For more information on this file, see
https://docs.djangoproject.com/en/4.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.2/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-^9frr%qp+(f(1z0k09w&*!y8de-xk440#1aek344)w-w8gwt^m'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'CookieSessionApp',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'CookieSession.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'CookieSession.wsgi.application'


# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/

STATIC_URL = 'static/'

# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

2.2 增加首頁URL對應到index函式的路徑到CookieSession/urls.py,黃底字是新增部份。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
"""
URL configuration for CookieSession project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from CookieSessionApp.views import index

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

2.3 新增index函式到CookieSession/CookieSessionApp/views.py

1
2
3
4
5
6
7
from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(request):
	response = HttpResponse('歡迎光臨')		
	return response	

2.4 更新瀏覽器-127.0.0.1:8000內容

3.加上Cookies
3.1 修訂在CookieSession/CookieSessionApp/views.py的index函式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from django.shortcuts import render
from django.http import HttpResponse
import datetime

# Create your views here.
def index(request):
	if "counter" in request.COOKIES:
		counter=int(request.COOKIES["counter"])
		counter+=1
	else:		
		counter=1
	response = HttpResponse('歡迎光臨,今日瀏覽次數:' + str(counter))		
	tomorrow = datetime.datetime.now() + datetime.timedelta(days = 1)
	tomorrow = datetime.datetime.replace(tomorrow, hour=0, minute=0, second=0)
	expires = datetime.datetime.strftime(tomorrow, "%a, %d-%b-%Y %H:%M:%S GMT") 
	response.set_cookie("counter",counter,expires=expires)
	return response	

3.2 更新瀏覽器-127.0.0.1:8000內容

3.3 查看Cookies,在執行網頁內容中按下右鍵,選擇'檢查'功能表,再選擇應用程式,即可以查看。



2024年4月8日 星期一

Python雙迴圈基礎教材

 1.

1
2
3
4
for i in range(5):
    for j in range(i+1):
        print('*', end='')
    print()

執行結果:



2.
1
2
3
4
for i in range(5):
    for j in range(5-i):
        print('*', end='')
    print()

執行結果:



3.

1
2
3
4
5
6
7
8
for i in range(5):
    for j in range(i+1):
        print('*', end='')
    print()
for i in range(5):
    for j in range(5-i-1):
        print('*', end='')
    print()

執行結果:


4.

1
2
3
4
5
6
for i in range(5):
    for j in range(5-i-1):
        print(' ', end='')
    for j in range(i+1):
        print('*', end='')
    print()

執行結果:

5.

1
2
3
4
5
6
for i in range(5):
    for j in range(i):
        print(' ', end='')
    for j in range(5-i):
        print('*', end='')
    print()

執行結果:


6.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
for i in range(5):
    for j in range(5-i-1):
        print(' ', end='')
    for j in range(i+1):
        print('*', end='')
    print()
for i in range(5):
    for j in range(i+1):
        print(' ', end='')
    for j in range(5-i-1):
        print('*', end='')
    print()

執行結果:

7.

1
2
3
4
5
6
for i in range(5):
    for j in range(5-i-1):
        print(' ', end='')
    for j in range(i*2+1):
        print('*', end='')
    print()

執行結果:


8.

1
2
3
4
5
6
for i in range(5):
    for j in range(5-i-1):
        print(' ', end='')
    for j in range(i*2+1):
        print(str(i+1), end='')
    print()

執行結果:

9.

1
2
3
4
5
6
for i in range(5):
    for j in range(5-i-1):
        print(' ', end='')
    for j in range(i*2+1):
        print(str(j+1), end='')
    print()

執行結果: