LooDaHu / ARORA_General_Introduction

A simple tutorial about Django-REST-framework and Retrofit related to ARORA Project

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Welcome to Tutorial!

Hi, this is a simple tutorial related to ARORA project. In this tutorial, you will learn about how to primarily use Django-REST-framework and Retrofit2.
Due to Github does not support Style HTML with TOC. You can download the html file in this project to have a better reading experience.

Django-REST-framework

Setup

Let's start with Django-rest-framework. Before we get started, please make sure:

  1. You have a python3 on your machine. Though Python is cross-platform, I recommend you use Linux or Linux VM as your operating system.

  2. You have installed Django and Django-rest-framework on your python. If you haven't

    pip(pipenv) install django pip(pipenv) install djangorestframework

  3. Have created a Django Project properly. If you use Pycharm as your IDE, Things should be easy. If you do not use Pycharm, you can use

    django-admin startproject < YOUR_PROJECT_NAME > .

  4. Have started an application, example1.

    python3 manage.py startapp example1

  5. You have example1, example2 and rest_framework at INSTALLED_APPS list which is at < root_dir>/ djangorest_example/setting.py .

     INSTALLED_APPS = [  
     'django.contrib.admin',  
     'django.contrib.auth',  
     'django.contrib.contenttypes',  
     'django.contrib.sessions',  
     'django.contrib.messages',  
     'django.contrib.staticfiles',  
    
     'example1', 
     'rest_framework',  
    ]
    
  6. The virtual environment is recommended. No matter which way you choose, please make sure the required packages are installed on the corresponding environment. For example, if you use the virtual environment, the problem like package not found can happen when you install the packages on the original python.

Here is a tutorial could be help at set-up stage.

FIie structure and explanation

After we have done the set-up, the whole project should look like this. enter image description here

And don't forget to create serializers.py and urls.py manually inunder every application.

Now, Let's take example1, one of our created application, as an example.

graph LR
A((example1)) -- - --> B(migratrions) 
B(migrarions) -- - --> C[__init__.py]
B(migrarions) -- - --> D{Other migration files}
A((example1)) -- - --> E(__init__.py) 
A((example1)) -- - --> F(admin.py *) 
A((example1)) -- - --> L(apps.py)
A((example1)) -- - --> G(models.py *)
A((example1)) -- - --> I(serializers.py *) 
A((example1)) -- - --> K(tests.py) 
A((example1)) -- - --> J(urls.py *)
A((example1)) -- - --> H(view.py *)

Note:

  1. The file structure of the application should like this figure. And please remeber those files are vital for the application, and do not delete them casually, except migration files. And I will explain why migration files can be deleted at later content.
  2. There are five files with STAR notation need us to work on. Let's handleget into themre one by one.

Models.py

We can create our models inat models.py. There can be more than one model in the models.py, which means there can be more than one model in an application.

Basically, Django database is based on ORM, this is to say, your database structure is determined by your code in model.py.

Let's bulid our model. Click here to MODEL.PY

After we finish our code, then we do

python3 manage.py makemigrations

As you can see, there are two new files, 0001_initial.py and db.sqlite3. enter image description here

  • You can regard 0001_initial.py as the blueprint of your database. And this blueprint is based on the code in your model.pythe database.

  • db.sqlite3 is the brand new database created by the blueprint. This single file is a database, which shows the meaning of Lite.

  • We use SQLite3 as our database by default. Of course, you can use other databases you want, and your database setting is at < root_dir>/ main_application/setting.py .

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

But we haven't done yet. Let's do

python3 manage.py migrate

enter image description here

After you see a series of OK, our model and database part is done.

Note: If you have a drastic change on your models and you meet a weired and tough bug when you try to modify your database by using migrate, I do recommand you delete all migration files and db.sqlite3 thewhich is database. And try ito rebuild everything again.

Serializers.py

