一、前言
最近为了构建用户端和服务器的通信,查看了许多教程。
综合各位大佬的内容,本教程实现了最简单的需求:部署并连接。
本文需要对Linux命令行操作有基础了解。
二、获取阿里云服务器
1. 注册
首先注册账号之后,直接免费试用三个月的ECS服务器,由于需求较低,选择最简单的设置即可。
2. 操作系统选择
首选CentOS,CentOS绑定了yum,使用Ubuntu需要折腾yum的安装,不值得。
3. 远程连接
在实例栏左右拖动,可以获得自己的IP地址(公)。点击右端的远程连接进入官方的网页连接。
首先需要重新设置账户密码,然后再使用密码登录。
进入熟悉的Linux终端:
三、安装软件及配置
1. 安装nginx
安装直接回车或者输入y即可。
更新系统软件包
sudo yum update
安装epel储存库
sudo yum install epel-release
安装nginx
sudo yum install nginx
2. 设置nginx
开启服务
sudo systemctl start nginx
开机自运行
sudo systemctl enable nginx
验证安装
sudo systemctl status nginx
出现activate(running)表示设置成功。
3. 设置服务器能够被公共访问
Nginx默认监听在http(80)端口,外部想使用nginx就需要云服务器开放80端口,在云服务器控制台的左侧导航栏找到安全组,点进安全组。
点击第一个安全组ID/名称,选择手动添加,按照下图设置进行设置。描述可自定义,设置完成后保存。
四、python环境配置
1. 安装python
Linux自带有python3和pip3,如没有则使用以下代码安装:
sudo yum install python3 python3-devel python3-pip
一般不在服务器上做开发,那么就在全局的环境下配置项目的python环境。如果需要配置虚拟环境,请参考其余文献。
2. 安装flask
pip3 install Flask
五、创建测试项目文件并导入
1. 本地测试
本地测试不在服务器上进行。
app.py
from flask import Flask, request
import json, time, datetime
app = Flask(__name__)
@app.route('/', methods=['GET','POST'])
def get_data():
if request.method == 'POST':
argsJson = request.data.decode('utf-8')
argsJson = json.loads(argsJson)
print(argsJson)
result = process_json(argsJson)
result = json.dumps(result, ensure_ascii=False)
return result
else:
return " 'it's not a POST operation! "
def process_json(data):
return data
if __name__ == '__main__':
app.debug = True
app.run(host='localhost', port=5000)
本地安装好flask,直接运行app.py,出现下图表示运行成功。
test.py
import requests
import json
class Request_Response():
def __init__(self, data):
self.data = data
self.url = 'http://localhost:5000/'
def post_request(self):
response = requests.post(self.url, json=self.data)
return response
if __name__ == '__main__':
response = Request_Response({'id':'1'})
print(json.loads(response.post_request().text)) # {'message': 'Data received successfully'}
print(response.post_request().status_code) # 200
运行test.py,得到测试的结果,与我们的期望输出相同。
2. 将app.py上传到服务器上
修改app.py
首先修改app.py中host的值,这样设置是因为服务器从IP地址接受POST之后,需要在服务器本地与flask进行通信,0.0.0.0:5000是nginx监听的端口号。
from flask import Flask, request
import json, time, datetime
app = Flask(__name__)
@app.route('/', methods=['GET','POST'])
def get_data():
if request.method == 'POST':
argsJson = request.data.decode('utf-8')
argsJson = json.loads(argsJson)
print(argsJson)
result = process_json(argsJson)
result = json.dumps(result, ensure_ascii=False)
return result
else:
return " 'it's not a POST operation! "
def process_json(data):
return data
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=5000)
上传app.py文件
在本地(windows)的终端进入app.py文件所在文件夹:
C:\Windows\System32>cd 文件所在位置
使用scp将文件传输到服务器,为了方便将文件放在home目录下:
D:\Users\SERVER>scp app.py root@你的公网IP:\home\app.py
需要输入密码完成传输:
检查文件传输结果
接下来在服务器终端进行,进入home位置,查看文件。
cd /home
ls
可以看到文件传输到了相应位置:
六、配置服务器
1. 编辑nginx的配置文件
使用以下命令进入nginx.conf文件:
vim /etc/nginx/nginx.conf
按A键进行编辑,将server{...}中的内容替换为如下:
server {
listen 80; # 监听公网端口(此处为标准HTTP端口80)
server_name 112.124.13.224; # 替换为您的域名或公网IP
location / {
proxy_pass http://localhost:5000; # 替换为项目实际监听的本地端口
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
按esc退出编辑,按shift+;,输入x,按回车,保存并退出vim。
这段配置是告诉nginx监听公网端口80,并将所有到此服务器的请求转发到本地端口5000(是flask项目运行的端口)。同时设置了必要的代理头信息。
重启nginx服务
sudo systemctl restart nginx
出现错误可以输入以下命令查看出错位置。
nginx -t
2. 安装gunicorn
直接在python的全局安装
pip3 install gunicorn
3. 启动flask项目
设置环境变量
export FLASK_APP=app.py
启动gunicorn,指定监听地址和端口,以及应用入口点:
exec gunicorn --bind 0.0.0.0:5000 app:app
七、本地远程连接服务器
1. 修改test.py
修改端口位置self.url = 'http://112.124.13.224/'。
import requests
import json
class Request_Response():
def __init__(self, data):
self.data = data
self.url = 'http://112.124.13.224/'
def post_request(self):
response = requests.post(self.url, json=self.data)
return response
if __name__ == '__main__':
response = Request_Response({'id':'1'})
print(json.loads(response.post_request().text)) # {'message': 'Data received successfully'}
print(response.post_request().status_code) # 200
2. 运行并查看结果
可以看到,在本地(windows)运行,成功连接到了云端服务器。成功开启了构建服务器的第一步。
参考文献
本文参考了以下文章的部分内容,如有疑惑,请参考原文:
https://blog.csdn.net/m0_66111719/article/details/138226848
https://blog.csdn.net/qq_42166923/article/details/114987154
https://blog.csdn.net/weixin_38470243/article/details/102545860
https://blog.csdn.net/tailonh/article/details/108865408
感谢各位大佬!!!