(手把手教程)基于nginx、gunicorn、flask、mysql:远程操作数据库,实现用户认证

一、前言

本文主要是在前文的基础上进一步研究。

(超详细)基于nginx、gunicorn、flask:部署阿里云服务器,前文中的细节不在本文赘述。

本文主要结构是:

  1. 安装mysql;
  2. 操作数据库;
  3. 数据库云端访问;
  4. 通过request远程访问测试;

二、停止gunicorn服务

输入以下命令停止所有的gunicorn进程,方便后续调试:

kill -9 9479

三、安装mysql

1. 设置下载源

无法直接使用yum安装mysql,需要使用wget拉取下载源:

wget https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm

添加下载源:

sudo yum localinstall mysql80-community-release-el7-3.noarch.rpm

安装yum工具

sudo yum install -y yum-utils

2. 安装mysql

使用代码安装

sudo yum install -y mysql-community-server

如果出现以下问题,

The GPG keys listed for the "MySQL 8.0 Community Server" repository are already installed but they are not correct for this package.

Check that the correct key URLs are configured for this repository.

 Failing package is: mysql-community-server-8.0.34-1.el7.x86_64

 GPG Keys are configured as: file:///etc/pki/rpm-gpg/RPM-GPG-KEY-mysql

则去掉GPG检查:

sudo yum -y install mysql-community-server --nogpgcheck

 启动mysql服务:

sudo service mysqld start

3. 初始化mysql

查看初始密码

sudo grep 'temporary password' /var/log/mysqld.log

使用初始密码登录:

mysql -u root -p

成功之后重新设置新密码:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass4!';

输入exit退出mysql。

设置mysql开机自启动

sudo systemctl enable mysqld

4. 安装pymysql

 需要在全局的python环境中安装插件,用于操作数据库:

pip3 install PyMySQL

四、操作数据库

在这里,我们要首先自定义一个数据库,然后定义一个新表,表储存ID和密码,最后插入一个初始的用户。

  • 打开数据库

    • mysql -u root -p
  • 输入密码

    • MyNewPass4!
  • 显示所有的数据库

    • show databases;
  • 创建新的数据库

    • create database cmic;
  • 使用数据库

    • use cmic;
  • 显示所有表

    • show tables;
  • 创建新的表

    • create table user(id int unsigned not null auto_increment primary key, 
      passport varchar(50) not null default 'cmic' );
  • 插入新的值

    • insert into user values(1,'1');
  • 查询

    • select * from user;

 最终查询结果如下所示:

 五、数据库云端访问

由于mysql是安装在阿里云服务器上,所以我们只能将本地的代码上传云服务器,然后在终端运行查看结果:

1. sql.py

创建测试文件,文件中的database就是我们之前创建的数据库的名字,查询命令中需要指定table为user,其他的设置保持默认指定,如果需要请查阅其他文献。

import pymysql
import pprint

def catch(id):
    try:
        connc = pymysql.Connect(
                    host='localhost', 
                    user='root',
                    password="MyNewPass4!",
                    database='cmic',
                    port=3306,
                    charset="utf8",
        )

        cur = connc.cursor()

        sql = 'select * from `user` where `id` = ' + str(id) + ';'

        cur.execute(sql)

        result = cur.fetchall()
        pprint.pprint(result[0][1]) #output the pasport
        
    except Exception as e:
        print(e)
        connc.rollback()

    finally:
        cur.close()
        connc.close()


if __name__ == '__main__':
    catch(1)

这段代码中catch函数接受一个id数,最终应当输出查询到的当前的id的passport。

2. 使用scp上传服务器

具体方法见我的上一个博客(超详细)基于nginx、gunicorn、flask:部署阿里云服务器

3. 在服务器终端运行

 运行代码

python3 sql.py

 得到终端输出为'1'。说明数据库配置没问题,且可以通过python代码访问数据库。

六、远程测试

1. 启动gunicorn服务

通过以下代码启动服务器,具体细节参考我的前一篇博客。

exec gunicorn --bind 0.0.0.0:5000 app:app

 2. 将数据库查询代码接入app.py

from flask import Flask, request
import json, time, datetime
import pymysql
import pprint

def catch(argsJson):
    #to find the passport by id, and return True or False
    id = argsJson['id']
    passport = argsJson['passport']
    
    try:
        connc = pymysql.Connect(
                    host='localhost', 
                    user='root',
                    password="MyNewPass4!",#password, you can change it
                    database='cmic',#database name, you can change it
                    port=3306,
                    charset="utf8",
        )

        cur = connc.cursor()

        sql = 'select * from `user` where `id` = ' + str(id) + ';'

        cur.execute(sql)

        result = cur.fetchall()
        # pprint.pprint(result[0][1]) #output the pasport
        
        if result[0][1] == passport:
            return "True"
        else:
            return "False"

    except Exception as e:
        print(e)
        connc.rollback()

    finally:
        cur.close()
        connc.close()

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 = catch(argsJson)
		result = json.dumps(result, ensure_ascii=False)	
		return result							
	else:
		return " 'it's not a POST operation! "

if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=5000)

这段代码将catch接入get_data函数,服务器收到POST之后,会在catch中处理收到的id和passport,如果输入值匹配,则返回字符串"True",反之"False"。

3. 使用scp将app.py上传到/home

4. 本地测试文件

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, 'passport':'1'})
    print(response)
    print(json.loads(response.post_request().text))  # {'message': 'Data received successfully'}
    print(response.post_request().status_code)  # 200

测试文件的改变不多,只是传入的字典中分别定义了id和passport。

a. {'id':1, 'passport':'1'}结果

b. {'id':1, 'passport':'2'}结果

 七、总结

本文基于nginx、gunicorn、flask和mysql实现了远程操作数据库并进行用户信息对比。本文实验只是一个简单的demo,如果有更加复杂的需求和问题,则需要进一步定制自己的APP。

参考文献

感谢各位大佬!!!

安装mysql

解决GPG问题

操作数据库1

操作数据库2

更多的pysql教程

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值