代码改变世界

21. Blog接口开发

2019-06-12 16:44  软件测试汪  阅读(378)  评论(0编辑  收藏  举报

一般的系统由登录、增删改查所组成。我们的Blog同样如此。我们会开发登录、创建博客、删除博客、修改博客、查询博客等功能。话不多说,我们直接展开实践吧。

思路分析

  1. 创建项目。既然我们要创建一个blog,那么我们第一步肯定是创建一个django项目。
  2. 创建应用。我们上面已经学过,应用是放在django项目中的。
  3. 设计数据库。我们之前提到过MTV设计模式,其中M我们没有用到。但是在Blog系统中我们将会用到。因为我们会创建博客,所以会有数据存储。
  4. 编写视图函数V
  5. 配置URL

代码实现

1.创建项目 django-admin blog
2.创建应用 django-admin startproject article,2.blog/settings.py添加article应用,如下代码所示:

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

3.设计数据库 在article/modles.py输入如下代码:

from django.db import models

# Create your models here.
class Article(models.Model):
    title = models.CharField(max_length=10, )
    author = models.CharField(max_length=10)
    content = models.CharField(max_length=500)
date_publish = models.DateTimeField(auto_now=True)

def __str__(self):
    return self.title

备注:__str__的作用是美化打印出来的结果,使人类更方便查看。
4.新建blog数据库 打开wampserver、Navicat,新建blog数据库

5.连接本地数据库 因为我们要使用Navicat连接数据库,所以我们需要对我们的项目进行一些修改,打开settings.py文件,注释粗体部分代码,添加数据库配置代码,如下所示:

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

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.sqlite3',
#         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#     }
# }

# 新增代码
DATABASES = {
    'default':{
        'ENGINE': 'django.db.backends.mysql',
        'HOST': '127.0.0.1',
        'PORT': '3306',
        'NAME': 'blog',
        'USER': 'root',
        'PASSWORD': '',
        'OPTIONS': {
            'init_command': "SET sql_mode='STRICT_TRANS_TABLES'",
        },
    }
}

6.在.../blog/init.py 目录下添加:

import pymysql
pymysql.install_as_MySQLdb() 

7.数据库迁移 执行python manage.py makemigrations,再执行python manage.py migrate

python manage.py makemigrations 
python manage.py migrate

8.创建用户。因为我们接口实现登录的功能,所以我们需要创建用户 。

F:\新建文件夹\blog>python3 manage.py createsuperuser
Username (leave blank to use 'administrator'): admin
Email address: admin@qq.com
Password:
Password (again):
Superuser created successfully.

9.编写视图函数V,打开article/views.py,输入如下代码

from django.http import JsonResponse
from .models import Article
from django.contrib import auth



# 登录接口
def login(request):
    if request.method == 'POST':
        username = request.POST.get('username', '')
        password = request.POST.get('password', '')
        if username == '' or password == '':
            return JsonResponse({'status': 0, 'message': 'username or password null'})
        user = auth.authenticate(username=username, password=password)
        if user is not None:
            return JsonResponse({'status': 1, 'message': 'login success'})
        else:
            return JsonResponse({'status': 0, 'message': 'username or password error'})
    else:
        return JsonResponse({'status': 0, 'message': 'request type error'})

# 添加文章接口
def add_article(request):
    if request.method == 'POST':
        id = request.POST.get('id', '')
        title = request.POST.get('title', '')
        author = request.POST.get('author', '')
        content = request.POST.get('content', '')

        if id == '' or title == '' or author == '' or content == '':
            return JsonResponse({'status': 0, 'message': 'id or title or author or content null'})

        if len(title) > 10:
            return JsonResponse({'status': 0, 'message': '文章标题过长'})
        if len(author) > 10:
            return JsonResponse({'status': 0, 'message': '作者名称过长'})
        if len(content) > 500:
            return JsonResponse({'status': 0, 'message': '文章内容过长'})

        try:
            result = Article.objects.filter(id=id)
        except ValueError:
            return JsonResponse({'status': 0, 'message': "参数类型错误"})

        if result:
            return JsonResponse({'status': 0, 'message': 'article id already exists'})
        else:
            try:
                Article.objects.create(id=id, title=title, author=author, content=content)
            except BaseException as e:
                return JsonResponse({'status': 0, 'message': e})
            finally:
                data = {
                    "id": id,
                    "title": title,
                    "author": author,
                    "content": content
                }
                return JsonResponse({'status': 1, 'data': data, 'message': 'add article success'})
    else:
        return JsonResponse({'status': 0, 'message': 'request type error'})


# 修改文章接口
def modify_article(request):
    if request.method == 'POST':
        id = request.POST.get('id', '')
        title = request.POST.get('title', '')
        author = request.POST.get('author', '')
        content = request.POST.get('content', '')

        if id == '' or title == '' or author == '' or content == '':
            return JsonResponse({'status': 0, 'message': 'id or title or author or content null'})

        try:
            result = Article.objects.filter(id=id)
        except ValueError:
            return JsonResponse({'status': 0, 'message': "参数类型错误"})
        if not result:
            return JsonResponse({'status': 0, 'message': 'article not exist'})

        if len(title) > 10:
            return JsonResponse({'status': 0, 'message': '文章标题过长'})
        if len(author) > 10:
            return JsonResponse({'status': 0, 'message': '作者名称过长'})
        if len(content) > 500:
            return JsonResponse({'status': 0, 'message': '文章内容过长'})

        try:
            Article.objects.filter(id=id).update(id=id, title=title, author=author, content=content)
        except BaseException as e:
            return JsonResponse({'status': 0, 'message': e})
        finally:
            data = {
                "id": id,
                "title": title,
                "author": author,
                "content": content
            }
            return JsonResponse({'status': 1, 'data': data, 'message': 'modify article success'})
    else:
        return JsonResponse({'status': 0, 'message': 'request type error'})


# 删除文章接口
def delete_article(request):
    if request.method == 'POST':
        id = request.POST.get('id', '')
        if id == '':
            return JsonResponse({'status': 0, 'message': 'id null'})
        try:
            result = Article.objects.filter(id=id)
        except ValueError:
            return JsonResponse({'status': 0, 'message': "参数类型错误"})
        if not result:
            return JsonResponse({'status': 0, 'message': 'id not exist'})
        try:
            Article.objects.filter(id=id).delete()
        except BaseException:
            return JsonResponse({'status': 0, 'message': '删除文章失败'})
        finally:
            return JsonResponse({'status': 1, 'message': 'delete article success'})
    else:
        return JsonResponse({'status': 0, 'message': 'request type error'})


# 查询文章接口
def get_article(request):
    if request.method == 'POST':
        title = request.POST.get("title", "")
        if title == '':
            data = []
            articles = Article.objects.all()
            if articles:
                for article in articles:
                    r = {
                        "id": article.id,
                        "title": article.title,
                        "author": article.author,
                        "content": article.content
                    }
                    data.append(r)
                return JsonResponse({'status': 1, 'message': 'success', 'data': data})
        if title != '':
            data = []
            articles = Article.objects.filter(title__contains=title)
            if articles:
                for article in articles:
                    r = {
                        "id": article.id,
                        "title": article.title,
                        "author": article.author,
                        "content": article.content
                    }
                    data.append(r)
                return JsonResponse({'status': 1, 'message': 'success', 'data': data})
            else:
                return JsonResponse({'status': 0, 'message': 'query result is empty'})
    else:
        return JsonResponse({'status': 0, 'message': 'request type error'})

10.配置URL 打开blog/urls.py输入如下代码

from django.contrib import admin
from django.urls import path
from article import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('add_article', views.add_article),
    path('modify_article', views.modify_article),
    path('delete_article', views.delete_article),
    path('get_article', views.get_article),
    path('login', views.login),

]

11.启动blog 在manage.py同级目录,输入python manage.py runserver

F:\新建文件夹\blog>python manage.py runserver
Performing system checks...

System check identified no issues (0 silenced).
March 04, 2019 - 13:25:31
Django version 2.1.4, using settings 'blog.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.