從零搭建一個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()