Django RESTFul (Application Interface)

EDITORIAL

  • A uniform interface RESTFul principle, be explained in detail below with reference to the connection
    https://www.runoob.com/w3cnote/restful-architecture.html
  • Interface view only returns Json type to the front, then json data to js, ​​js make the front page of html to deal with change

1, try to write an interface

1.1, the new django project

If you have a new good projects (including the mysql database), and can run successfully
you can skip all the contents of 1.1, 1.2 to start

1.1.1, first create a new project in pycharm in django

(Here I used python3, django2)

django 0 basis can take a look at this article, then read the following: https: //www.cnblogs.com/liqu/p/9308966.html

Remember created modify setting configuration file (DEBUG = True, ALLOWED_HOSTS = [ "*"], change the database mysql, commented csrf)

Here Insert Picture Description

1.1.2, write driver (for connecting the mysql)

Here Insert Picture Description

1.1.3 New Database

Enter the command, log database
Here Insert Picture Description

登录数据库指令:mysql -u用户名 -p密码

Here Insert Picture Description

Building a database
Here Insert Picture Description

create database 库名 charset=utf8;

1.1.4 Migration

The migration command
Here Insert Picture Description

python manage.py migrate

这里我用的是django2,所以报了错误,这个问题是django2才会出现的
Here Insert Picture Description
具体解决办法:找到下图这个base文件对应的if version下面这一行,注释掉,写个pass
Here Insert Picture Description
再次执行迁移命令,成功
Here Insert Picture Description

1.1.5、登录数据库

这里我们在pycharm里面登录,(你也可以在navicat等其他数据库软件里面登录)
Here Insert Picture Description
注意库名这里要和 1.1.3、新建数据库 里面建的库名一致
Here Insert Picture Description
然后填上用户名密码
Here Insert Picture Description
填完信息点测试连接,如上图,绿色部分打勾了,就可以点“ok”了,

如果测试失败

数据库版本问题参考:https://www.cnblogs.com/wt7018/p/11209854.html
数据库时区问题参考:https://www.cnblogs.com/wt7018/p/11209854.html

创建成功
Here Insert Picture Description

1.2、先测试一下django能否正常启动

Here Insert Picture Description

python manage.py runserver

在浏览器里面输入http://127.0.0.1:8000/,显示下面页面成功运行
Here Insert Picture Description

1.3、创建接口应用

1.3.1、创建应用Api

根据RESTFul原则,接口应用我们应该取名为“Api"

python manage.py startapp Api

Here Insert Picture Description
创建完成记得在setting里面注册Api(不注册使用models.py时可能会报错)
Here Insert Picture Description
在Api里面新建一个urls.py
Here Insert Picture Description
在根路由untitled/urls.py上添加上新建的这个urls.py

注意:这里是django2的写法,django1稍有不同

Here Insert Picture Description
在Api/urls.py加一个路由

Here Insert Picture Description
在视图里创建对应视图函数
Here Insert Picture Description

1.4、运行、访问

运行
Here Insert Picture Description
然后在 浏览器 尝试访问这个接口
Here Insert Picture Description
到这里一个简单的django接口就创建成功了

2、使用接口

2.1、使用postman工具发一个POST请求

2.1.1、下载postman(接口测试工具)

https://dl.pstmn.io/download/latest/win32

打开postman它会跳出一个注册登录页面可以直接跳过

关于postman使用教程,你可以参考这篇文章(我觉得没有太大必要,里面操作很简单)
https://www.jianshu.com/p/97ba64888894

Here Insert Picture Description

2.1.2、写一个可以接收post请求的接口

Api路由
Here Insert Picture Description
模型(models.py)
Here Insert Picture Description

from django.db import models


# Create your models here.
class Book(models.Model):
    b_name = models.CharField(max_length=32)
    b_price = models.FloatField(default=1.0)

    def to_dict(self):
        return {'id': self.id, 'b_name': self.b_name, 'b_price': self.b_price}

迁移

python manage.py makemigrations
python manage.py migrate

视图
Here Insert Picture Description

from Api.models import Book
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt


