美文网首页
React + Django Part. 1 Setup

React + Django Part. 1 Setup

作者: _魔人啾啾_ | 来源:发表于2018-09-17 23:36 被阅读0次

    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

    Reference

    1. 最外层是一个django projectdjango-admin startproject project

      1. project/project/settings.py: 这个project的总设定。在settings.py中register你的app,比如frontend, backend, 以及依赖的package, 比如rest_framework
      2. 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”))
    2. 开始一个backend app: django-admin startapp backend

      1. models.py:设置你的models
      2. serializers.py:api如何jsonify各种models
      3. views.py:api的内部逻辑。需要哪个model的数据,要多少,怎么传回。这里的class被urls.py调用,作为views.<your-class-name>.as_view()
      4. urls.py:对内提供的api endpoint
      5. project/python3 manage.py runserver。开始测试或prodution
    3. 开始一个frontend app: django-admin startapp frontend

      1. 在这里手动配置React的依赖。需要用webpack帮忙generate main.js。我其实并不太懂...步骤比较复杂,详细看reference。似乎也可以用create-react-app...(那样访问的应该就是127.0.0.1:3000 hosted by react)大致步骤:
        1. initialize packages.json (project对npm的package dependency)的地方run npm init -y
        2. npm install webpack
        3. config webpack dev/production build command in package.json
        4. npm install babel related, config .babelrc
        5. npm install react related
        6. config webpack.config.js to use babel, css, file loader.
      2. frontend/urls.py: route url to views, e.g. path(‘’, views.index)
      3. frontend/views.py: handle request and render, e.g. return render(request, ‘frontend/index.html’)
      4. frontend/src/components: 所有components的js,css
      5. frontend/src/index.js: js entry point of your frontend
      6. frontend/static/frontend/main.js: generated by webpack
      7. frontend/templates/frontend/index.html: html entry point of your frontend

    相关文章

      网友评论

          本文标题:React + Django Part. 1 Setup

          本文链接:https://www.haomeiwen.com/subject/dtvjnftx.html