@[toc]
云端留言板基本功能
- 提交留言功能:
用戶設(shè)定自己的名字為A,指定任意名字B
向B留言,記為msg毅整,留言保存字云端 - 獲取留言功能:
輸入名字A,云端返回10條最新留言記錄
開發(fā)流程
步驟1:新建工程cloudms
django-admin startproject cloudms
步驟2.1:新建應(yīng)用msgapp
python manage.py startapp msgapp
步驟2.2:增加模板现柠,即顯示界面的HTML/CSS/JS代碼谤饭,配置路徑
#cloudms/magapp/templates/MsgingleWeb.html
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8">
<title>云端留言板(1)首頁</title>
</head>
<body>
<h1>提交留言功能區(qū)</h1>
<form action="/msggate/" method="post">
{% csrf_token %}
發(fā)送方 <input type="text" name="userA"/><br>
接收方 <input type="text" name="userB"/><br>
消息文 <input type="text" name="msg"/><br>
<input type="submit" value="留言提交"/>
</form>
<h1>獲取留言功能區(qū)</h1>
<form action="/msggate/" method="get">
接收方 <input type="text" name="userC"/><br>
<input type="submit" value="留言獲取"/>
</form>
<table borader="1">
<thead>
<th>留言時間</th>
<th>留言來源</th>
<th>留言信息</th>
</thead>
<br>
<tbody>
{% for line in data %}
<tr>
<td> {{line.time}}</td>
<td align="center">{{line.userA}}</td>
<td>{{line.msg}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>
#setting.py
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,"msgapp/templates")],
'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',
],
},
},
]
步驟2.3:設(shè)定URL路由止毕,本地路由和全局路由
#msgapp/urls.py
from django.urls.resolvers import URLPattern
from . import views
urlpatterns = [
path('',views.magproc),
#cloudms/urls.py
from django.contrib import admin
from django.urls import include,path
urlpatterns = [
path('msggate/',include('msgapp.urls')),
path('admin/', admin.site.urls),
]
步驟2.4 編寫交互代碼
#msgapp/views.py
from django.shortcuts import render
from datetime import datetime
# Create your views here.
def msgproc(request):
datalist = []
if request.method == "POST":
userA = request.POST.get("userA",None)
userB = request.POST.get("userB",None)
msg = request.POST.get("msg",None)
time = datetime.now()
with open("msgdata.txt","a+") as f:
f.write("{}--{}--{}--{}--\n".format(userB,userA,msg,time.strftime("%Y-%m-%d %H:%M:%S")))
if request.method =="GET":
userC = request.GET.get("userC",None)
if userC != None:
with open("msgdata.txt","r") as f:
cnt = 0
for line in f:
linedata = line.split('--')
if linedata[0] == userC:
cnt = cnt + 1
d = {"userA":linedata[1], "msg":linedata[2],"time":linedata[3]}
datalist.append(d)
if cnt >= 10:
break
return render(request, "MsgSingleWeb.html",{"data":datalist})
運(yùn)行工程
python manage.py runserver