def get(self): args = self.parser.parse_args() page = args.get('page', None) if page is None: return ResponseClass.warn(ResponseCode.FORMAT_ERROR) if g.user.role == conf.USER_ROLE_ADMIN: session = AppUtils.get_session() try: items = session.query(Item).order_by(desc(Item.id)).offset( page * 10).limit(10).all() data = [] for item in items: item_dict = AppUtils.serialize(item) data.append(item_dict) return ResponseClass.ok_with_data(data) except Exception as e: pass finally: session.close() else: session = AppUtils.get_session() try: items = session.query(Item).filter_by(isOn=True).order_by( Item.name).offset(page * 10).limit(10).all() data = [] for item in items: item_dict = AppUtils.serialize(item) data.append(item_dict) return ResponseClass.ok_with_data(data) except Exception as e: pass finally: session.close()
def post(self): from app_config import USER_ROLE_ADMIN from app.database_models import Threads if g.user.role == USER_ROLE_ADMIN: # 系统删帖 t_id = request.json.get('thread_id', None) session = AppUtils.get_session() try: th = session.query(Threads).filter_by(id=t_id).first() if th is None: return ResponseClass.warn(ResponseCode.THREAD_NOT_EXIST) session.delete(th) session.commit() return ResponseClass.ok() finally: session.close() else: t_id = request.json.get('thread_id', None) session = AppUtils.get_session() th = session.query(Threads).filter_by(user_id=g.user.id, id=t_id).first() if th is None: return ResponseClass.warn(ResponseCode.THREAD_NOT_EXIST) AppUtils.delete_to_sql(th).close() return ResponseClass.ok()
def post(self): username = request.json.get('username', None) password = request.json.get('password', None) code = request.json.get('code', None) mail = request.json.get('mail', None) if username is None or password is None or code is None or mail is None or not re.match( r'[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[a-zA-Z0-9]+', mail): return jsonify(code=ResponseCode.FORMAT_ERROR, msg="用户名密码格式错误") cache_email = cache.get(code) if cache_email != mail: return ResponseClass.warn(ResponseCode.FORMAT_ERROR) else: cache.delete(code) cache.delete(mail) session = AppUtils.get_session() try: # 验证用户名 AppUtils.validate_username(username) from models.models import User user = User() user.username = username user.mail = mail user.hash_password(password) user.credits = 0 session.add(user) session.commit() # 数据库 from app_config import SQLSession return jsonify(code=0, data=user.get_self_data()) except Exception as e: return jsonify(code=-1, msg=e.args[0]) finally: session.close()
def post(self): import app_config from app.database_models import Comments, Threads if g.user.role == app_config.USER_ROLE_ADMIN: comment_id = request.json.get('comment_id', None) if comment_id is not None: session = AppUtils.get_session() try: comment = session.query(Comments).filter_by( id=comment_id).first() if comment is not None: session.delete(comment) session.commit() return ResponseClass.ok() finally: session.close() else: thread_id = request.json.get('thread_id', None) comment_id = request.json.get('comment_id', None) if comment_id is None or thread_id is None: return ResponseClass.warn(ResponseCode.FORMAT_ERROR) session = AppUtils.get_session() c = session.query(Comments).filter_by(id=comment_id, user_id=g.user.id).first() t = session.query(Threads).filter_by(id=thread_id).first() if t is None or c is None: session.close() return ResponseClass.warn(ResponseCode.COMMENT_NOT_FOUND) result = t.del_comment(comment_id) if result: session.close() return ResponseClass.ok() else: session.close() return ResponseClass.warn(ResponseCode.SERVER_ERROR)
def create_app(): # 生成app app = Flask(__name__) # 配置views set_up_views(app) # 初始化APP AppUtils.init(app) return app
def post(self): code_id = request.json.get('code_id', None) title = request.json.get('title', None) subtitile = request.json.get('subtitle', '') from app.database_models import Threads if not Threads.verify_title(title): return ResponseClass.warn(ResponseCode.FORMAT_ERROR) thread = Threads() thread.user_id = g.user.id thread.title = title thread.code_id = code_id thread.subtitle = subtitile AppUtils.add_to_sql(thread).close() return ResponseClass.ok()
def submit_comment(self, comment, session: Session): try: last_time_commented = Cf.cache.get("comment_" + str(comment.user_id)) if last_time_commented is not None: return False Cf.cache.add("comment_" + str(comment.user_id), datetime.now().timestamp(), timeout=10) if self.comment_id is None: # 对首 comment.threads_id = self.id session.add(comment) self.comment_id = comment.id else: session = AppUtils.get_session() # 不是队列首部 last_comment = session.query(Comments).filter_by( threads_id=self.id, next_id=None).first() comment.parent_id = last_comment.id session.add(comment) last_comment.next_id = comment.id return True except Exception as e: print(e) return False
def del_comment(self, comment_id): try: session = AppUtils.get_session() comment = session.query(Comments).filter_by(id=comment_id).first() if comment_id == self.comment_id: # 对首 self.comment_id = comment.next_id session.delete(comment) elif comment.next_id is None: # 队尾 session.delete(comment) else: # 对中 pre_comment = session.query(Comments).filter_by( id=comment.parent_id).first() next_comment = session.query(Comments).filter_by( id=comment.next_id).first() pre_comment.next_id = next_comment.id next_comment.parent_id = pre_comment.id session.delete(comment) session.commit() session.close() return True except Exception as e: print(e) return False
def post(self): ids = request.json.get("ids", []) if len(ids) == 0: return ResponseClass.warn(ResponseCode.FORMAT_ERROR) session = AppUtils.get_session() total_credits = g.user.credits try: need_paid = 0 cart_item = [] for id in ids: item = session.query(Cart).filter_by(id=id).first() if item is not None: need_paid += item.item.credits cart_item.append(item) if need_paid > total_credits: return ResponseClass.warn(ResponseCode.NO_ENOUGH_CREDITS) else: # cart_id -> repository user = session.query(User).filter_by(id=g.user.id).first() user.credits -= need_paid for cart in cart_item: repo = Repository() repo.user_id = g.user.id repo.item_id = cart.item_id session.add(repo) session.delete(cart) session.commit() return ResponseClass.ok_with_data(user.credits) except Exception as e: pass finally: session.close()
def get(self, user_id): t1 = time.clock() session = AppUtils.get_session() try: from models.models import User q_user = session.query(User).filter_by(id=user_id).with_for_update().first() if q_user is None: return ResponseClass.warn(ResponseCode.USER_NOT_EXIST) else: # 判断是否点过赞,点过赞则警告 from models.models import UserLikes result = session.query(UserLikes).filter_by(user_id=g.user.id, like_user=user_id).with_for_update().first() if result is None: # 点赞 q_user.likes += 1 likes = UserLikes() likes.user_id = g.user.id likes.like_user = user_id session.add(likes) return ResponseClass.ok() else: # TODO 测试并发量 q_user.likes += 1 return ResponseClass.warn(ResponseCode.ALREADY_LIKED) finally: session.commit() print("请求时间:%f" % (time.clock() - t1)) session.close()
def post(self): if g.user.role == conf.USER_ROLE_USER: return ResponseClass.warn(ResponseCode.NOT_ROOT) else: session = AppUtils.get_session() id = request.json.get('id', None) print(id) item: Item if id is not None: # 修改items item = session.query(Item).filter_by(id=id).first() else: item = Item() item.name = request.json.get('name') item.detail = request.json.get('detail') item.credits = request.json.get('credits') item.isOn = request.json.get('isOn') item.img = request.json.get('img') if id is None: session.add(item) try: session.commit() return ResponseClass.ok_with_data({"id": item.id}) finally: session.close()
def post(self): t_id = request.json.get('thread_id', None) # 帖子ID c_id = request.json.get('code_id', None) content = request.json.get('content', None) if t_id is None or content is None: return ResponseClass.warn(ResponseCode.FORMAT_ERROR) session = AppUtils.get_session() try: from app.database_models import Threads thread = session.query(Threads).filter_by(id=t_id).first() if thread is None: return ResponseClass.warn(ResponseCode.THREAD_NOT_EXIST) from app.database_models import Comments new_comment = Comments() new_comment.code_id = c_id new_comment.user_id = g.user.id new_comment.threads_id = t_id new_comment.content = content result = thread.submit_comment(new_comment, session) if result: user = session.query(User).filter_by(id=g.user.id).first() user.credits += 5 session.commit() return ResponseClass.ok() else: return ResponseClass.warn(ResponseCode.OPERATION_TOO_FAST) finally: session.close()
def get(self, user_id): session = AppUtils.get_session() try: from app.database_models import User q_user = session.query(User).filter_by( id=user_id).with_for_update().first() if q_user is None: return ResponseClass.warn(ResponseCode.USER_NOT_EXIST) else: # 判断是否点过赞,点过赞则警告 from app.database_models import UserLikes result = session.query(UserLikes).filter_by( user_id=g.user.id, like_user=user_id).with_for_update().first() if result is None: # 点赞 q_user.likes += 1 likes = UserLikes() likes.user_id = g.user.id likes.like_user = user_id session.add(likes) else: q_user.likes -= 1 session.delete(result) session.commit() return ResponseClass.ok_with_data(q_user.likes) finally: session.close()
def get(self, offset: int): session = AppUtils.get_session() try: result = Code.get_code(session, g.user.id, offset) result = list(map(Code.get_public_dict, result)) return ResponseClass.ok_with_data(result) finally: session.close()
def create_app(): # 配置 pywsgi # dapp = DebuggedApplication(app, evalex=True) # server = pywsgi.WSGIServer(('0.0.0.0', 5000), dapp) # server.serve_forever() # 运行 flask # 猴子补丁,增加并发 # monkey.patch_all() # 生成app app = Flask(__name__) # 配置views set_up_views(app) # 初始化APP AppUtils.init(app) return app
def get(self, id): session = AppUtils.get_session() try: from app.database_models import Code code = session.query(Code).filter_by(user_id=g.user.id, id=id).first() if code is not None: session.delete(code) return jsonify(ResponseClass.ok()) finally: session.close()
def get(self): args = self.parser.parse_args() page = args.get('page', None) if page is None: return ResponseClass.warn(ResponseCode.FORMAT_ERROR) session = AppUtils.get_session() try: repository_items = session.query(Repository).filter_by( user_id=g.user.id).order_by( conf.database.desc(Repository.create_date)).offset( page * 10).limit(10).all() data = [] for repository_item in repository_items: item_data = AppUtils.serialize(repository_item.item) item_data['repo_id'] = repository_item.id data.append(item_data) return ResponseClass.ok_with_data(data) except Exception as e: pass finally: session.close()
def post(self): content = request.json.get('content', None) file_name = request.json.get('fileName', None) if not content or not file_name: return jsonify(code=-1, msg="参数不对") filename = secure_filename( g.user.username + datetime.datetime.now().strftime('_%H-%M-%S-%f_') + file_name).lower() local_path = os.path.join(Cf.upload_path, filename) # file.save(local_path) file = open(local_path, encoding="utf-8", mode="w") file.write(content) file.close() # 写入数据库 from app.database_models import Code code = Code() code.user_id = g.user.id code.local_path = local_path # 根据后缀判断语言 suffix = os.path.splitext(filename)[-1] from app.code_manager import CodeType if suffix == '.py': code.code_type = CodeType.PYTHON3 elif suffix == '.c': code.code_type = CodeType.C elif suffix == '.cpp': code.code_type = CodeType.CPP elif suffix == '.java': code.code_type = CodeType.JAVA else: code.code_type = CodeType.FILE session = AppUtils.get_session() try: session.add(code) session.commit() return jsonify(code=ResponseCode.OK_RESPONSE, data={'id': code.id, 'url': AppUtils.get_network_url(os.path.join(Cf.upload_path, filename))}) finally: session.close()
def get(self): args = self.parser.parse_args() page_num = int(args.get('page', None)) if page_num is None or type(page_num) != int or page_num <= 0: return ResponseClass.warn(ResponseCode.FORMAT_ERROR) # 将page_num-1,适应计算 page_num = page_num - 1 session = AppUtils.get_session() from app.database_models import Threads threads = session.query(Threads).filter_by(user_id=g.user.id).offset( page_num * self.page_num_per_request).limit( self.page_num_per_request).all() threads = [tr.get_public_dict() for tr in threads] return ResponseClass.ok_with_data(threads)
def get(self, id): session = AppUtils.get_session() try: user = g.user if user.id != id: # 查询他人的信息 query_user = session.query(User).filter_by(id=id).first() return ResponseClass.ok_with_data(query_user.get_minimal_data( )) if query_user is not None else ResponseClass.warn( ResponseCode.USER_NOT_EXIST) else: ResponseClass.ok_with_data(user.get_self_data()) finally: session.close()
def post(self): url = request.json.get("url", None) url = AppUtils.get_local_path(url) print("url:", url) session = AppUtils.get_session() from app.database_models import Code code = session.query(Code).filter_by(local_path=url).first() if code is None: return ResponseClass.warn(ResponseCode.FILE_NOT_EXIST) session.close() # 先存入CodeResult from app.database_models import CodeResult code_result = CodeResult() code_result.code_id = code.id code_result.user_id = g.user.id from app_config import code_manager session = AppUtils.add_to_sql(code_result) block = CodeBlock(user_id=code_result.user_id, task_id=code_result.id) session.close() return_value = code_manager.add_task(block) if return_value: return ResponseClass.ok_with_data({"code_id": code_result.code_id}) else: return ResponseClass.warn(ResponseCode.SUBMIT_ERROR)
def post(self): cart_id = int(request.json.get("item_id", None)) if cart_id is None: return ResponseClass.warn(ResponseCode.FORMAT_ERROR) session = AppUtils.get_session() try: cart = Cart() cart.item_id = cart_id cart.user_id = g.user.id session.add(cart) session.commit() return ResponseClass.ok() except Exception as e: pass finally: session.close()
def post(self): if g.user.role == conf.USER_ROLE_USER: return ResponseClass.warn(ResponseCode.NOT_ROOT) else: session = AppUtils.get_session() try: item = session.query(Item).filter_by( id=request.json.get("id")).first() if item is not None: item.isOn = not item.isOn session.commit() return ResponseClass.ok_with_data(item.isOn) else: return ResponseClass.warn(ResponseCode.ITEM_NOT_FOUND) finally: session.close()
def post(self): cart_id = int(request.json.get("item_id", None)) if cart_id is None: return ResponseClass.warn(ResponseCode.FORMAT_ERROR) session = AppUtils.get_session() try: item = session.query(Cart).filter_by(user_id=g.user.id, id=cart_id).first() if item is None: return ResponseClass.warn(ResponseCode.ITEM_NOT_FOUND) session.delete(item) session.commit() return ResponseClass.ok() except Exception as e: pass finally: session.close()
def post(self): username = request.json.get('username', None) password = request.json.get('password', None) if username is None or password is None: return jsonify(code=ResponseCode.FORMAT_ERROR) # 查找用户 session = AppUtils.get_session() try: user = session.query(User).filter_by(username=username).first() if user is None: user = session.query(User).filter_by(mail=username).first() if user is None: return jsonify(code=ResponseCode.USER_NOT_EXIST) if not user.verify_password_only(password): return jsonify(code=ResponseCode.PASSWORD_ERROR) # 用户验证成功 return ResponseClass.ok_with_data(user.get_self_data()) finally: session.close()
def get_public_dict(self): d = dict() d['create_date'] = self.create_date d['id'] = self.id d['title'] = self.title d['subtitle'] = self.subtitle d['comment_id'] = self.comment_id d['username'] = self.user.nickname + '(' + self.user.username + ')' d['avatar'] = self.user.avatar_url d['user_like'] = self.user.likes from app_utils import AppUtils session = AppUtils.get_session() code = session.query(Code).filter_by(id=self.code_id).first() if code is not None: d['code_url'] = code.get_download_url() else: d['code_url'] = '' d['user_id'] = self.user_id return d
def get(self): args = self.parser.parse_args() thread_id = args.get("thread_id", None) page = args.get("page", None) if thread_id is None or page is None: return ResponseClass.warn(ResponseCode.FORMAT_ERROR) session = AppUtils.get_session() try: from app.database_models import Comments comments = session.query(Comments) \ .filter_by(threads_id=thread_id) \ .order_by(desc(Comments.create_date)) \ .offset(int(page) * 10) \ .limit(10) \ .all() comments = [item.get_public_dict() for item in comments] return ResponseClass.ok_with_data(comments) finally: session.close()
def get_public_dict(self): d = dict() d['id'] = self.id d['user_id'] = self.user_id d['threads_id'] = self.threads_id d['content'] = self.content d['parent_id'] = self.parent_id d['next_id'] = self.next_id d['create_date'] = self.create_date.timestamp() from app_utils import AppUtils session = AppUtils.get_session() code = session.query(Code).filter_by(id=self.code_id).first() if code is not None: d['code_url'] = code.get_download_url() else: d['code_url'] = '' d['username'] = self.user.nickname + '(' + self.user.username + ')' d['avatar'] = self.user.avatar_url return d
def post(self): field = request.json.get("field", None) value = request.json.get("value", None) if field is not None and value is not None: user = g.user # 需要重新查找,这个User未绑定sql,无法更新 session = AppUtils.get_session() user = session.query(User).filter_by(id=user.id).first() try: if field == "nickname": user.nickname = value session.commit() return ResponseClass.ok() elif field == "avatar_url": user.avatar_url = value session.commit() return ResponseClass.ok() finally: session.close() return ResponseClass.warn(ResponseCode.FORMAT_ERROR)
def post(self): name = request.json.get("username", None) if name is None: return ResponseClass.warn(ResponseCode.FORMAT_ERROR) session = AppUtils.get_session() try: user = session.query(User).filter_by(username=name).first() if user is None: user = session.query(User).filter_by(mail=name).first() if user is None: return ResponseClass.warn(ResponseCode.USER_NOT_EXIST) else: # 发送邮件 if self.send_reset_password_mail(user): return ResponseClass.ok() else: # 没发出去,服务器错误 return ResponseClass.warn(ResponseCode.SERVER_ERROR) finally: session.close()