从零搭建一个tf2.0的web服务,包含mysql redis
使用anaconda 来管理
https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/找一个使用自己环境的安装包安装
已mac为例,下载对应版本后设置环境变量
echo "export PATH=\" xxx你的安装路径xxx \">>~/.bash_profile
source ~/.bash_profile
1.创建一个环境
conda create -n my_web python=3.6
然后激活该环境
conda activate my_web 或 其他环境 source activate my_web
2.安装包 (使用豆瓣源 https://pypi.doubanio.com/simple/
)
需要安装flask tf2.0 mysql redis
pip install flask -i https://pypi.doubanio.com/simple/
pip install tensorflow==2.0.0a0 -i https://pypi.doubanio.com/simple/
pip install PyMySQL -i https://pypi.doubanio.com/simple/
pip install redis -i https://pypi.doubanio.com/simple/
3.实例
数据库:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
import pymysql
from flask import Flask
from flask import jsonify, request
import time
import tensorflow as tf
import redis
print(tf.__version__)
app = Flask(__name__)
#数据库实例
db = pymysql.connect("localhost", "root", "han123", "demo")
#redis实例
r = redis.Redis(host='0.0.0.0', port=6379)
@app.route('/')
def index():
return 'Index Page'
@app.route('/tf_test')
def tf_test():
"""
测试tf
:return:
"""
x = tf.Variable([[1., 2., 3.], [1., 2., 3.]])
return str(tf.reshape(x, [3,2]))
@app.route('/tf')
def redis():
"""
测试redis
:return:
"""
r.set('name', 'test')
return(r.get('name'))
@app.route('/add')
def add():
"""
数据库添加
:return:
"""
username = request.args['name']
if not username:
return 'name invalid'
cursor = db.cursor()
print("INSERT INTO user (id, name) VALUES ({}, '{}');".format(int(time.time()), username))
cursor.execute("INSERT INTO user (id, name) VALUES ({}, '{}');".format(int(time.time()), username))
data = cursor.fetchall()
cursor.close()
return jsonify(data)
@app.route('/get')
def get():
"""
数据库获取全部记录
:return:
"""
cursor = db.cursor()
cursor.execute("SELECT * FROM user")
data = cursor.fetchall()
cursor.close()
return jsonify(data)
if __name__ == '__main__':
app.run()