django开发云端留言板基本框架

@[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



    
    云端留言板(1)首页


    

提交留言功能区

{% csrf_token %} 发送方
接收方
消息文

获取留言功能区

接收方

{% for line in data %} {% endfor %}
留言时间 留言来源 留言信息
{{line.time}} {{line.userA}} {{line.msg}}
#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

你可能感兴趣的:(django开发云端留言板基本框架)