This is the fourth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

Previously on

Hi, I’m a cat lover and a tech lover.

Today we take you hand in hand to build a WEB service, and deploy to our cloud server, I named this article with the old table learn cloud server pilot: Owning a cloud server can be so cool. Yes, this article is not about getting started (not giving you story after story, theory after theory about cloud servers), but it is about getting started (being project oriented and sharing the whole setup process).

There will be a lot of knowledge to expand in the article and when we do the project, I hope beginners do not tangle, first follow the article to complete the replay, understand the whole project, deployment logic, and then to think about some details, so that the learning efficiency will be higher, to avoid getting into the beginning of the point ~

As mentioned above, when we write a Web application, we want to be able to show it to others. It’s even cooler if others can access it. How do we make it accessible to others? Just deploy your project to a cloud server, and that’s where the story begins.

I am also engaged in the activity of giving a cloud server these two days (has ended), there are two requirements: the user is a new user + associated with me, because the user side can not judge whether it is associated with me, so I can only look at the background one by one, to a person to log in ali Cloud once, to a person to log in once… After coming and going several times like this, I collapsed!

No, as a programmer, how can do so, I calm down, or what did not think of! Climb ali cloud background data, write a Web project, do a front-end query? It takes too long. Where is the data crawling? I’m not good at the front end either!

When I was helpless, I suddenly looked at the activity group chat message, and found that there were leaders discussing this verification problem, and leaders found the data interface (cloud ambassador associated user data interface).

And the big guy code has been written, this is also very grateful ~

Equivalent, I just need to write a back-end judgment logic and front-end display, but I am not a front-end! ?

Can’t help but worry and Google: a Beginner’s Guide to the front End?

So search to this white three days entry front-end HTML liver goods notes, can, I have three days to see the front end, can only continue to worry, you must know the story must have a turning point.

Finally, Python can write a front end, send a black question mark at the same time, quickly open a tweet, so I am smiling.

After careful reading, though not as good as the title says the Python with current end, but also about the same, a few days ago I also to share this article brother get up early, it’s not, today is to teach you how to implement the whole project process and deployment, using cloud server to do a small project together – blog page + data query ‘system’.

I can’t help feeling that life is also so twists and turns, and finally also laugh to open up how nice ~ remember to give this article a thumbs up.

Second, basic preparation

1. You need to have a cloud server (absolutely, use your local computer as a server too!)

2. If you need a domain name, you need a domain name (optional)

Project Deployment Notes:

  • Basic environment: Python 3.6 and above is acceptable
  • Third Party library:

Pipenv requests for library pandas for data processing and reading pywebio is a Web project framework

The interface data is stored in pandas. The interface data is stored in the CSV library for pandas. The interface data is stored in pandas. The framework will help render the front end of the page, allowing the writer to quickly build web projects, which is just too nice

Three, start using your head

As an example, I bought Ali Cloud ECS shared N4 (1 core 2G) 50g memory, installed ali cloud’s own research and development of Linux system, in their own server will be more smooth, of course, we can also choose other, such as the more popular Centos, a total of less than 180 years to buy, cool ah ~

3.1 Introduction to the Cloud Server

First of all, we log in ali cloud background, enter the ECS server management background, you can directly log in through the following link (the premise is that you have a cloud server oh ~).

https://ecs.console.aliyun.com/#/home
Copy the code

After entering, you can see some basic information about the server, such as name (can be changed), region, public IP, remote link, switch, CPU usage, etc

Click the instance button on the left to enter the server details page. You can see more information and Settings about the server. Here are the following Settings:

  • Password/key: You can change your server instance password or remote connection (VNC) password here, please change/set the password before connecting
  • Cloud disk and Mirror: You can reset the system and customize mirrors
  • Network and security groups: This is where you set up open ports, which are very important

3.2 Remotely Connect to the cloud server to view the basic information

We click on the remote link, will be sent ali cloud provides three remote connection:

  • Workbench remote connection (recommended, in order to learn Linux or use native is better) : the first login needs to enter the instance user name (default root) and password we set, it seems that the automatic login (may also have a certain cache period), if you do not remember the password, according to 3.1 method reset;

  • VNC remote connection: You need to enter the VNC remote connection password set by us, and also need to enter the instance user name (default root) and password, mainly used in scenarios where you cannot directly use Workbench remote connection. Same as above, if you forget it, just reset it, very simple;

  • Send remote command (cloud Assistant) : ECS official provided additional functions, always free, “no login, no jumper, batch instance operation and maintenance, execute commands (Shell, Powershell and Bat) and send files”, ECS official provided additional functions, really excellent, point a like ~

