从零搭建一个tf2.0的web服务,包含mysql redis操作

从零搭建一个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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值