In this column, I will occasionally share some of Django’s most cutting-edge articles, focusing on tips and lessons learned from:
- Medium
- I’m a Twitter blogger
If you are interested, please pay attention to it and give me some motivation. After all, it takes time to sort out the translation. Thank you
—
Original address:
Creating websites using React and DRF(With changes)
Original author:
Mark Winter
Translator:
In the book
Check:
In the book
Recommended: ✨✨✨
✨
In our most recent work, the architecture used to build websites was the React front end with a Django REST Framework (DRF) back end. They interact by calling the back-end API on the front end using AXIos (the front end library). We also used Redux (the front-end library) to store the global application state (which exists on the browser side). This is our preferred because it allows for complete separation of the front and back ends. The front end and back end can be developed in parallel, as long as the list of resources requested and the format of the data returned are defined in advance. This also makes it easy to create mobile apps for any future projects because they can still reuse the back-end apis.
In the remainder of this article, I’ll show you how to configure the React front end and DRF back end. Note that I assume you are already familiar with React, Redux, Django, DRF, NPM, etc. This is not a basic tutorial.
The Backend
Beyond simply installing Django and DRF and setting up the database, there isn’t much work to do on the back end
$ pip3 install django djangorestframework django-filter
$ pip3 freeze > requirements.txt
Copy the code
Yeah, we’re using Python3
Find a directory and create a Django project and Django App:
$ django-admin startproject backend
$ cd backend
$ django-admin startapp api
Copy the code
Next you should configure your database and edit your project Settings file to use it. Documentation on how to do this for your particular DB can be found on the Django website.
Or you can do nothing and create a file database for your project and directory: sqlite3.db
Finally, you should configure the DRF as described here.
Some students are confused about the authentication method of front – and – back – end separation. Let’s look at how to configure the authentication back – end separation architecture:
# file: api/urls.py
from django.conf.urls import url
from rest_framework.authtoken import views as drf_views
urlpatterns = [
url(r'^auth$', drf_views.obtain_auth_token, name='auth'),
]
Copy the code
Just to be clear, your backend/urls.py file should now look like this:
# file: backend/urls.py
from django.conf.urls import url, include
urlpatterns = [
url(r'^', include('api.urls', namespace='api', app_name='api')),
]
Copy the code
By doing this, we can let each application manage its own URL. Maybe in the future you will add more applications to backend and add them to backend/urls.py.
You now have a back-end DRF API: an endpoint called /auth that can be accessed to get an authentication token. Let’s configure a user and run the back-end server for testing.
$python3 manage.py migrate $python3 manage.py createsuperuser $python3 manage.py runServer 0.0.0.0:8000Copy the code
Remember to run migrate the first time to create your database. Then, we create a user. You can use curl to quickly test your /auth endpoint when the server is running:
$ curl -X POST -d "username=username&password=password"
http://localhost:8000/auth
Copy the code
In the process of verification, the translator found that the author neglected some details and added below
1. Add rest_framework and rest_framework. authToken to the INSTALLED_APPS configuration:
# file: backend/settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
]
Copy the code
2. Run the command to create the database required by the authentication App:
$ python manage.py migrate
Copy the code
Here, back end done
The Frontend
We used Facebook’s create-React-app scaffolding as the base for the front end. The first thing to do is install it, and then use it in the root of the project folder to create a new project.
$ npm install -g create-react-app
$ create-react-app frontend
$ cd frontend
$ yarn eject
Copy the code
Tip: You must commit all git changes before running YARN eject, because it will change your files and add directories in case you lose your previous changes
Next we install some dependencies:
$ npm install --save-dev babel-preset-es2015 babel-preset-stage-3
$ npm install --save redux redux-logger redux-persist react-redux
$ npm install --save axios react-router-dom lodash
Copy the code
For now, let’s just show the main parts of connecting the front end to the back end. Start by creating a Redux Store to hold users’ tokens for future API calls.
// file: src/store.js
import { compose, createStore, applyMiddleware } from 'redux';
import { createLogger } from 'redux-logger';
import { persistStore, autoRehydrate } from 'redux-persist';
import rootReducer from './reducers';
const store = createStore(
rootReducer,
compose(
applyMiddleware(
createLogger(),
),
autoRehydrate()
)
);
persistStore(store);
export default store;
Copy the code
Then configure the reducer of the token:
// file: src/reducers/index.js import { combineReducers } from 'redux'; import * as actionType from '.. /actions/types'; const tokenInitialState = null; const token = (state = tokenInitialState, action) => { switch(action.type) { case actionType.SET_TOKEN: return action.data; default: return state; } } const appReducer = combineReducers({ token, }) const rootReducer = (state, action) => { return appReducer(state, action); } export default rootReducer;Copy the code
Finally, configure the action (note that the code block has two different files)
// file: src/actions/index.js
import * as actionType from './types';
export const setToken = (data) => {
return {
type: actionType.SET_TOKEN,
data
}
}
// file: src/actions/types.js
export const SET_TOKEN = "SET_TOKEN";
Copy the code
With an Action, we can now dispatch the user’s token to the store after logging in. Let’s see how to log in:
// file: src/util/Auth.js import axios from 'axios'; import _ from 'lodash'; import store from '.. /store'; import { setToken } from '.. /actions' import { URL, LOGIN } from '.. /config/Api'; export function InvalidCredentialsException(message) { this.message = message; this.name = 'InvalidCredentialsException'; } export function login(username, password) { return axios .post(URL + LOGIN, { username, password }) .then(function (response) { store.dispatch(setToken(response.data.token)); }) .catch(function (error) { // raise different exception if due to invalid credentials if (_.get(error, 'response.status') === 400) { throw new InvalidCredentialsException(error); } throw error; }); } export function loggedIn() { return store.getState().token == null; }Copy the code
This code uses the AXIos POST login information to our/Auth endpoint, which will then return the token
Dispatch to our Redux store. Once that’s done, we can use our stored token to create an AXIos-based API client. Instead of having to explicitly pull the token information out of the store and insert it into payload every time), it’s easy to make other API calls from elsewhere in our React component.
// file: src/util/ApiClient.js import axios from 'axios'; import store from '.. /store'; import { URL } from '.. /config/Api'; export const apiClient = function() { const token = store.getState().token; const params = { baseURL: URL, headers: {'Authorization': 'Token ' + token} }; return axios.create(params); }Copy the code
In the last two code blocks above we refer to the following.. / config/Api documentation. It’s just a file that maps constants to an endpoint, which makes the code more readable and easier to modify. (If you feel confused, please refer to the code that the translator restored to the end of this article.)
export const URL = process.env.API_URL;
export const LOGIN = "/auth";
Copy the code
This is the code that connects our front end to our back end. You can now try using the auth.js login feature to retrieve the user identity token we created earlier. This allows you to view the setToken Redux action result by checking the redux-Logger output from the browser’s developer tools.
If the details are not clear, look directly at the source code: tmpbook/ Django-auth-with-react
—
The full text, reprint please indicate the source: zhuanlan.zhihu.com/p/33546988
If you find this kind of article useful to you, please be sure to click on it, thank you