This is my first tech blog post, and I want to start documenting and reviewing some of the things I’ve done and some of the holes I’ve stepped in. Just because something has been built doesn’t mean it can actually be said, so in a way, I see it as a combination of journaling and technical growth, and hopefully getting off to a good start.

The origin of this project is the computer network experiment at the end of the third year of college. The goal is to build an online bookstore with complete basic functions. In fact, before self-improvement do front-end work when has been more curious about the back-end and server operation, so this time simply rented a cloud server directly, from 0 to complete the whole project framework step by step to build and deploy.

The local paper

Before deploying the project to the server, the primary goal is to get the project framework up and running locally.

The MySQL database is installed locally

For details, see MySQL installation tutorial

After installing MySQL WorkBench, configure a local database connection with host 127.0.0.1 and port 3306 by default.

I’m going to go in and create a new Schema example, so I’m going to create a new database, and I’m going to call it test

Building a Django Project

First of all: who still uses vscode after getting a taste of JetBrains’ family bucket? You need to configure the Python environment. I use Anaconda to manage the Python environment. For a tutorial, see Anaconda configuring the Python Environment

New project

Install the latest Version of Pycharm and create a Django project at the top left corner of Pycharm. The project I created is bookstore. Be sure to use your Anaconda to create a virtual environment that is isolated from other Python packages. The newly created file directory should look like this:

Under the project folder:

  • manage.pyIt is a file that is used to perform a series of subsequent operations. It is very important and functions like an engine
  • The Templates folder is used to store some front-end HTML files that you don’t really need to use if you only use Django on the back end
  • The outermost bookstore folder is your project folder, and the bookstore folder one level below is your project configuration folder, which contains configuration files for the project such as Settings, WSGI, and so on. Pay attention to distinguish between project and application

Under the project configuration folder, we need to use the following files:

  • settings.pyIs the file that sets the project configuration
  • urls.pyDjangos is a file that manages routes in Django. The back-end write interface needs to be put into the front end to request routes
  • wsgi.pyIt is a file that will be used for subsequent deployment on the server. The local deployment can be ignored for the time being

Py startApp is the name of the target application. For example, if I created an application called API, it would be python manage.py startApp API. Once you’ve created your project folder you’ll have an additional application folder called API.

Then add the created application to settings.py. Find the INSTALLED_APPS property in settings.py and add the app name at the end.

ALLOW HOST allows all IP addresses to access:

Connect to MySQL database

Sqlite3 dp.sqlite3 dp.sqlite3 dP. sqlite3 dP. sqlite3 dP. sqlite3 dP. sqlite3 dP. sqlite3 dP. sqlite3 dP. sqlite3 dP. sqlite3

Again, go to settings.py and modify the Settings. Locate the DATABASES property and change the contents to

'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'test',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': '127.0. 01.',
        'PORT': '3307'}Copy the code

For example, I created a new database named test, user name and password were root and 123456, host address was 127.0.0.1, and port number was 3307

A package called PIP Install Pymysql needs to be installed

Then modify __init__.py under the project configuration folder:

import pymysql
pymysql.version_info = (1.4.0.'final'.0)
pymysql.install_as_MySQLdb()
Copy the code

Python manage.py Migrate will display the progress of each file migration if the process is correct, but it will flash very quickly. After the migration, you can check the test database on MySQL WorkBench to see if there are several tables in the database. These stores Django’s built-in user logs and so on. So we have successfully connected to the local database.

Build table

If I want to write a member login interface, then I can abstract out a simple member class, its attributes are Account (account),password (password),name (name), where Account is the key.

Going into our application folder API, you can see that there is a models.py file, which is where we build the different abstract classes.

from django.db import models

# Create your models here.

class Member(models.Model) :
    account = models.CharField(max_length=64, primary_key=True)
    password = models.CharField(max_length=64)
    name = models.CharField(max_length=64)
Copy the code

So we’ve built a Member class. Django automatically creates a table for this class in the database, without requiring you to manually enter SQL statements. Hoisting Python manage.py Makemigrations Indicates that we have updated the database, and python Manage.py migrate. SQL > alter table api_member (‘ api_member ‘);

Write the interface