Of course, there are also bad, such as: need to input multiple commands, command relationship or content is not all I determine when it will be more troublesome, especially for white users, but the file upload will be very nice for new users.

If it is a small white user, I still suggest to choose Workbench remote connection, experienced users, according to their own habits, any link can be.

3.3 Viewing related Environment

3.3.1 System Software Management Tool: Yum

Check the package management tool yum (apt-get for Ubuntu).

yum version
Copy the code

You’ll notice there is a version, but the first line is oneFailed, happy! In the wronglocaleRepresents the runtime locale of the software, which we can input directlylocaleView related Settings,hintsLC_CTYPEWhat can’t be set to default because file/directory, so let’s just set it here, okayLC_ALLJust (the highest priority, instead of all), we willLC_ALL=en_US.UTF-8Add to system variables file/etc/profileAnd then run it again/etc/profileWe can solve this problem.

echo "export LC_ALL=en_US.UTF-8" >> /etc/profile
source /etc/profile
Copy the code

Next, let’s update yum for about half a minute

yum update -y
Copy the code

3.3.2 Network file data download tool: wget

I looked it up and it came with Aliyun Linux,The general way to use it isWget file linkThe download speed is very fast and convenient.

Wget file linkCopy the code

So first, behind can upgrade below ~

3.3.3 Programming Environment: Python (most important)

Python2.7 and Python3.6(released on December 24, 2018) are both quite old, but this experiment is still useful. To get you started, we’ll leave it to update the Python version later.

3.4 Learning Common and basic Linux Commands

Now that we know about the environment, let’s learn some common and basic Linux operations

  • 1) View the complete path of the current directory
pwd
Copy the code

You can see that we are now following the directory (/) under therootIn the directory

  • 2) Access the specified directory
cdDirectory pathCopy the code

So we go in/The root directory

  • 3) View all files in the current directory
ls
Copy the code

We can see that the system contains a lot of files, know that all the following project files are in the root directory, there is also a home directory, you may be confused, this is for ordinary users (we can create other accounts to log in).

  • 4) Create a folder
Mkdir Folder nameCopy the code

  • 5) Create a file
Touch file nameCopy the code

  • 6) Edit the file content
Name of the vim fileCopy the code

In Linux, the default encoding is UTF-8. If you change it directly, the Chinese characters will be garbled, so we need to set the. Vimrc configuration file first, and directly enter the following command:

vim ~/.vimrc
Copy the code

Press the A key to insert the input from the cursor position, copy and paste the following text, then press ESC, hold Shift+, and enter wq:

set encoding=utf-8
set fileencodings=ucs-bom,utf-8,cp936
Copy the code

This can solve the problem of editing files to input Chinese garble.

1) vim will set encoding according to the contents of ~/. Vimrc, encoding is set to vim encoding, fileencodings is set to the original fileencoding tuple, vim will probe the original fileencoding according to fileencodings set to fileencoding; 2) ViM will automatically compare encoding and FileEncoding to see if they are the same. If they are not, VIM will create a cache and change the content encoding from FileEncoding to Encoding, and users can edit normally. 3) It will be compared again when saving, and if it is inconsistent, it will change the encoding of the cache from Encoding to FileEncoding, and then store it in the file.

Reference: www.jianshu.com/p/44691357c…

Now let’s modify our readme.md. After executing this, we can go to the edit page.

vim readme.md
Copy the code

Once again, click the letterAKey (lowercase) : inserts the input content from the cursor position, enters the desired input content, and then pressesESCKey (to stop input), and then hold downShift+:(Note that it must be in the English input method state), inputwq(Save and exit)

  • 7) Check the file contents
Cat file nameCopy the code

  • 8) Delete files and folders (use with caution)
Rm File name rm -rf Folder nameCopy the code

Because now we directly login is the root user permissions users most (server), so must be careful with the rm – rf, use must be set at the back to delete the file/folder name, to avoid “delete library run road”, behind the study will teach you how to create a normal user, used for everyday use development.

  • 9) Modify/move files
Change the file/folder nameMv Old file name new name# move fileMv Directory where old files reside New directoryCopy the code

The above simple to introduce you in Linux file processing common commands, which will be very helpful to our later learning, after the relevant article will be detailed to introduce you to Linux in other commands. More support!

3.5 Project Introduction

The project is two pages that we wrote using PyWeBio. Yes, the next article will share some of the advantages of PyWeBio when building Web projects quickly, and how to use it. If you are interested, you can also go to the official documentation.

Here to tell you the main code framework, the rest because I this application scenario we can not experience, so not public, but also for you to prepare a small project, continue to read in the future have access to methods oh ~ have questions welcome comment area for learning exchange ~

