可怜我的所有web知识全部集中在c#上,这次需要把远程数据存到ubuntu的mysql数据库上,不光需要写核心算法,这些接口也得自己来弄啊!无奈,java实在是太弱,还是用熟悉的python吧,至少可以维持现在python c++ c#的语法混乱,别再加个java进来了,否则必须疯 ?
本想用Django,不过这玩意儿貌似太强大了 我的需求其实很小,弄一个接收数据的接口即可,Django对于我的需求来说简直就是大材小用,最终选了flask,小巧玲珑(我就喜欢小巧玲珑的 哈哈)
====================== 我是即会洗衣服做饭又会垒代码可就是没人娶的分割线 ======================
安装我就不啰嗦了,直接各种pip,请自行百度。需要用到: flask和PyMySQL
1. 访问数据库,使用PyMySQL,写了一个访问类MySqlHelper.py,很简单
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name: MySqlHelper.py
# Purpose:
#
# Author: BQH
#
# Created: 2019/3/28
# Copyright: (c) Administrator 2018
# Licence: PyCharm
# -------------------------------------------------------------------------------
import pymysql
from PulseData_table import *
class PulseDbHelper:
def __init__(self, server_ip="10.xx.xx.xx", user_name="sa", pwd="xxxx"):
self.db_ip = server_ip
self.db_user = user_name
self.db_pwd = pwd
self.db = pymysql.connect(self.db_ip, self.db_user, self.db_pwd, "Pulse")
def Add(self, pulseData_entity):
res = 1
sql = "INSERT INTO table(Name,DataContent,UpLoadTime, Comment) VALUES('{0}','{1}','{2}', '{3}')".format(
pulseData_entity.Name,
pulseData_entity.DataContent,
pulseData_entity.UpLoadTime,
pulseData_entity.Comment)
cursor = self.db.cursor()
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
self.db.commit()
except:
# 如果发生错误则回滚
self.db.rollback()
res = 0
# 关闭数据库连接
self.db.close()
return res
def GetAllData(self, limit=-1):
sql = "SELECT * FROM PulseData"
if limit > 0:
sql += " limit " + str(limit)
cursor = self.db.cursor()
res = []
try:
# 执行sql语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall()
for row in results:
entity = PulseData()
entity.id = row[0]
entity.Name = row[1]
entity.DataContent = row[2]
entity.UpLoadTime = row[3]
entity.Comment = row[4]
res.append(entity)
except:
res = []
# 关闭数据库连接
self.db.close()
return res
if __name__ == '__main__':
pulseDb = PulseDbHelper()
res = pulseDb.GetAllData(5)
r = 0
pass
用到的表实体类
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name: PulseData_table.py
# Purpose:
#
# Author: BQH
#
# Created: 2019/3/28
# Copyright: (c) Administrator 2018
# Licence: PyCharm
# -------------------------------------------------------------------------------
class PulseData:
id = 0
Name = ''
DataContent = ''
UpLoadTime = ''
Comment = ''
这样数据库访问层就搞定了,然后开始写接口
WebAPI.py
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name: WebAPI.py
# Purpose:
#
# Author: BQH
#
# Created: 2019/3/28
# Copyright: (c) Administrator 2018
# Licence: PyCharm
# -------------------------------------------------------------------------------
from flask import Flask, jsonify
from flask import request
import datetime
from PulseData_table import *
from MySqlHelper import *
app = Flask(__name__)
@app.route('/api/data', methods=['POST'])
def create_task():
response = {'success': 'true', 'message':'Ok!'}
try:
if not request.form or not 'Name' in request.form or not 'DataContent' in request.form:
raise Exception('Data format error!')
entity = PulseData()
entity.Name = request.form['Name']
entity.DataContent = request.form['DataContent']
entity.UpLoadTime = datetime.datetime.now()
entity.Comment = request.form['Comment']
pulseDb = PulseDbHelper()
res = pulseDb.Add(entity)
if res == 0:
response['success'] = 'false'
except Exception as ex:
response['success'] = 'false'
response['message'] = str(ex)
return jsonify(response), 200
if __name__ == '__main__':
app.run(debug=True)
到这里就在开发环境上就结束了,可以使用Postman.exe来做个测试,使用form-data来post数据
2. 目标环境部署
在目标环境上安装uwsgi
pip install uwsgi
找个路径存放第一步写好的三个文件,比如/home/xxx/WebSite
新建一个uwsgi.ini文件,用来配置uwsgi,内容如下:
[uwsgi]
plugin=python
http=192.168.1.11:8888
wsgi-file=/home/DatabaseAgent/WebSite/WebAPI.py
callable=app
touch-reload=/home/PulseDatabaseAgent/WebSite/
说明:
plugin:python,需要将你的python路径写入环境变量中,~/.brashrc这个文件
http:填写你的目标及其IP,端口随意
wsgi-file:你的WebAPI.py文件路径
callable:app 就写“app”别动,我一开始写的是 WebAPI就一直报错,郁闷
touch-reload:监听路径,同wsgi-file一致就行
别的还有N多配置,暂时不管了,反正这不是我的专业,这个api很简单,能用就行
然后启动:
uwsgi --ini /home/DatabaseAgent/uwsgi.ini
ok,完工走人!