Python云端留言板之基本框架
1.新建一个工程cloudms。在window命令行输入命令:
django-admin startproject clouds
2.在工程cloudms中,新建一个应用msgapp。在window命令行输入命令:
python manage.py startapp msgapp
打开Pycharm,具体目录结构

3.增加模板,完成用户返回页面
在应用msgapp创建一个templates目录,在其中新建一个HTML文件MsgSingleWeb.html
html设计如下:
(1) 提交留言:提交消息方法采用post方法,并指定动作连接对应的url连接为/msggate/,发送方命名为userA,接收方命名为userB,消息命名为msg
(2)获取消息:获取消息采用get方法,使用了模板语言。获取内容展示在表格中,表格根据消息大小动态生成
<!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 border="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>
4.配置模板路径
修改settings.py文件,具体代码如下
'DIRS': [os.path.join(BASE_DIR, "msgapp/templates")],
5.增加本应用路由
在msgapp应用中,新建urls.py文件,设views中会定义一个函数msgproc()处理本地路由。具体代码如下:
from django.urls import path
from . import views
urlpatterns = [
path('', views.msgproc),
]
6.设定全局路由
在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),
]
7.编写交互代码,即编写views.py中的处理函数msgproc()
两个部分功能:
1)提交留言:使用的是request的post方法。当用户留言提交时,我们把留言保存在一个文本文件msgdata.txt里(目前不使用数据库)每一条消息,同时记录消息的获取时间,发送方、接收方、消息、时间之间使用“–”分开
2)获取留言:使用的是request的get方法。设定放回最多不多于10条
from django.shortcuts import render
from datetime import datetime
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})
8.调试运行
在windows命令行,输入命令:
python manage.py runserver
