diff --git a/README.md b/README.md index 07a3943..ffcd2f8 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ pip install Flask pip install requests pip install bs4 pip install gunicorn +pip install pymongo // 设置全局变量 export FLASK_APP=coc.py export FLASK_ENV=development @@ -28,8 +29,72 @@ kill (pid) ## 错误代码一览 -/login +/api/login 100:数据校验失败 101:账户错误 102:教务挂了 -200:ok \ No newline at end of file +200:ok + +/api/laf/add +330:数据校验失败 +331:插入数据库失败 + +/api/laf/del +340:数据校验失败 +341:id不合法 + +/api/laf/get +350:数据校验失败 +351:lost表获取失败 +352:found表获取失败 + +/api/laf/detail +360:数据校验失败 +361:数据不存在 +362:id不合法 + +/api/laf/comment +370:数据校验失败 +371:评论数据库修改失败 +372:回复数据库修改失败 +373:数据不存在 +374:id不合法 + +/api/photo/upload +380:图片格式不符 + +# lost and found +* /api/laf/add + * data + * title + * content + * create_time + * img_url + * total_addr + * detail_addr + * contact_way > type + content + * comment [ {msg, user_name, time, user_cid, reply } ] + * user_info > user_cid + user_name + user_id + * type +* /api/laf/del + * data + * id + * type + * user_info > user_cid + user_name +* /api/laf/get + * data + * user_info > user_cid + user_name +* /api/laf/detail + * data + * id + * type +* /api/laf/comment + * data + * user_info > user_cid + user_name + * msg + * time + * position + * id + * type + * comment_type + * comment_index \ No newline at end of file diff --git a/coc.py b/coc.py index e616dce..6f5e072 100644 --- a/coc.py +++ b/coc.py @@ -1,7 +1,7 @@ # 引入文件夹中的文件 import sys sys.path.append('./lib') -from allFunction import manageLogin +from allFunction import manageLogin, managePhoto, manageAdd, manageDel, manageGet, manageDetail, manageComment from flask import Flask, request, session @@ -13,6 +13,42 @@ def login(): res = manageLogin(request) return res +# 上传图片 +@app.route('/api/photo/upload', methods=['PUT'], strict_slashes=False) +def upload_photo(): + res = managePhoto(request) + return res + +# 新增失物招领信息 +@app.route('/api/laf/add',methods=['POST']) +def laf_add(): + res = manageAdd(request) + return res + +# 删除失物招领信息 +@app.route('/api/laf/del',methods=['POST']) +def laf_del(): + res = manageDel(request) + return res + +# 获取全部失物招领信息 +@app.route('/api/laf/get',methods=['POST']) +def laf_get(): + res = manageGet(request) + return res + +# 获取指定失物招领信息 +@app.route('/api/laf/detail',methods=['POST']) +def laf_detail(): + res = manageDetail(request) + return res + +# 新增评论 +@app.route('/api/laf/comment',methods=['POST']) +def laf_comment(): + res = manageComment(request) + return res + if __name__ == '__main__': app.debug = True app.run() \ No newline at end of file diff --git a/lib/allFunction.py b/lib/allFunction.py index 299dfa0..f6b97f4 100644 --- a/lib/allFunction.py +++ b/lib/allFunction.py @@ -4,6 +4,8 @@ from mail import sendMail import json from hashlib import md5 from urllib.parse import urlencode, unquote_plus +from photoUpload import upload_photo +from db import addLAF, getLost, getFound, getDetail, delLAF, commentLAF, replyLAF # 主函数 # 处理登录操作 data:{cid,pwd,sign} @@ -13,6 +15,7 @@ def manageLogin(request): data_cache = json.loads(request.form['data']) # MD5校验 checked = checkData(data_cache) + data_cache.pop('sign') if checked: # 创建会话 res = connect(data_cache) @@ -28,6 +31,95 @@ def manageLogin(request): else: return {'errcode': 100, 'errmsg':'数据校验失败'} +# 处理上传的图片 +def managePhoto(request): + res = upload_photo(request) + return res + +# 处理新增失物招领信息 +def manageAdd(request): + # json化,应该能当dict用 + data_cache = json.loads(request.form['data']) + # MD5校验 + checked = checkData(data_cache) + data_cache.pop('sign') + if checked: + return addLAF(data_cache, data_cache['type']) + else: + return {'errcode': 330, 'errmsg': '数据校验失败'} + +# 处理删除失物招领信息 +def manageDel(request): + # json化,应该能当dict用 + data_cache = json.loads(request.form['data']) + # MD5校验 + checked = checkData(data_cache) + data_cache.pop('sign') + if checked: + return delLAF(data_cache['id'], data_cache['type'], data_cache['user_info']) + else: + return {'errcode': 340, 'errmsg': '数据校验失败'} + +# 获取全部失物招领信息 +def manageGet(request): + # json化,应该能当dict用 + data_cache = json.loads(request.form['data']) + # MD5校验 + checked = checkData(data_cache) + data_cache.pop('sign') + if checked: + return {'errcode': 200, 'lost': getLost(), 'found': getFound()} + else: + return {'errcode': 350, 'errmsg': '数据校验失败'} + +# 获取指定失物招领信息 +def manageDetail(request): + # json化,应该能当dict用 + data_cache = json.loads(request.form['data']) + # MD5校验 + checked = checkData(data_cache) + data_cache.pop('sign') + if checked: + return getDetail(data_cache['id'], data_cache['type'], 361) + else: + return {'errcode': 360, 'errmsg': '数据校验失败'} + +# 处理新增评论 +def manageComment(request): + # json化,应该能当dict用 + data_cache = json.loads(request.form['data']) + # MD5校验 + checked = checkData(data_cache) + data_cache.pop('sign') + if checked: + position = data_cache['position'] + data = data_cache['data'] + if position['comment_type'] == 1: + # 留言 + return commentLAF(position['id'], data, position['type']) + elif position['comment_type'] == 2: + # 回复 + # 取出信息 + laf_cache = getDetail(position['id'], position['type'], 373) + # 错误拦截 + if laf_cache['errcode'] != 200: + return laf_cache + # json化失物招领信息 + laf_cache = json.loads(laf_cache['detail']) + # 取出comment + comment = laf_cache['comment'] + # 如果还没reply过要初始化 + if 'reply' not in comment[position['comment_index']]: + comment[position['comment_index']]['reply'] = [] + # 将回复信息加入comment + comment[position['comment_index']]['reply'].append(data) + # 覆写comment + return replyLAF(position['id'], comment, position['type']) + else: + # 参数错误 + return {'errcode': 370, 'errmsg': '数据校验失败'} + else: + return {'errcode': 370, 'errmsg': '数据校验失败'} # 工具函数 diff --git a/lib/db.py b/lib/db.py new file mode 100644 index 0000000..c9cf7fa --- /dev/null +++ b/lib/db.py @@ -0,0 +1,92 @@ +from pymongo import MongoClient +from bson import ObjectId, json_util + +# 主环境 (生产环境为production,开发环境为development) +setting = 'development' + +# 获取数据集 +def col(arg): + conn = MongoClient('mongodb://coc:qlSfefSor5@localhost:12236/coc') + if setting == 'development': + arg += '_test' + if arg == 'lost': + return conn.coc.lost + elif arg == 'found': + return conn.coc.found + elif arg == 'lost_test': + return conn.coc.lost_test + elif arg == 'found_test': + return conn.coc.found_test + else: + return False + +# 新增失物招领信息 +def addLAF(data, add_type): + try: + col(add_type).insert_one(data) + except Exception as e: + # 失败了 + return { 'errcode': 331, 'errmsg': '插入数据库失败', 'errdetail': e} + return {'errcode': 200, 'errmsg': 'ok'} + +# 获取全部失物信息 +def getLost(): + arr = [] + try: + for i in col('lost').find(): + arr.append(i) + except Exception as e: + return {'errcode': 351, 'errmsg': 'lost表获取失败', 'errdetail': e} + return {'errcode': 200, 'arr': json_util.dumps(arr), 'errmsg': 'ok'} + +# 获取全部招领信息 +def getFound(): + arr = [] + try: + for i in col('found').find(): + arr.append(i) + except Exception as e: + return {'errcode': 352, 'errmsg': 'found表获取失败', 'errdetail': e} + return {'errcode': 200, 'arr': json_util.dumps(arr), 'errmsg': 'ok'} + +# 获取指定失物信息 +def getDetail(id, get_type, errcode): + try: + info = col(get_type).find_one({"_id": ObjectId(id)}) + if info: + return {'errcode': 200, 'detail': json_util.dumps(info), 'errmsg': 'ok'} + else: + return {'errcode': errcode, 'errmsg': '数据不存在'} + except Exception as e: + # id不合法 + return {'errcode': errcode+1, 'errmsg': 'id不合法', 'errdetail': e} + +# 删除某个失物 +def delLAF(id, del_type, del_user_info): + try: + col(laf_type).update({"_id": ObjectId(id)}, + {'$set': {'close': 'true','del_user_info': del_user_info}}) + except Exception as e: + # id不合法 + return {'errcode': 341, 'errmsg': 'id不合法'} + return {'errcode': 200, 'errmsg': 'ok'} + +# 向一条记录添加留言 +def commentLAF(id, data, laf_type): + try: + col(laf_type).update({"_id": ObjectId(id)}, + {'$push': {'comment': data}}) + except Exception as e: + # 失败 + return {'errcode': 371, 'errmsg': '评论数据库修改失败'} + return {'errcode': 200, 'errmsg': 'ok'} + +# 向一条记录添加回复 +def replyLAF(id, comment, laf_type): + try: + col(laf_type).update({"_id": ObjectId(id)}, + {'$set': {'comment': comment}}) + except Exception as e: + # 失败 + return {'errcode': 372, 'errmsg': '回复数据库修改失败'} + return {'errcode': 200, 'errmsg': 'ok'} diff --git a/lib/photoUpload.py b/lib/photoUpload.py new file mode 100644 index 0000000..0128d0e --- /dev/null +++ b/lib/photoUpload.py @@ -0,0 +1,31 @@ +import os +from werkzeug.utils import secure_filename +import datetime +import random + +basedir = os.path.abspath(os.path.dirname(__file__)) +ALLOWED_EXTENSIONS = set(['png', 'PNG', 'jpg', 'JPG', 'jpeg', 'gif', 'GIF']) +def allowed_file(filename): + return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS + +def create_uuid(): #生成唯一的图片的名称字符串,防止图片显示时的重名问题 + nowTime = datetime.datetime.now().strftime("%Y%m%d%H%M%S") # 生成当前时间 + randomNum = random.randint(0, 100) # 生成的随机整数n,其中0<=n<=100 + if randomNum <= 10: + randomNum = str(0) + str(randomNum) + uniqueNum = str(nowTime) + str(randomNum) + return uniqueNum + +def upload_photo(request): + file_dir = os.path.join(basedir, '../upload') + if not os.path.exists(file_dir): + os.makedirs(file_dir) + f = request.files['photo'] + if f and allowed_file(f.filename): + fname = secure_filename(f.filename) + ext = fname.rsplit('.', 1)[1] + new_filename = create_uuid() + '.' + ext + f.save(os.path.join(file_dir, new_filename)) + return {'errcode': 200, 'filename': new_filename} + else: + return {'errcode': 380, 'errmsg': '图片格式不符'} \ No newline at end of file