Intro
backend Django:负责talk to database,提供internal API over network, e.g. 127.0.0.1/api/login/,可以附上parameter ?user=diane,consumed by frontend。Django这里提供的所有内容都是与前端talk的,它的url不对外。
frontend React:负责render website,跳转的逻辑,以及consume backend API data。
Setup
-
最外层是一个django project:
django-admin startproject project
-
project/project/settings.py
: 这个project的总设定。在settings.py
中register你的app,比如frontend, backend, 以及依赖的package, 比如rest_framework
-
project/project/urls.py
:这个project总的url指向。有admin的,(等设定后)有backend的internal api url,也有给user看的frontend url. Only points to urls of each app, let each app handle internal logic:path(‘something’, include(“backend.urls”))
-
-
开始一个backend app:
django-admin startapp backend
-
models.py
:设置你的models -
serializers.py
:api如何jsonify各种models -
views.py
:api的内部逻辑。需要哪个model的数据,要多少,怎么传回。这里的class被urls.py调用,作为views.<your-class-name>.as_view()
-
urls.py
:对内提供的api endpoint - 在
project/
中python3 manage.py runserver
。开始测试或prodution
-
-
开始一个frontend app:
django-admin startapp frontend
- 在这里手动配置React的依赖。需要用webpack帮忙generate main.js。我其实并不太懂...步骤比较复杂,详细看reference。似乎也可以用create-react-app...(那样访问的应该就是127.0.0.1:3000 hosted by react)大致步骤:
- initialize packages.json (project对npm的package dependency)的地方run
npm init -y
- npm install webpack
- config webpack dev/production build command in package.json
- npm install babel related, config
.babelrc
- npm install react related
- config
webpack.config.js
to use babel, css, file loader.
- initialize packages.json (project对npm的package dependency)的地方run
-
frontend/urls.py
: route url to views, e.g.path(‘’, views.index)
-
frontend/views.py
: handle request and render, e.g.return render(request, ‘frontend/index.html’)
-
frontend/src/components
: 所有components的js
,css
-
frontend/src/index.js
: js entry point of your frontend -
frontend/static/frontend/main.js
: generated by webpack -
frontend/templates/frontend/index.html
: html entry point of your frontend
- 在这里手动配置React的依赖。需要用webpack帮忙generate main.js。我其实并不太懂...步骤比较复杂,详细看reference。似乎也可以用create-react-app...(那样访问的应该就是127.0.0.1:3000 hosted by react)大致步骤:
网友评论