Let’s start by secretly adding two pieces of data to the database’s API_member table as our elder members.

Then I’ll write my interface in views.py under the application folder API. My function name is login.

from django.http importHttpResponse JsonResponse / / incoming HTTP response methodfrom api.models import* // Import the class we have writtendef login(request) :
    print(request)
    if request.method == 'POST':
        account = request.POST.get('account'Password = request.post.get () // Get the value of the account field from the form from the front end'password')
        print(account, password)
        if Member.objects.filter(Account =account).exists(): // Checks whether an account exists in the database, wherefilterSelect user = member.objects.get (Account =account)ifuser.password ! = password:return HttpResponse('wrong')
            else:
                return HttpResponse('right')
        else:
            return HttpResponse('not exist')
Copy the code

In urls.py under your project folder, change it to the following:

from django.contrib import admin
from django.urls import path,include
from api import views asUrlpatterns = [path();'admin/', admin.site.urls),
    path('login/', api_views.login), // define an interface path named login/]Copy the code

A login/interface so that we can write well, use the command python manage. Py runserver then executes the project in the local running, too, can use the postman test our interface http://127.0.0.1:8000/login/, but not proud. Since the Vue project will most likely run with port number 8080, unlike Django, access will be prohibited if it involves cross-domain access, you need to configure CORS to handle cross-domain access

To deal with cross domain

For details, see using Django-corons-header for cross-domain handling

Set up Vue project

New project

Use WebStorm to create new projects (yes, JetBrains again)

Build the page

Using an interface

First set the initial URL in vuex to the running http://127.0.0.1/, then write the request

this.$axios.post(this.$store.state.url + 'login/', data).then(res= > {
        console.log(res);
        if(res.data === 'right') {this.$message.success('Login successful! ');
          this.$router.push({path: '/home'})
          this.$store.commit('setIdentity'.'Administrator');
        } else if(res.data === 'wrong') {
          this.$message.error('Wrong password! ')}else {
          this.$message.error('This account does not exist! ')}}}Copy the code

The local login is now complete.

Server article

Buy a cloud server first. Heard that Tencent cloud lightweight server to students have a discount, decisively buy it.

After a series of student certification and payment operation can get 27 yuan three months lightweight server, used to build the environment to practice what, there is no super value!

Then we entered the console of Tencent Cloud, and we could see the server we just bought under the page of lightweight server.

CentOS is chosen as the operating system because it is quite famous, is it also the dormitory director?

After the server with a good password, the server is really in our hands at our mercy. Open ports 8000-8001 and 8080-8081 in the firewall first, listen to me, open and done (DOGE)

Then we need to download two software locally: XShell and Xftp. After installation, open XShell and connect with our cloud server. After successful connection, XShell will be our remote desktop, and all operations of configuring the server will be carried out inside. After XShell establishes the connection, Xftp can be opened in XShell, and the files on our server can be visually manipulated.

The next step is to configure the runtime environment for our Django project. CentOS is native to python2.x, so there are many ways to update to 3.x. For details, see installing python3 in CentOS

Mysql > install mysql

Then install uWSGi and nginx:

  • pip install uwsgi
  • yum install nginx

Yum supports python2.x, which has been updated to 3.x. Yum yum yum yum yum yum yum

Next comes the endless blood and tears: config files for UWSGi and Nginx

Configuration uwsgi

First we upload the local Django project folder to the server using Xftp. My position in the project folder on the server is/djangoTest/bookstoreDjango. Go to the project folder and create a new folder called uwsgi (for uWSGi startup initialization files, etc.). The uWSgi folder should be the same as manage.py. Go to the uwsGi folder, create a new file, uwsGi.ini, and put the following contents in it:

[uwsgi]
#http = :8000
socket = 127.0.0.1:8000 
# address of your project folder on the server
chdir = /djangoTest/bookstoreDjango/ 

# WSGI in your own project
module = bookstoreDjango.wsgi 
master = true 
processes = 1 
threads = 2  # threads
max-requests = 2000 # maximum request
chmod-socket = 664
vacuum = true 
# uwsgi file storage address
stats = %(chdir)/uwsgi/uwsgi.status
pidfile = %(chdir)/uwsgi/uwsgi.pid 
daemonize = %(chdir)/uwsgi/uwsgi.log
Copy the code

A few things to note here:

  • HTTP attributes are used when using only UWSGi as the server, but we don’t use them here
  • The socket attribute is used to connect to nginx. This value must be set toA network addressSuch as127.0.0.1:8000Do not set it to the server’s public IP address!! Blood and tears…
  • The module properties arebookstoreDjango.wsgiTo go to the next levelbookstoreDjangoFolder, pointing to itwsgi.pyfile

Ini uwsGi. ini is used to start the UWSGi service in the UWSGi folder. My guess is that you’ll start it a thousand times because of that first touch, so there will be many UWSGi processes in the background.

How do I stop the UWSGi service?

First of all, can use ps aux | grep uwsgi view associated with uwsgi running process. If there is more than one item, uWSGi is running. You can use uwsgi –stop uwsgi.pid to stop the service or pkill -f uwsgi-9 to force the process to be killed.

Note that the UWSGi service must be restarted after each uwsgi.ini modification.

Configure nginx

Nginx -t: /etc/nginx/nginx.conf: /etc/nginx/nginx.conf

Edit the file, find the server field and change it to the following:

server { listen 80; Server_name 119.29.24.77; charset utf-8; Location / {# listen on the same port as uWSgi uWSgi_pass 127.0.0.1:8000; include /etc/nginx/uwsgi_params; } location /static {#uwsgi static link alias /djangoTest/collected_static/; } error_page 404 /404.html; location = /40x.html { } error_page 500 502 503 504 /50x.html; location = /50x.html { } }Copy the code

A few points to note:

  • Listen is the port number to be monitored, 80 is the default port, and the URL needs to be changed to port 80 in the subsequent Vue project
  • Server_name Changed to a public IP address
  • The uWSgi_pass property for location should be changed to the previous configurationuwsgi.iniThe same value as the socket attribute in the127.0.0.1:8000

How do I start nginx?

  • systemctl start nginxStart the
  • systemctl stop nginxstop
  • systemctl restart nginxrestart

Change the data configuration in Django

Use MySQL WorkBench to create a host for the server public IP database connection, after the configuration to create a database. Change the database parameters in Settings of your Django project configuration folder to those of your newly created database, and python manage.py Migrate.

Deploy the Vue project

Go to index.js under config and find the following fields in the build section (not dev) and change them:

// Paths
    assetsRoot: path.resolve(__dirname, '.. /dist'),
    assetsSubDirectory: 'static'.assetsPublicPath: '/'.Copy the code

Changed assetsPublicPath to ‘./’

Go to the utils.js folder under build and find the following fields and change them:

return ExtractTextPlugin.extract({
        use: loaders,
        fallback: 'vue-style-loader'.publicPath: '.. /.. / '
      })
Copy the code

A line of publicPath is added to ensure that static resources can be accessed when deployed to the server. If something doesn’t have this and uses Element-UI, ICONS will be lost.

Finally, NPM Run Build packages the Vue project. After success, a dist folder will be added to the project folder. We uploaded the DIST to the server.

Go to the nginx configuration file nginx.conf, modify it again, and add a server as follows:

server { listen 8080; #1. Which port do you want your project to run on? {root /bookstore_frontend/dist/; Dist file try_files $uri $uri/ /index.html; #4. Redirection, internal file pointing (copy)}}Copy the code

Listen do not fill in port 80, because it will crash with the previous setting. The root property under location specifies the location of the dist folder you uploaded to the server.

Now that everything is configured, it’s time to get UWSGi and Nginx up and running, and see what we can do. Since Vue is deployed on port 8080, we can access the page created by Vue by typing the server public IP address + :8080 in the browser address bar.

The function test is successful, everyone can access this IP address, I wonder if you have succeeded?

Ps: Write the last words

Because I stepped on a lot of pits in the configuration of the server, a lot of times even irritable, so I want to write a comprehensive point of the full stack framework process to help see this blog. I hope you can point out some missing points in the comments section, and I will make further improvements. Now it is 20:00 PM on December 25, 2020, let’s give the first blog to myself as a Christmas present HHH, writing this is much more interesting than writing a paper.