In my project, I have the following 4 APIs (function base API view)
save_user()
login_user()
get_user_info()
update_user()
I want to convert it into class base API view
class UserApi(APIView):
def post():
#save user
def get():
#for get user info
def put():
#for update user info
so how to use login() in class base views. OR use function base view for login?
to use a mixture of class based API view and function base API view in a single views.py file is good or bad?
CodePudding user response:
To login, the user has to provide the username and password. This will be a HTTP post request. You can create a class-based view only for post for login and define the URL endpoint.
class Login(APIView):
def post(self, request, format=None):
# authentication related code
urlpatterns = [
path('login/', Login.as_view()),
]
The main advantage of using class-based views is to separate the HTTP methods (get, post, put, delete) and write re-usable code. DRF provides generic class-based views that can be used for common functionality with less code.
For the login functionality, having a class-based view is useful if you have token based authentication. Since, you haven't mentioned about it, I would say having class-based views for both login
and user
will be good for consistency and readability. There is not rule that you can't mix class-based and function-based views; it depends on what you are trying to achieve and one is not necessarily good or bad over the other.