def halfer(event, context): try: n = float(event['number']) return util.jsonify(str(n) + ' divided by two is ' + str(n/2)) except ValueError: logger.error('Input number is not a number.') return util.jsonify('Please input a REAL number.')
def dig_or_bury(user_id,post_id,value=1): dig = Dig() dig.user_id = user_id dig.post_id = post_id dig.state = value dig.pubdate = datetime.datetime.now() session.add(dig) try: session.commit() return jsonify() except: session.rollback() return jsonify(500)
def put(event, context): table = dynamodb.Table('ARTIST') try: genre = event['genre'] name = event['name'] age = int(event['age']) table.put_item(Item={'GENRE': genre, 'NAME': name, 'AGE': age}) return util.jsonify('Artist created successfully') except ValueError: logger.error('User Input is not a number.') return util.jsonify('Please input a number for artist\'s age.')
def register(ctx,request:YuHeLg.Request): payload = request.json #email,pwd,name email = payload.get("email") #验证邮箱是否唯一 if session.query(User).filter(User.email == email).first() is not None: raise exc.HTTPConflict("{} already exists".format(email)) user = User() try: user.name = payload.get("name") user.email = payload.get("email") user.password = bcrypt.hashpw(payload.get("password").encode(), bcrypt.gensalt()) except Exception as e: print(e) exc.HTTPBadRequest() session.add(user) try: session.commit() res = jsonify(user={ 'id': user.id, 'name': user.name }, token=gen_token(user.id)) print(res) return res except: session.rollback() raise exc.HTTPInternalServerError()
def get(ctx,request:YuHeLg.Request): post_id = request.vars.id try: post = session.query(Post).filter(Post.id==post_id).one() post.hits +=1 session.add(post) try: session.commit() except: session.rollback() #处理tags pts = session.query(Post_tag).filter(Post_tag.post_id == post_id).limit(10).all() tags = " ".join([pt.tag.tag for pt in pts]) buryinfo, diginfo = get_digs_or_burys(post_id) return jsonify(post={ 'post_id':post.id, 'title':post.title, 'author':post.author.name, 'postdate':post.postdate.timestamp(), 'content':post.content.content, 'hits':post.hits },diginfo=diginfo,buryinfo=buryinfo,tags=tags) except Exception as e: print(e) raise exc.HTTPNotFound()
def pub(ctx,request:YuHeLg.Request): payload = request.json post = Post() try: post.title = payload.get("title") post.author_id = request.user.id post.postdate = datetime.datetime.now() cont = Content() cont.content = payload.get("content") post.content = cont tags = payload["tags"] except Exception as e: print(e) raise exc.HTTPBadRequest() taglist = re.split('[\s,]',tags) for tag in taglist: t = session.query(Tag).filter(Tag.tag == tag).first() if t is None: t = Tag() t.tag = tag session.add(t) pt = Post_tag() pt.tag = t pt.post = post session.add(pt) session.add(post) try: session.commit() return jsonify(post_id=post.id) except: session.rollback() raise exc.HTTPInternalServerError()
def list(ctx,request:YuHeLg.Request): page = vaildate(request.params,"page",int,1,lambda x,y:x if x >0 and x<101 else y) size = vaildate(request.params,"size",int,20,lambda x,y:x if x >0 and x<101 else y) #size 这里是运行浏览器端改变的,但是要控制范围。也可以不让浏览器端改变 query = session.query(Post) try: user_id = vaildate({"user_id":request.vars.id},"user_id",int,-1,lambda x,y:x if x >0 else y ) except: user_id = -1 if user_id>0: query = query.filter(Post.author_id == user_id) try: count = query.count() posts = query.order_by(Post.id.desc()).limit(size).offset((page-1)*size).all() #offset偏移量丛集开始取 return jsonify(posts=[{ "post_id":post.id, "title":post.title } for post in posts], page_infos={ "page":page, "size":size, "count":count, "pages":math.ceil(count/size) }) except Exception as e: print(e) raise exc.HTTPInternalServerError()
def wrapper(*args, **kwargs): try: rv = func(*args, **kwargs) except (wkerr.BadRequest, MultipleInvalid) as e: LOGGER(str(e)) return jsonify(request.path, has_error=True, data=Err.ErrArgs) except Err.ServiceError as e: if e.code == 1001: return Response('relogin', status=599) return jsonify(request.path, has_error=True, data=e) except Exception as e: print(e) LOGGER(traceback.format_exc()) return jsonify(request.path, has_error=True, data=Err.ErrInternal) return jsonify(request.path, data=rv)
def save_json(file_name, json_dict): """ :param file_name: file name to save json :param json_dict: dictionary to save :return: None """ with open(os.path.join(util.PROCESSED_DATA, file_name), 'w') as fp: json.dump(jsonify(json_dict), fp)
def calculating(event, context): try: n1 = float(event['number']) n2 = float(event['number']) operation = event['operation'] except ValueError: logger.error('Input number is not a number.') return util.jsonify('Please input a number.') return calulator.calcResult(n1, n2, operation)
def login(ctx,request:YuHeLg.Request): payload = request.json email = payload.get('email') user = session.query(User).filter(User.email == email).first() if user and bcrypt.checkpw(payload.get('password').encode(), user.password.encode()): return jsonify(user={ 'id':user.id, 'name':user.name, 'email':user.email },token=gen_token(user.id)) else: raise exc.HTTPUnauthorized()
def handler(event, context): try: # Check if input was a string and add extension name = str(event['name']) image = name + '.png' except ValueError: # Input was not a string logger.error('Input name is not a string.') return util.jsonify('Please input a string only!') try: # Check if image exist s3.Object('music-jermaine-anderson', image).load() return util.jsonify( 'https://s3.amazonaws.com/music-jermaine-anderson/' + image) except botocore.exceptions.ClientError as e: if e.response['Error']['Code'] == "404": # The object does not exist return util.jsonify('The Image Does Not Exist!') else: # Something else has gone wrong return util.jsonify('Lambda Function Error!')
def primer(event, context): try: n = int(event['number']) orginalN = n result = 'Similar Tempo(s): ' while n / 2 > 10: number = n / 2 stringNumber = str(number)+'BPM | ' result += stringNumber n = number while orginalN * 2 < 999: number = orginalN * 2 stringNumber = str(number)+'BPM | ' result += stringNumber orginalN = number return util.jsonify(result) except ValueError: logger.error('User Input is not a number.') return util.jsonify('Please input a number [0-999].')
def d(*args, **kwargs): ctx.response.content_type = 'application/json' ret = {'msg': 'ok', 'success': True, 'data': None} try: content = fn(*args, **kwargs) ret['data'] = content except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() fp = StringIO() traceback.print_exception(exc_type, exc_value, exc_traceback, file=fp) stacks = fp.getvalue() print(stacks) fp.close() ret['success'] = False ret['msg'] = str(e) ret['traceback'] = stacks return jsonify(ret)
def d(*args, **kwargs): ctx.response.content_type = 'application/json' ret = { 'msg': 'ok', 'success': True, 'data': None } try: content = fn(*args, **kwargs) ret['data'] = content except Exception as e: exc_type, exc_value, exc_traceback = sys.exc_info() fp = StringIO() traceback.print_exception(exc_type, exc_value, exc_traceback, file=fp) stacks = fp.getvalue() print(stacks) fp.close() ret['success'] = False ret['msg'] = str(e) ret['traceback'] = stacks return jsonify(ret)