• Python-Django WebAPi基本使用方法


    目的

    利用django搭建一个WebApi,实现数据库表的增删查改。
    数据传输基于Http协议,数据格式:JSON
    ORM方式进行数据库表的CRUD(增删查改)

    开发步骤

    使用pycharm专业版搭建一个django项目,File-->newProject


    专业版的使用需要注册码,网上自己下载即可

    项目与应用

    当前生成的项目只是一个框架啊,具体的实现方法在应用中

    创建应用

    python manage.py startapp apitest  #apitest是应用名

    django项目中使用应用

    settings.py配置数据库

    修改默认DATABASES

    # DATABASES = {  # 默认数据库sqlite连接
    #    'default': {
    #        'ENGINE': 'django.db.backends.sqlite3',
    #        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    #    }
    # }
    DATABASES={ # mysql连接
        'default':{
            'ENGINE':'django.db.backends.mysql',
            'NAME':'py1',  # 数据库名
            'USER':'root', # mysql用户名
            'PASSWORD':'root', # mysql密码
            'PORT':'3306',
        }
    }
    

    api的创建和调用(Activities:应用,Project1:项目名)

    Activities/models.py创建活动表

    from django.db import models
    
    # Create your models here.
    class activity(models.Model):
        # class Meta:
        #     db_table='activities_activity'
    
            id = models.AutoField(primary_key=True)
            name = models.CharField(max_length=20)
            cost = models.CharField(max_length=20)
            deposit = models.CharField(max_length=20)
            activity_price_deposit = models.CharField(max_length=20)
            toplimit = models.CharField(max_length=20)
            Statement = models.CharField(max_length=20)

    迁移文件,将models中的表添加到mysql

    python manage.py makemigrations  //生成迁移文件
    python manage.py migrate  //进行迁移

    Activities/views.py中创建5个方法的实现

    from django.shortcuts import render
    from .models import activity
    import simplejson
    import json
    
    from django.http import JsonResponse,HttpResponse,HttpRequest
    
    def reg(request:HttpRequest):
        return HttpResponse("test")
    
    def delete(request:HttpRequest):
        try:
            payload = simplejson.loads(request.body)  
            id = payload['id']
            mgr = activity.objects.get(id=id)
            mgr.delete()
            return JsonResponse({'Status': 'DeleteSuccess'})
        except Exception as e:
            return JsonResponse({'Runstatus': e.args})
    
    def update_by_id(request: HttpRequest):
        try:
            payload = simplejson.loads(request.body)
            id = payload['id']
            mgr = activity.objects.filter(id=id)
            name = payload['name']
            cost = payload['cost']
            deposit = payload['deposit']
            activity_price_deposit = payload['activity_price_deposit']
            toplimit = payload['toplimit']
            Statement = payload['Statement']
            ac = activity()
            ac.id = id
            ac.name = name
            ac.cost = cost
            ac.deposit = deposit
            ac.activity_price_deposit = activity_price_deposit
            ac.toplimit = toplimit
            ac.Statement = Statement
            ac.save()
            return JsonResponse({'Status': 'UpDateSucess'})
        except Exception as e:
            return JsonResponse({'Status': 'UpDateError'})
    
    def Select_by_id(request: HttpRequest):
        try:
            payload = json.loads(request.body)
            id = payload['id']
            mgr = activity.objects.get(id=id)
            data={
                'name': mgr.name,
                'cost': mgr.cost,
                'deposit' : mgr.deposit,
                'activity_price_deposit': mgr.activity_price_deposit,
                'toplimit': mgr.toplimit,
                'Statement': mgr.Statement
            }
            return JsonResponse(data)
        except Exception as e:
            return JsonResponse({'Runstatus':e.args})
    
    def Create(request: HttpRequest):
        try:
            payload = simplejson.loads(request.body)
            id = payload['id']
            mgr = activity.objects.filter(id=id)
            if mgr:  # 如果数据库中存在
                return JsonResponse({'Status': 'Exist'})
            else:
                name = payload['name']
                cost=payload['cost']
                deposit=payload['deposit']
                activity_price_deposit=payload['activity_price_deposit']
                toplimit=payload['toplimit']
                Statement=payload['Statement']
                ac = activity()
                ac.id = id
                ac.name = name
                ac.cost=cost
                ac.deposit=deposit
                ac.activity_price_deposit=activity_price_deposit
                ac.toplimit=toplimit
                ac.Statement=Statement
                ac.save()
                return JsonResponse({'Status': 'CreateSucess'})
    
        except Exception as e:
            return JsonResponse({'Status': 'CreateError'})

    Activities/urls.py中创建子路由(默认无此文件,需自己创建)

    from django.conf.urls import url
    from .views import reg,delete,Select_by_id,update_by_id,Create
    urlpatterns =[
        url(r'^reg$',reg),
        url(r'^delete$',delete),
        url(r'^Select_by_id$',Select_by_id),
        url(r'^update_by_id$',update_by_id),
        url(r'^Create$',Create),
    ]

    Project1/urls.py中创建路由

    urlpatterns = [
        url('admin/',admin.site.urls),  # 根目录
        url(r'^activities/',include('activities.urls')), # 指向子路由
    ]

    一般报错及解决方法

    数据库迁移异常

    数据库语句无问题时,数据迁移命令无法使用,检查一下mysql的版本

    项目下载与使用

    百度网盘链接

    链接:https://pan.baidu.com/s/1zGAy24ZonOUQJtEo4Zp2-g
    提取码:s6wr

    测试方式

    http://127.0.0.1:8000/admin

    账号:admin,密码:adminadmin

    发送Reqest请求

    http://127.0.0.1:8000/activities/Create
    内容包含:

    {
    "id":"15",
    "name":"jack",
    "cost":"123",
    "deposit":"test",
    "activity_price_deposit":"test",
    "toplimit":"test",
    "Statement":"test"
    }

  • 相关阅读:
    云端: 小软件大平台,绿色又安全 V0.9 Beta3(090722)
    Kindle 中文阅读终极优化指南
    编辑距离
    在IE中输入网址不能访问,但输入IP地址可以访问,为什么?
    英文缩写解释
    为什么有时上网速度很慢?
    常用命令
    如何使用ping命令检查网络故障
    密码的故事
    提示主机名冲突怎么办?
  • 原文地址:https://www.cnblogs.com/aqyl/p/11204917.html
Copyright © 2020-2023  润新知