Twinning project analysis summary

Twinning project analysis summary

Overview

To tell the truth this time item for my increase is not large, both front-end, back-end of the experience I have in the past, for team collaboration, version control, automated CI / CD also understand. So this blog I will not achieve the primary analysis on the front and rear ends, more focus on the aspects of deployment.

Attached project experience address .

Front and rear side implementation

We've done is typical before and after the end of the separation project, first thing to do is to implement the front and rear ends of the interactive format, we used JSONthis lightweight data interchange format, specific formatting conventions are as follows:

{
  "status": "success",
  "data": interface{}
}
{
  "status": "error",
  "err_msg": "error message"
}

Next we need to do is front and rear ends were achieved, we realize the front end into the code reuse speak with the part, here we take a look at the back end. We chose the back end Pythonas the primary development tool, let's look at an example of APP acquisition process:

from flask import Flask
from flask_cors import CORS
from app.config import FlaskConfig
from app.controllers import register_routers
from app.models import connect_db


def new_flask_app() -> Flask:
    app = Flask(__name__)
    CORS(app, supports_credentials=True)

    # 添加配置文件
    app.config.from_object(FlaskConfig)

    # 注册路由
    register_routers(app)

    # 链接数据库
    connect_db(app)

    return app

Comments in the code are more detailed, do not want to talk about a lot. I have your attention in Python type annotations which a characteristic very good code so you can get tips and other IDE support.

Next, let's look at an example of each of a Model and Controller:

from app.models import db
from app.models import session_commit


class User(db.Model):
    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    username = db.Column(db.String, nullable=True)
    password = db.Column(db.String, nullable=True)

    def __init__(self, username, password):
        self.username = username
        self.password = password

    def __str__(self):
        return "User(username={})".format(self.username)

    @classmethod
    def check_password(cls, username: str):
        return cls.query.filter_by(username=username).first()

    @classmethod
    def change_password(cls, username: str, password: str):
        user = cls.query.filter_by(username=username).first()
        user.password = password
        return session_commit()

    def new_user(self):
        db.session.add(self)
        return session_commit()

Note where the class method to use, and the rest is a simple Python ORM used

  
from flask import Blueprint, request, session
from app.models.user import User
import app.utils.return_warp as warp

login_out_page = Blueprint('login_out', __name__, url_prefix='/log')


@login_out_page.route('/in', methods=['POST'])
def login():
    username = request.form.get('username')
    password = request.form.get('password')
    # 校验必须参数
    if username is None or password is None:
        return warp.fail_warp('params error')

    user = User.check_password(username=username)

    if user.password == password:
        session.clear()
        session['user'] = username
        return warp.success_warp('login success')
    else:
        return warp.fail_warp('user error')


@login_out_page.route('/out', methods=['GET'])
def logout():
    session.clear()

    return warp.success_warp('logout success')

The rest of the content is not repeated, the specific code to achieve there is no hard to understand, but also no explanation necessary.

Code multiplexing section

The main project we reuse the code of the front end portion, and optimized on the basis thereof.

It can be said of this pair programming, responsible for front-end portion of my teammates, because the front-end code reuse is when my personal project, so we have adopted Reactthis technology. My teammates now for front-end engineering approach has been greatly appreciated that, for the use of front-end workflow also conducted preliminary entry for the popular MVVM in-depth understanding of the model has.

Next, a lift React the Context example shows how the code multiplexing:

// 个人项目代码
import React, {createContext, useState} from 'react';

export const TypeContext = createContext(null);

export const TypeProvider = props => {
  let [userType, setUserType] = useState({
    name: '张三1',
    type: 1
  });

  return (
    <TypeContext.Provider value={{userType, setUserType}}>
      {props.children}
    </TypeContext.Provider>
  )
};

export const TypeConsumer = TypeContext.Consumer;

//结对项目
import React, {createContext, useState} from 'react';

export const UserContext = createContext(null);

export const TypeProvider = props => {
  const [user, setUser] = useState('');
  const [errorMessage, setErrorMessage] = useState('');

  return (
    <UserContext.Provider value={{user, setUser, errorMessage, setErrorMessage}}>
      {props.children}
    </UserContext.Provider>
  )
};

export const TypeConsumer = UserContext.Consumer;

We can see both the code is basically the same, but we need to share data is not the same, so the outside offers different the Provide .

Interested parties can learn about the principles and use of React Hooks

Deployment part

Docker

Docker is an open source software project that allows applications to be deployed in the container work under software can be automated, whereby on the Linux operating system, provide an additional layer of software abstraction, and the operating system level virtualization, automatic management mechanism. Docker resources separation mechanism in the Linux kernel, for example cgroups, as well as the name of the Linux kernel space, to create a separate container.

Our back-end project which uses Docker deployment, specific commands so you can see the Docker's official website , Dockerfile given below:

# 基础镜像
FROM python:3.7

WORKDIR /app

ADD . /app

RUN pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple

CMD ["gunicorn", "main:app", "-c", "gunicorn.conf.py"]

Nginx

Nginx web server is asynchronous frame can also be used as a reverse proxy, load balancers and HTTP caching. The software was created by Igor Saisuoyefu and in 2004 the first public release. The company of the same name was established in 2011 to provide support. March 11, 2019, Nginx company acquired by F5 Networks for $ 670 million. Nginx is a free, open source software, released under the terms of BSD-like license.

Our server port only running at 443,80 two, and the rest were deployed by Nginx anti generations:

#PROXY-START/pair
location /pair
{
    expires 12h;
    if ($request_uri ~* "(php|jsp|cgi|asp|aspx)")
    {
         expires 0;
    }
    proxy_pass http://内网IP:6000/;
    proxy_set_header Host localhost;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header REMOTE-HOST $remote_addr;
    
    add_header X-Cache $upstream_cache_status;
    add_header Cache-Control no-store;

    proxy_cache cache_one;
    proxy_cache_key $host$uri$is_args$args;
    proxy_cache_valid 200 304 301 302 1m;
}

#PROXY-END/pair

Note which can not be used because of the use Docker localhost , you must use the internal network IP , remember to set as the API server should not open the browser cache.

Guess you like

Origin www.cnblogs.com/wangjq4214/p/11601388.html