Now, we need a tool which is able tothat can transform our data between models and JSON format data. Django REST Framework provides serializers to do this job. What we need to do is extend the built-in serializer to fit our requirement.

Serializers allow complex data such as querysets and model instances to be converted to native Python datatypes that can then be easily rendered into JSON, XML or other content types. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

The serializers in REST framework work very similarly to Django's Form and ModelForm classes. We provide a Serializerclass which gives you a powerful, generic way to control the output of your responses, as well as a ModelSerializer class which provides a useful shortcut for creating serializers that deal with model instances and querysets.

From Django REST Framework

Let's start with our code.

Click here to SERIALIZERS.PY

views.py

Now, we are doing the core of thean application,. views.py, determines how your RESTful server responses the request.

There are different ways to write the code of this part is highly flexible. In a word, all roads lead to Rome, from low customized to highly customized. Here, I just provide a way which I think should be easy and clear.

Click here to VIEWS.PY

urls.py

Though we have done the core part of our application, but there is still no route to access our server. So, we have to set URLs upurls for our server.

REMEMBER: Do not forget to add the URLurls of the applications into the main application, The main applicationwhich should be djangorest_example in this case.

< root_dir >/ djangorest_example/ urls.py

from django.contrib import admin  
from django.urls import path, include  
  
urlpatterns = [  
    path('admin/', admin.site.urls),  
  path('', include('example1.urls')),  
]

Click here to URLS.PY

admin.py

We are alomost done. But we want our admin site knows we have a new application. So, we need a register in admin.py. Now, we can modify the content in our database at the back-end.

Click here to ADMIN.PY

Test

  1. Let's try to create a new Model1 object by using POSTMAN

  2. Oops, something is wrong here, it shows model2_id : object does not exist, which means our Model1Serializer works well at this point. Due to model2 _id is a foreign key of model1 and related to table Model2. enter image description here

  3. Let's create a new Model2 object by admin site. And try to create Model1 objecit again. enter image description here

  4. It seems works well. Let's double check it by GET. It returns the expected result. enter image description here

Summary

  • Here isare processing figure to show how it works.

GET

graph LR
request -- . --> urls.py
urls.py -- route to the method --> views.py
views.py -- . --> models.py
models.py -- find the ojbect --> Database
Database -- result back --> serializers.py
serializers.py -- serialized data/JSON --> views.py
views.py --. --> response

POST/ PUT/ PATCH

graph LR
request -- . --> urls.py
urls.py -- route to the method --> views.py
views.py -- . --> serializers.py
serializers.py -- deserialized data/Object --> models.py
models.py -- create/update the ojbect --> Database
Database -- result back success/failure --> views.py
views.py --. --> response

DELETE

graph LR
request -- . --> urls.py
urls.py -- route to the method --> views.py
views.py -- . --> models.py
models.py -- find the ojbect --> Database
Database -- result back success/failure --> views.py
views.py --. --> response
  • Building proper models is the first and key step to create a good application.

  • Typo could be a problem when you code due to there are a lot of functions accepting the string arguments and your IDE may not be able to find them in time. And theBe care of your every step, small problem, like this could waste your life. So, be careful of the details like this in your coda typo, could take much time.

Retrofit2

To be done

Contact

If you have any question about the above content, be free to contact me.

Developer: Jinming Yang Email: jy345@nau.edu Github: @LooDaHu WeChat: a651120561

This is just a simple tutorial about how to fast working on this frameworkset up, if you want to learn more and deep, please refer API GUIDE

What you know about Django is also able to use on the development when you Because Django-_RESTful framework because this _framework is based on the Django. Sometimes, if you think the built-in functions in this framework is not good to use or not fit your requirement, using Django is an alternative way to try. , if you feel not good enough for Django_REST_framework, using Django is a good option to develop your code.

About

A simple tutorial about Django-REST-framework and Retrofit related to ARORA Project


Languages

Language:HTML 100.0%