Here to tell you about the main code framework, the rest because I this application scenario we can not experience, so not open, have questions can private chat I entered the learning exchange group, welcome you to ask questions in the group.

Import pyWeBio-related packages
from pywebio import *
from pywebio.input import *
from pywebio.output import *

# first_page: Blog display page
def activity_introduction() :
    with open('My article. Md') as md:
        md_txt = md.read()
    put_markdown(md_txt)
    print(md_txt)

# second_page: data query validation page
def account_verification() :
    put_markdown('# [simple Python] Aliccloud server to receive associated query ')
    
# start_page: Application home page
def index() :
    put_link('[Must-see] Guide to Alibaba Cloud Server', app='activity_introduction') 
    put_markdown('<br>')
    put_link('[Key] Alibaba Cloud server is given associated query', app='account_verification')
                
if __name__ == '__main__':
    start_server([index, activity_introduction, account_verification],port=8081,auto_open_webbrowser=True)
Copy the code

The first step is to import pyWeBio-related packages, followed by three functions that correspond to three pages.

The first page I wrote was for the introduction document, or blog, which is too long to write directly to put_Markdown, so I read the local file and passed it into put_Markdown. This makes the code look more maintainable and beautiful.

Then there is the second page: data query validation, where the put_input function is used, and I pass in four parameters:

  • The first argument is the name of the input box, a string
  • The second parameter type indicates the input data format
  • The third parameter, validate, represents the validation parameter, and the received value is the name of a function to which the input data is passed for validation
  • The fourth parameter, placeholder, represents the input hint

The third page is our home page,pywebioThere are two modes of page hopping, as shown belowpywebio.session.go_app()One is theput_link()And I chose yesput_link()Link copy setting is flexible.

Finally, to start the project, use the start_server function:

  • The first one is the app we want to launch. If there are multiple apps we just pass in a list, and the list element is the app name (function name).
  • The second parameter port is the port to which the application will be deployed. You can select this parameter as long as it is not the same as an existing port in the system
  • The third parameter, auto_open_webbrowser, indicates whether the browser is automatically opened. This parameter can be set to True for local testing and to the default Fasle for deployment to the server

With a few simple steps, we have developed a Web application that would have been much faster if it had only been a single application (e.g., a data query system, a resume display page, etc.).

The original project is not applicable to everyone (Ali Cloud data interface, including personal information), so we can not open source to everyone, but in order to let everyone can 100% follow the tutorial deployment success, so I also prepared a small project for you: personal profile display website, you can see my next sharing content (tomorrow).

3.6 Deploying the Project to the server

We need to do the following things:

  • Identify local project environment + dependency packages
  • Upload the project file and dependency package file to the server
  • Build a virtual environment on the server and install dependency packages
  • Running the project through public IP access is no problem
  • Customize the domain name and set domain name resolution (optional)

3.6.1 Determine the local project environment + dependency packages

Pipenv is used to manage the virtual environment of Python. I will share with you how to use PipenV to manage the virtual environment of Python.

Of course, you don’t have to do this step, the relevant code and dependency storage files I have prepared for you, directly read tomorrow’s article can be obtained.

I’m using python3.10, so it’s not a good idea to export dependencies here (3.6.8 in the cloud server), but I used requests+pandas+pywebio for this project.

Normally, you should go to the local project directory and run the following command to generate the project dependency package files:

pipenv shell   Enter the virtual environment
pip freeze > requirements.txt   Create dependency package files
Copy the code

Then upload to the server and after the environment is installed on the server, execute the following PIP command in the requirements.txt directory to install.

pip install -r requirements.txt 
Copy the code

3.6.2 Upload the project file and dependent package file to the server

Then we need to transfer the local project files to the server. I have written relevant articles before. After SSH service is enabled, the file can be directly transferred using the SCP command, in the following format.

SCP local file directory your server login username @your server IP address: storage directory in the server#, such as: SCP/Users/HHH/Desktop/do. TXT root @ your public IP: / root/Project /
Copy the code

Add a -r to transfer folders:

SCP -r /Users/ HHH /Desktop/FRC root@ Your public IP address: /root/project/Copy the code

We can enter the following command in the terminal:

/SimpleBlog root@ Your public IP address :/root/Project/ SCP - r/Users/HHH/Desktop/SimpleBlog [email protected]: / root/Project /Copy the code

This will upload the entire contents of our local SimpleBlog folder to the Project directory on the cloud server.