@csrf_exempt
def books(request):
    if request.method == "GET":
        pass
    if request.method == "POST":
        b_name = request.POST.get('b_name')
        b_price = request.POST.get('b_price')

        book = Book()
        book.b_name = b_name
        book.b_price = b_price
        book.save()
        data = {
            "status": 201,
            "data": book.to_dict(),
        }
        return JsonResponse(data=data)

2.1.3、打开postman发一个POST请求

先启动django

python manage.py runserver

Here Insert Picture Description
打开postman,输入对应内容
Here Insert Picture Description
点击 send 发送后出现以下截图内容表示成功
Here Insert Picture Description
也可以再数据库里查看数据插入了没有
Here Insert Picture Description

2.1.4、在linux命令窗口下也有接口测试工具

使用linux命令窗口的同学可以查看这篇文章
HTTPie的安装及使用:https://blog.csdn.net/bobey/article/details/84863380

模拟form的POST请求

http -f POST www.baidu.com b_name=‘java书籍’ b_price=20

常用操作指令:

http -f POST www.baidu.com name=name  #模拟表单提交

http -v www.baidu.com     #显示详细的请求信息
http -h www.baidu,com     #仅显示Header
http -b www.baidu.com     #仅显示Body
http -d www.baidu.com     #下载文件

http PUT www.baidu.com name=name password=pwd  #传递json类型参数(字符串)
http PUT www.baidu.com age:=28 #非字符串类型使用:=分割

http --form POST www.baidu.com name='name'    #模拟form的POST请求
http -f POST www.baidu.com/files  name='name' file@~/test.txt  #模拟form文件上传

http www.baidu.com User-Agent:Txl/1.0 'Cookie:a=b;b=c' Referer:http://www.baidu.com/
# 修改请求头,使用:分割

http -a username:password www.baidu.com   #认证
http --auth--type=digest -a user:pwd www.baidu.com  #认证

http --proxy=http:http://192.168.1.1:8080 www.baidu.com
# 使用HTTP代理

2.2、GET请求

视图
Here Insert Picture Description

    if request.method == "GET":
        book_list = Book.objects.all()
        book_list_json = []
        for book in book_list:
            book_list_json.append(book.to_dict())
        data = {
            "status": 200,
            "data": book_list_json,
        }
        return JsonResponse(data=data)

启动django
Here Insert Picture Description
在postman里面发起请求
Here Insert Picture Description

2.3、带参数的GET请求

获取某本书籍
路由:
Here Insert Picture Description
视图:
Here Insert Picture Description

@csrf_exempt
def book(request, bookid):
    if request.method == "GET":
        book_obj = Book.objects.get(pk=bookid)
        data = {
            "status": 200,
            "data": book_obj.to_dict(),
        }
        return JsonResponse(data=data)

访问
Here Insert Picture Description

2.4、带参数的DELETE请求

视图
Here Insert Picture Description
访问
Here Insert Picture Description

3, interfaces and Web butt

Create a static folder
Here Insert Picture Description
registration static
Here Insert Picture Description

3.1, the new BookList.html

First import jQuery (.js and .min.js are copied into the line)

jq下载地址:http://www.jq22.com/jquery/jquery-1.11.3.zip

Here Insert Picture Description
New BookList.htmlHere Insert Picture Description


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>书籍列表</title>
    
    // 如果你直接复制的,注意你的jquery位置和名称,可能和我这个不一致
    
    <script type="text/javascript" src="/static/js/jquery-1.9.1.js"></script>
    <script type="text/javascript">
        $(function () {
            $.getJSON("/api/books/", function (data) {
                console.log(data);
                if (data['status'] === 200) {
                    var $ul = $("ul");
                    var books = data['data'];
                    for (var i = 0; i < books.length; i++) {
                        var $li = $("<li></li>");
                        $li.html(books[i]["b_name"]);
                        $li.appendTo($ul)
                    }
                }

            });
        });

    </script>

</head>
<body>
<div id="container">
    <ul>

    </ul>
</div>
</body>
</html>

Here $ .getJSON ( "/ api / books /", ... json to get data directly from the view in the books

3.2, browser access

After running the Access Note: This is of html files directly accessed without routing assignment (html get json data submitted by jq asynchronous)
Here Insert Picture Description

Published 87 original articles · won praise 20 · views 1591

Guess you like

Origin blog.csdn.net/a__int__/article/details/103938308