Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to develop RESTful API for Django to add, delete, modify and check

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this article "Django how to develop RESTful API to achieve additions, deletions, changes and queries", so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "Django how to develop RESTful API to achieve additions, deletions, changes and queries" article.

Create a new Django project:

Django-admin.py startproject myDjango

Catalogue introduction

MyDjango/ ├── manage.py # manage files └── myDjango # Project directory ├── _ _ init _ _ .py ├── settings.py # configuration file ├── urls.py # routing-- > correspondence between URL and function └── wsgi.py # runserver command to do simple web server using wsgiref module

Use rest_framework

Add to the setting.py:

INSTALLED_APPS = [... 'rest_framework']

Connect to MySQL database

Set up in setting.py:

DATABASES = {'default': {' ENGINE': 'django.db.backends.mysql',' NAME': 'bigdatatest',' USER': 'root',' HOST': '127.0.0.1,' PASSWORD': '1009,' PORT': 3306, 'OPTIONS': {' charset': 'utf8mb4'},}}

Add to _ _ init__.py:

Import pymysqlpymysql.version_info = (1,4,13, "final", 0) pymysql.install_as_MySQLdb ()

Create a new app

Python manage.py startapp users

Catalogue introduction:

Users/ ├── migrations # is used to define a declaration file that references the migration function ├── _ _ init _ _ .py ├── _ _ init _ .py ├── admin.py # administrative site model. The default is the empty ├── apps.py # application information definition file. In which the class Appconfig is generated, which is used to define Meta data such as the application name, ├── models.py # add the model layer data class file ├── tests.py # test code file └── views.py # define the URL response function

Add to the setting.py:

INSTALLED_APPS = [... 'users']

Generate the corresponding model from the tables in the database

Python manage.py inspectdb

Copy the model of our table to models.py under users

From django.db import modelsclass User (models.Model): id = models.IntegerField (primary_key=True) name = models.CharField (max_length=255, blank=True, null=True) age = models.IntegerField (blank=True, null=True) class Meta: managed = False db_table = 'user'

Create a serialized Serializer class so that it can be converted to some form of representation such as json

In the users directory, create the file serializers.py

From rest_framework import serializersfrom users.models import Userclass UserSerializer (serializers.ModelSerializer): class Meta: model = User fields = "_ _ all__"

Data output

Write views.py under users

From _ future__ import unicode_literalsfrom rest_framework.decorators import api_viewfrom rest_framework.response import Responsefrom user.models import Userfrom user.serializers import UserSerializer@api_view (['GET']) def getlist (request): # get all data if request.method = =' GET': users = User.objects.values ('id',' name', 'age'). Distinct () serializer = UserSerializer (users) Many=True) return Response (serializer.data) @ api_view (['GET']) def getlistpic (request): # find a single piece of data based on id [' id'] if id is not None: users = User.objects.filter (id=id) serializer = UserSerializer (users) Many=True) return Response (serializer.data) else: return Response (str ('please send id')) @ api_view ([' POST']) def addUser (request): # add data ser = UserSerializer (data=request.data) if ser.is_valid (): ser.save () return Response (ser.data) return Response (ser.errors) @ api_view (['GET']) def deleteUser (request) ): # add and delete id= request.GET ['id'] if id is not None: if User.objects.filter (id=id): User.objects.get (id=id). Delete () return Response (str (' success')) else: return Response (str ('no id')) else: return Response (str ('Please) Id') @ api_view (['POST']) def updateUser (request): # modify data if User.objects.filter (id=request.data [' id']) according to id: user = User.objects.get (id=request.data ['id']) ser = UserSerializer (instance=user) Data=request.data) # Note the specified parameter if ser.is_valid (): ser.save () return Response (str ('success')) return Response (ser.errors) return Response (str (' without this id'))

Set up in urls.py:

From django.conf.urls import urlfrom users import views as users_viewsurlpatterns = [url (r'^ getlistpic', users_views.getlistpic, name='home'), url (r'^ getlist', users_views.getlist, name='home'), url (r'^ addUser', users_views.addUser, name='home'), url (r'^ deleteUser', users_views.deleteUser, name='home'), url (r'^ updateUser', users_views.updateUser, name='home')]

Start the project:

Python manage.py runserver 127.0.0.1 python manage.py runserver 8000 is about "how to develop RESTful API to add, delete, modify and query". I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report