@[toc]
云端留言板基本功能
- 提交留言功能:
用户设定自己的名字为A,指定任意名字B
向B留言,记为msg,留言保存字云端 - 获取留言功能:
输入名字A,云端返回10条最新留言记录
开发流程
步骤1:新建工程cloudms
django-admin startproject cloudms
步骤2.1:新建应用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>提交留言功能区</h1>
<form action="/msggate/" method="post">
{% csrf_token %}
发送方 <input type="text" name="userA"/><br>
接收方 <input type="text" name="userB"/><br>
消息文 <input type="text" name="msg"/><br>
<input type="submit" value="留言提交"/>
</form>
<h1>获取留言功能区</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:设定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})
运行工程
python manage.py runserver
网友评论