Of course, we can also connect ali cloud server in the terminal, directly through SSH, as shown below, MAC open the terminal (Windows open CMD), enter the following command to connect successfully, we do not need to open the browser to ali cloud server background ~

SSH Your server login username @your server IP address# if SSH [email protected]
Copy the code

3.6.3 Building a Virtual Environment and Installing dependency packages on the Server

On the server, go to the /root/project/simpleblog directory. You need to install the virtual environment management package pipenv and enter pip3 install pipenv.

Pipenv is used to install the virtual environment first. After the installation is successful, there will be two more files in the directory Pipfile (download source and version records) and pipfile. lock (manage package dependencies).

cd /root/Project/SimpleBlog  Enter the project directory
pipenv install --three   Install the PYTHon3 virtual environment
Copy the code

Let’s modify the dependencies before we install themPipfileIn the file, you can set the mirror source under the third-party package. We changed it to the mirror source of Tsinghua University. The address is:pypi.tuna.tsinghua.edu.cn/simple(Vim usage is described in 3.4)

vim Pipfile
Copy the code

We will install the project dependency package, first need to enter the virtual environment, in the present directory inputpipenv shellEnter the virtual environment, after entering the front will be a logoSimpleBlog.

Requirements. TXT = requirements. TXT

pip install pandas pywebio requests
Copy the code

After the installation is successful, we can enterpip listIf you have a python package installed, you will find that there are several more packages in the python environment. They are all dependent packages, and you do not need to worry about thempip installInstall. (Note now in the virtual environment oh ~)

3.6.4 Running the project through public IP access is no problem

In the server, we run the following command to start the application: (note is directly in the virtual environment, and in the/root/Project/SimpleBlog SimpleBlog directory)

python simpleblog.py
Copy the code

Run on port 8081

Public IP :8081. Public IP refers to the public IP address of the server (described briefly in 3.1).

We found that the page kept going round and round, knowing that we could not access the website and the response time was too long. This is because we did not open the external access permission of port 8081. We can configure it in the server security group.

We enter ali cloud server background, enter the instance, click more -> Network and Security Group -> Security Group configuration,

On the security group configuration page, clickConfiguration rules.

On the rule configuration page, clickManually addAnd then enter the security group information, except for port access write as8081/8088(Other applications can be deployed later), and the authorization object is0.0.0.0(All IP addresses are accessible), other default Settings will do.

After adding the security group, we can successfully access our deployed service via public IP :8081.

  • The main page

  • Child pages

  • Child pages

3.6.5 Customizing domain Names and Setting Domain Name Resolution (Optional)

You need to have a domain name, which can be purchased from Ali Cloud or Tencent Cloud. I have purchased it before. If you want to purchase it, you can click here for a discount.

Before the use of domain name must be put on record (after the application for a record, there will be a special person telephone contact you to consult the relevant situation, truthful answer can, such as: write a blog, learning to use, etc.).

After purchase, log in ali Cloud domain name management background and click the resolution behind the corresponding domain name to enter the domain name resolution page (each resolution can be interpreted as a mapping from our domain name to the recorded value).

On the domain name resolution page, click Add Record and enter the following information:

  • Select the record type: we select A, which points to an IPV4 address; CNAME refers to another domain name
  • Host record: You need to enter the domain name prefix. You can choose to enter @ to access the host using the domain name, or customize the host name
  • Record value: is to map the domain name to where, here we write the public IP address of our server (introduced in 3.2)

Once everything is added, we can click OK

You can ping the domain name locally to check whether the IP address corresponding to the domain name is the public IP address of the server bound to it and verify whether the binding is successful.

Note that the domain address is not HTTP or HTTPSPing Domain name addressCopy the code

Then we can use our own domain name + service port to access our project deployed on the server

Iv. Notice of the next period

We have basically completed the above: understanding our cloud server, Linux basic command learning, server environment construction and file transfer, Web program logic (PyweBio), project deployment and domain name binding. Of course, there are many things not covered in this article, such as setting up reverse proxy to hide ports in access links, daemon project process, domain name certificate binding (SSL), etc.

I am very glad that you can insist on seeing here, Lao Biao tried to write this cloud server learning pilot from the perspective of small white users: Have a cloud server can turn out to be so cool, such as the introduction, this is a project oriented essay, hope that we can know the whole project to create, through this article the deployment process, I know this is never easy for programmers, hope you can have more experience in the comment area, learning to share.

From here, we officially open with the old watch learn cloud server series tutorial ~ a week 1-2 more!

See you next time. I’m a cat lover and a tech lover. If you find this article helpful, please like, comment and follow me!

See you next time! Click “like” to break 50, add (wan) speed (Ming) update ~