promotion/handler/location.py
2019-07-10 10:49:57 +08:00

104 lines
3.1 KiB
Python

# -*- coding: utf-8 -*-
from __future__ import absolute_import
from flask import Flask, jsonify
from flask_restful import reqparse, abort, Api, Resource
import logging
from mysql.mmysql import MysqlBase
from config import mysql_promotion_config
import pdb
log = logging.getLogger(__name__)
mydb = MysqlBase(**mysql_promotion_config)
parser = reqparse.RequestParser()
parser.add_argument('id')
parser.add_argument('gameid')
parser.add_argument('area')
parser.add_argument('type')
parser.add_argument('in_used')
class Location(Resource):
def __init__(self):
self.args = parser.parse_args()
def get(self):
sql = f"select id,gameid,area,type from location where in_used=1;"
try:
data = mydb.query(sql)
except Exception:
log.error("get data from location failed!", exc_info=True)
return jsonify({'code': 500})
all_data = []
log.debug(f"get data from localtion was {data}")
if data:
for line in data:
if line:
localtion = {}
localtion['id'], localtion['gameid'], localtion['area'], localtion['type'] = line
all_data.append(localtion)
del localtion
return jsonify({'code': 200,'message': all_data})
else:
log.error(f"{data} not found in mysql !")
return jsonify({'code': 404})
def post(self):
try:
location = {}
location['gameid'] = self.args['gameid']
location['area'] = self.args['area']
location['type'] = self.args['type']
location['id'] = self.create_id()
mydb.insert("location", location)
except Exception:
log.error("set values to location mysql failed!", exc_info=True)
return jsonify({'code': 500})
return jsonify({'code': 200})
def create_id(self):
max_id = f"select id from location order by id desc limit 1"
data = mydb.query(max_id)
log.info(f"2 {data}")
try:
max = int(data[0][0]) + 1
log.info(f"max id was {max}!")
except Exception:
log.error(f"error with get location id ", exc_info=True)
max = 1001
return max
def put(self):
try:
location = {}
location['id'] = self.args['id']
location['gameid'] = self.args['gameid']
location['area'] = self.args['area']
location['type'] = self.args['type']
location['in_used'] = self.args['in_used'] or 0
sel_sql = f"select area from location where id={self.args['id']};"
data = mydb.query(sel_sql)
if data:
condition = f"id='{self.args['id']}'"
mydb.update("location", location, condition)
return jsonify({'code': 200})
else:
return jsonify({'code': 404, 'message': f"{self.args['id']} not found in mysql!"})
except Exception:
log.error("update values to location mysql failed!", exc_info=True)
return jsonify({'code': 500})
def delete(self):
id = self.args['id']
if not id:
return jsonify({'code':500,'message':'id not found'})
try:
del_sql = f'delete from location where id={id};'
mydb.query(del_sql)
except Exception:
log.error(f"location remove {id} failed!", exc_info=True)
return jsonify({'code': 500})
return jsonify({'code': 200})