Django models across multiple projects/microservices. How to?

后端 未结 4 2050
旧时难觅i
旧时难觅i 2021-02-19 10:34

I\'m wondering how to solve sharing of the model structure between multiple (separated) django projects/microservices. Eg:

  1. Project: API
  2. Project: Users das
4条回答
  •  渐次进展
    2021-02-19 10:47

    Django basic idea is to couple the entire app functionality together, but this does not hold in your case. It's a style and opinion question, here is what I did in a similar situation.

    Split the app functionality into two project lairs:

    mysite
       |
       | - db_access
       |         | --- app1
       |                 | ---- models.py
       |                 | ---- db_api.py
       |         | --- app2
       |                 | ---- models.py
       |                 | ---- db_api.py
       | - service
       |         | --- app1
       |                 | ---- urls.py
       |                 | ---- views.py
       |         | --- app2
       |                 | ---- urls.py
       |                 | ---- views.py
    

    The db_access part has the models, and db_api.py has the queries, get objects etc, so you don't query the models, but the db_api.

    Instead of

    item = app1.models.Items.objects.get(user=request.user)
    

    Use

    item = app1.db_api.get_first_item(user=request.user)
    

    This style lets you share the db & models access together, while each service consumes what it needs, and then use it for API, website etc. If a service consumes some data in a way that other services don't (and will not) use, then put this query in the service code, otherwise in the db_api.py.

    This is more like a traditional laired application, but it works.

    Another thing, the same project can use two git repositories, one for the db_access (which all services pull), and one for the specific service. So each django project is actually the db_access repo, and the service repo - wsgi doesn't care, of course, if the project code comes from two repositories.

提交回复
热议问题