In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article is to share with you about how to use Django REST framework, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
We will use django-rest to create a simple API to allow administrator users to view and edit user and group in the system.
Create a project
Create a Django project called tutorial, then launch a new application called quickstart, and find a suitable location on your computer to execute these commands.
Mkdir tutorialcd tutorial
# Create a virtual environment to isolate our package dependencies locallypython3-m venv envsource env/bin/activate # On Windows use `env\ Scripts\ activate`
# Install Django and Django REST framework into the virtual environmentpip install djangopip install djangorestframework
# Set up a new project with a single applicationdjango-admin startproject tutorial. # Note the trailing'.' Charactercd tutorialdjango-admin startapp quickstartcd..
The project directory structure is like this
$pwd/tutorial$ find... / manage.py./tutorial./tutorial/__init__.py./tutorial/quickstart./tutorial/quickstart/__init__.py./tutorial/quickstart/admin.py./tutorial/quickstart/apps.py./tutorial/quickstart/migrations./tutorial/quickstart/migrations/__init__.py./tutorial/quickstart/models.py./tutorial/quickstart/tests.py./tutorial/quickstart/views.py./tutorial/settings.py./tutorial/urls.py./tutorial/wsgi.py
The application is created in the project directory, which may seem unusual. Using the project's namespace can avoid conflicts with the names of external modules (which is beyond the scope of getting started).
Now synchronize your database:
Python manage.py migrate
We will also create an initial user named admin with a password of password123. Later, we will validate the user in the example.
Python manage.py createsuperuser-email admin@example.com-username admin
Once you have created a database and created the initial user, ready to start, open the application's directory.
Serializers
First, we will define some serializers. Let's create a new module called tutorial/quickstart/serializer .py for data representation. Serializers mainly verifies whether the data transmitted from the front end is correct and meets the requirements of the back-end interface api interface. In development, do not trust any value passed by the front end, you should check the type of the field and whether it is legal or not.
From django.contrib.auth.models import User, Groupfrom rest_framework import serializers
Class UserSerializer (serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url',' username', 'email',' groups']
Class GroupSerializer (serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ['url',' name']
Note that we are using HyperlinkedModelSerializer's hyperlink relationship here. You can also use primary keys and various other relationships, but hyperlinks are good RESTful designs.
Views
Well, we'd better write some views. Open tutorial/quickstart/views.py and start typing.
From django.contrib.auth.models import User, Groupfrom rest_framework import viewsetsfrom tutorial.quickstart.serializers import UserSerializer, GroupSerializer
Class UserViewSet (viewsets.ModelViewSet): "API endpoint that allows users to be viewed or edited." Queryset = User.objects.all () .order_by ('- date_joined') serializer_class = UserSerializer
Class GroupViewSet (viewsets.ModelViewSet): "API endpoint that allows groups to be viewed or edited." Queryset = Group.objects.all () serializer_class = GroupSerializer
Instead of writing multiple views, we group all the common behaviors into a class called viewset.
We can easily break them down into separate views if necessary, but using viewset makes the view logic well organized and very concise.
Urls
Next, let's connect to API url. In tutorial/urls.py
From django.urls import include, pathfrom rest_framework import routersfrom tutorial.quickstart import views
Router = routers.DefaultRouter () router.register (ringing usersgiving, views.UserViewSet) router.register (ringing groupsmatching, views.GroupViewSet)
# Wire up our API using automatic URL routing.# Additionally, we include login URLs for the browsable API.urlpatterns = [path ('', include (router.urls)), path ('api-auth/', include (' rest_framework.urls', namespace='rest_framework'))]
Because we are using viewset instead of views, we can automatically generate URL conf for our API by registering viewset with the router class.
Similarly, if we need more control over API URL, we can simply use a regular class-based view and explicitly write URL conf.
Finally, we include the default login and logout views in browsable API. This is optional, but it is useful if your API requires authentication and you want to use browsable API.
Pagination
Paging allows you to control how many objects are returned on each page. To enable it, add the following line to the tutorial/settings.py
REST_FRAMEWORK = {'DEFAULT_PAGINATION_CLASS':' rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 10}
Settings
Add 'rest_framework'' to the INSTALLED_APPS. The setup module will be in tutorial/settings.py
INSTALLED_APPS = [
...
'rest_framework',]
At this point, our interface code is finished, and we can test whether the written interface meets the front-end requirements.
Python manage.py runserver
Use the browser to access [http://127.0.0.1:8000/users/], and the user name and password are the admin password123 you created earlier.
See the following effect:
The above is how to use Django REST framework, the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.