def next(show): try: return json_response({ 'episode': get_show_by_name(show).next_episode() }) except EpisodeNotFoundException: return json_response({'error': 'Episode not found'}, 404)
def view_show_info(show): try: result = json_response(Show(show)) add_epguides_key_to_redis(show) return result except EpisodeNotFoundException: return json_response({'error': 'Show not found'}, 404)
def edit_item(category_name, item_name): user = getUser() item, category = getItemAndCategory(category_name, item_name) if category.user is not user: return json_response('Editing item forbidden', 403) categories = getCategories() if request.method == 'GET': return render_template('edit_item.html', categories=categories, category=category, item=item, user=user) else: name = request.form['item-name'] description = request.form['item-description'] new_category_name = request.form['category'] new_category = getCategory(new_category_name) if not new_category: return json_response('Category not found.', 404) item.name = name item.description = description item.category = new_category session.commit() flash('Successfully modified %s' % item.name) return redirect(url_for('item', category_name=category.name, item_name=item.name))
def post(self, request): ''' Edit user. Only can change password. ''' pk = request.user.pk user = request.user permission_required(user, 'UserData', 'edit', pk) permission_required(user, 'AuthEvent', 'create') try: req = parse_json_request(request) except: return json_response( status=400, error_codename=ErrorCodes.BAD_REQUEST) old_pwd = req.get('old_pwd', '') new_pwd = req.get('new_pwd', '') if not old_pwd or not new_pwd: return json_response( status=400, error_codename=ErrorCodes.BAD_REQUEST) if not user.check_password(old_pwd): return json_response( status=400, error_codename="INVALID_OLD_PASSWORD") user.set_password(new_pwd) user.save() data = {'status': 'ok'} return json_response(data)
def post(self, request, pk): e = get_object_or_404(AuthEvent, pk=pk) # find if there's any extra field of type match_census_on_registration = [] if e.extra_fields is not None: match_census_on_registration = [ f for f in e.extra_fields if "match_census_on_registration" in f and f['match_census_on_registration'] ] if (e.census == 'close') and (len(match_census_on_registration) == 0 or e.status != 'started'): return json_response( status=400, error_codename="REGISTER_IS_DISABLED") if e.census == 'open' and e.status != 'started': # register is closing return json_response( status=400, error_codename="AUTH_EVENT_NOT_STARTED") data = auth_register(e, request) if data['status'] == 'ok': return json_response(data) else: return json_response( status=400, error_codename=data.get('error_codename'))
def post(self, request): ''' Edit user. Only can change password. ''' pk = request.user.pk user = request.user permission_required(user, 'UserData', 'edit', pk) permission_required(user, 'AuthEvent', 'create') try: req = json.loads(request.body.decode('utf-8')) except: return json_response(status=400, error_codename=ErrorCodes.BAD_REQUEST) old_pwd = req.get('old_pwd') new_pwd = req.get('new_pwd') if not old_pwd or not new_pwd: return json_response(status=400, message="") if not user.check_password(old_pwd): return json_response(status=400, message="Invalid old password") user.set_password(new_pwd) user.save() data = {'status': 'ok'} return json_response(data)
def next_from_given_episode(show, season, episode): try: return json_response({ 'episode': get_show_by_name(show).get_episode(int(season), int(episode)).next() }) except EpisodeNotFoundException: return json_response({'error': 'Episode not found'}, 404)
def get_groups_by_query(request): """ :param request: :return: """ query = request.POST.get('query', '') if query == '': json_response(0) group_type = request.POST.get('type', '') data = { 'v': settings.API_VERSION, 'access_token': request.session.get('access_token'), 'q': query, 'count': 1000, 'type': group_type } r = requests.post(settings.GET_GROUPS_URL, data=data) groups_data = r.json() if u'response' in groups_data: return json_response(groups_data[u'response']['items']) return json_response(0)
def send_notification(request): """ :param request: :return: """ if 'ids' not in request.POST: return json_response(-1) ids = request.POST.get('ids') rd = settings.REQUEST_DATA.copy() rd['user_ids'] = ids rd['message'] = str(datetime.now())[:-7] + "\nТест для отправки сообщений" rd['access_token'] = request.session.get('access_token') requests.post(settings.SEND_MESSAGE_URL, data=rd) del rd['user_ids'] gid = request.session.get('gid') ids = map(int, ids.split(',')) client = MongoClient() db = client[gid] targets_c = db['targets'] targets = targets_c.find({"id": {"$in": ids}}) for t in targets: rd['message'] = str(datetime.now())[:-7] + "\n" + get_recommendations(t) rd['user_id'] = t['id'] requests.post(settings.SEND_MESSAGE_URL, data=rd) return json_response(1)
def episode(show, season, episode): try: return json_response({ 'episode': Show(show).get_episode(int(season), int(episode)) }) except EpisodeNotFoundException: return json_response({'error': 'Episode not found'}, 404)
def get_cities_by_query(request): """ :param request: :return: """ cid = int(request.POST.get('country', 0)) if cid == 0: return json_response(0) data = { 'country_id': cid, 'v': settings.API_VERSION, 'access_token': request.session.get('access_token') } query = request.POST.get('query', None) if query: data['q'] = query url = settings.GET_CITIES_URL r = requests.post(url, data=data) cities_data = r.json() items = [] if u'response' in cities_data: items = cities_data[u'response']['items'] return json_response(items)
def next_released_from_given_episode(show, season, episode): try: return json_response({ 'status': Show(show).get_episode(int(season), int(episode)).next().released() }) except EpisodeNotFoundException: return json_response({'error': 'Episode not found'}, 404)
def delete_category(category_name): user = getUser() category = getCategory(category_name) if not category: return json_response('Category not found', 404) if category.user is not user: return json_response('Deleting category forbidden', 403) items = getItemsByCategory(category_name) if items: return json_response('Cannot delete category with items in it.', 400) if request.method == 'GET': return render_template( 'delete_entity.html', entity=category, path=url_for('delete_category', category_name=category_name), user=user) else: session.delete(category) session.commit() flash('Successfully deleted %s' % category.name) return redirect('/')
def new_item(category_name): user = getUser() if request.method == 'GET': categories = getCategories() category = findCategory(category_name) return render_template('edit_item.html', category=category, categories=categories, user=user) else: name = request.form['item-name'] description = request.form['item-description'] category_name = request.form['category'] category = getCategory(category_name) if not category: return json_response('Category not found.', 404) existing_item = getItemByName(name) if existing_item: return json_response('Item with that name already exists.', 400) item = Item(name=name, description=description, category=category, user=user) session.add(item) session.commit() flash('Created item %s' % item.name) return redirect('/category/%s' % category.name)
def answer_question(request): if request.is_ajax() and request.POST.get('pk', ''): pk = request.POST.get('pk', '') delete = request.POST.get('del', False) if '_' in pk: pk = pk.split('_')[1] if not delete: answer_cnt = request.POST.get('answer', '') try: question = Question.objects.get(pk=pk) if hasattr(question, 'answer'): answer = question.answer else: answer = Answer(question=question) answer.responder = Manager.objects.get(pk=request.user.pk) answer.content = answer_cnt answer.save() return json_response({'op_status': 'success'}) except Exception as e: print (e) else: question = Question.objects.get(pk=pk) if hasattr(question, 'answer'): question.answer.delete() question.delete() return json_response({'op_status': 'success'}) return render_to_response('messages.html', {'message': u'اجازه دسترسی ندارید.'}, context_instance=RequestContext(request,))
def reject_request(request): if request.is_ajax() and request.POST.get('pk', ''): pk = request.POST.get('pk', '') request = Request.objects.get(pk=pk) request.status = False request.save() return json_response({'op_status': 'success'}) return json_response({'op_status': 'fail'})
def post(self, request): try: req = json.loads(request.body.decode('utf-8')) except: return json_response(status=400, error_codename=ErrorCodes.BAD_REQUEST) data = {'status': 'ok', 'method': 'POST'} data['post'] = req return json_response(data)
def remove_from_card(): try: card_id = request.args["id"].strip() serv.remove_from_card(card_id) return json_response(True,"") except Exception, e: log.error(print_debug(e)) return json_response(False,u"未知异常")
def last(show): try: return json_response({ 'episode': Show(show).last_episode() }) except EpisodeNotFoundException: return json_response({'error': 'Episode not found'}, 404)
def get_api(key): value = r.get(key) if not value: return json_response({'error': 'No value for given key'}, 404) return json_response({ key: value })
def released(show, season, episode): try: return json_response({ 'status': Show(show).episode_released(int(season), int(episode)) }) except EpisodeNotFoundException: return json_response({ 'status': False })
def ask_question(request): if request.is_ajax(): title = request.POST.get('title', '') content = request.POST.get('content', '') sender = request.user Question.objects.create(sender=sender, title=title, content=content) return json_response({'op_status': 'success', 'redirect': '/question/your_questions/'}) return json_response({'op_status': 'fail'})
def remove_self_log(request): if request.is_ajax() and request.POST.get('pk', ''): pk = request.POST.get('pk') al = ActionLog.objects.get(pk=pk) al.disabled = True al.save() return json_response({'op_status': 'success'}) return json_response({'op_status': 'fail'})
def next_from_given_episode(show, season, episode): try: result = json_response({ 'episode': Show(show).get_episode(int(season), int(episode)).next() }) add_epguides_key_to_redis(show) return result except EpisodeNotFoundException: return json_response({'error': 'Episode not found'}, 404)
def get_group_parsing_status(request): """ :param request: :return: """ tid = request.session.get('tid') if tid: return json_response(app.AsyncResult(tid).ready()) return json_response(-1)
def add_to_card(): try: product_key = request.form["p"] count = int(request.form["c"]) pay_type = int(request.form['t']) pay_count = int(request.form["tl"]) serv.add_to_card(product_key, count,pay_type,pay_count) return json_response(True,"") except Exception, e: log.error(print_debug(e)) return json_response(False,u"未知异常%s"%request.form["c"])
def put_create_instance(data, instance_id): try: broker.create_instance(instance_id=instance_id, **data) except ProvisioningAsynchronously: return json_response({}, 202) except CannotProvisionSynchronouslyError as e: return json_response(e.msg, 422) except ServiceConflictError: return json_response({}, 409) else: return json_response({}, 201)
def put_bind(data, instance_id, binding_id): try: credentials = broker.bind_instance(instance_id=instance_id, binding_id=binding_id, **data) except BindingNotSupportedError as e: return json_response(e.msg, 400) except BindingExistsError as e: return json_response(e.msg, 409) except AppGUIDRequiredError as e: return json_response(e.msg, 422) else: return json_response({"credentials": credentials}, 201)
def get_hash_api(name, key=None): if key is None: value = r.hgetall(name) else: value = {key: r.hget(name, key)} if not value: return json_response({'error': 'No value for given key'}, 404) return json_response({ name: value })
def change_item_count(): try: card_id = request.form.get("id") count = int(request.form.get("c")) pay_type = int(request.form.get("pt")) pay_count = int(request.form.get("pc")) fee,favor_fee = serv.set_item_count(card_id, count, pay_type, pay_count) return json_response(True,{'fee':fee,'favor_fee':favor_fee}) except Exception, e: log.error(print_debug(e)) return json_response(False,u"未知异常")
def update_orders(): data = request.get_json() order_id = data.pop('id') o = Order.get(order_id) o.update(data) return json_response(o.json())
def get(request): '''Retrieve a list of all panels.''' session_attendee_list = Session_Attendee.objects.all().values() return json_response(session_attendee_list)
def post(request): return json_response({})
def list_books(): books = [] for b in g.db.query(Book).all(): books.append(b.book_to_dict()) return json_response(books=books)
def index(request): u = current_user(request) todos = Todo.find_all_json(user_id=u.id, deleted=False) return json_response(todos)
def update(request): form = request.json() todo_id = int(form.get('id')) t = Todo.update(todo_id, form) return json_response(t.json())
def user_login(): login_data = LoginData(**get_request_data(request)) if not login_data.validate(): return json_response({"message": "Missing login or password"}, 400) return login_data.login_response(db.users)
def final(request): category = Category.objects.filter().order_by('?')[0] return utils.json_response(category.serialize(), 200, "success")
def read_nat(nat_type, router_id, rule_id=None): # TODO log.debug('%s nat_id: %d-%r' % (nat_type, router_id, rule_id)) return json_response(status=SUCCESS), HTTP_OK
def create(self, collection): if find_one(collection, self.login, 'login') is not None: return json_response({"message": "User already exists"}, 409) return object_save(collection, self.to_dict(), "users")
def request_wrapper(fn): def foo(request): if request.method == 'GET': return fn(request.GET.get('term'), request.GET.get('n', 10)) return json_response(foo)
def metadata(): return json_response(json.dumps(METADATA))
def update_weibo(request): form = request.json() weibo_id = int(form.get('id')) t = Weibo.update(weibo_id, form) return json_response(t.json())
def users(): if request.method == 'POST': user_data = User(**get_request_data(request)) if not user_data.validate(): return json_response({"message": "User form is invalid"}, 400) return user_data.create(db.users)
def get_thread(request, thread_id): try: t = Thread.objects.get(id=thread_id) civis = Civi.objects.filter(thread_id=thread_id) req_a = Account.objects.get(user=request.user) # problems = civis.filter(c_type='problem') # causes = civis.filter(c_type='cause') # solutions = civis.filter(c_type='solution') #TODO: move order by to frontend or accept optional arg c = civis.order_by('-created') c_scores = [ci.score(req_a.id) for ci in c] c_data = [Civi.objects.serialize_s(ci) for ci in c] for idx, item in enumerate(c_data): problems[idx]['score'] = c_scores[idx] problems = sorted(problems, key=lambda x: x['score'], reverse=True) # for idx, item in enumerate(problems): # problems[idx] = json.dumps(item, cls=DjangoJSONEncoder) # # c = civis.filter(c_type='cause').order_by('-created') # c_scores = [ci.score(req_a.id) for ci in c] # causes = [Civi.objects.serialize_s(ci) for ci in c] # for idx, item in enumerate(causes): # causes[idx]['score'] = c_scores[idx] # causes = sorted(causes, key=lambda x: x['score'], reverse=True) # for idx, item in enumerate(causes): # causes[idx] = json.dumps(item, cls=DjangoJSONEncoder) # # c = civis.filter(c_type='solution').order_by('-created') # c_scores = [ci.score(req_a.id) for ci in c] # solutions = [Civi.objects.serialize_s(ci) for ci in c] # for idx, item in enumerate(solutions): # solutions[idx]['score'] = c_scores[idx] # solutions = sorted(solutions, key=lambda x: x['score'], reverse=True) # for idx, item in enumerate(solutions): # solutions[idx] = json.dumps(item, cls=DjangoJSONEncoder) # problems = [Civi.objects.serialize(c) for c in civis.filter(c_type='problem').order_by('-votes_vpos', '-votes_pos')] # problems = # causes = [Civi.objects.serialize(c) for c in civis.filter(c_type='cause').order_by('-votes_vpos', '-votes_pos')] # solutions = [Civi.objects.serialize(c) for c in civis.filter(c_type='solution').order_by('-votes_vpos', '-votes_pos')] data = { 'title': t.title, 'summary': t.summary, 'hashtags': t.hashtags.all().values(), 'author': { 'username': t.author.user.username, 'profile_image': t.author.profile_image.url if t.author.profile_image else "/media/profile/default.png", 'first_name': t.author.first_name, 'last_name': t.author.last_name }, 'category': model_to_dict(t.category), 'created': t.created, # 'problems': problems, # 'causes': causes, # 'solutions': solutions, 'contributors': [ Account.objects.chip_summarize(a) for a in Account.objects.filter(pk__in=civis.distinct( 'author').values_list('author', flat=True)) ], 'num_civis': t.num_civis, 'num_views': t.num_views, 'votes': [{ 'civi_id': act.civi.id, 'activity_type': act.activity_type, 'acct': act.account.id } for act in Activity.objects.filter(thread=t.id, account=req_a.id) ] } #modify thread view count t.num_views = t.num_views + 1 t.save() return json_response(data) except Exception as e: return HttpResponseBadRequest(reason=str(e))
def update(id): b = Book.get(id) data = request.json b.update(data) return json_response(Book.get(id).json())
def room_meetings(room_id): if find_one(db.rooms, room_id) is None: return json_response({"message": "Room does not exist"}, 404) return list_all(db.meetings, {"room_id": room_id}, request.args)
def add(request): u = current_user(request) form = request.json() t = Todo.new(form, user_id=u.id) return json_response(t.json())
def get(request): '''Retrieve a list of all schedules.''' schedule_list = Schedule.objects.all().values() return json_response(schedule_list)
def books_all(): bs = Book.all() return json_response([b.json() for b in bs])
def update(request): form = request.json() check_id(request, form) newTodo = Todo.update(form) return json_response(newTodo.json())
def update_book(title): price = request.form.get('price') return json_response(updated=True)
def delete(id): b = Book.get(id) b.delete() return json_response(Book.get(id).json())
def post(request, pk=None): ''' Creates a new auth-event or edit auth_event create_authevent permission required or edit_authevent permission required ''' try: req = parse_json_request(request) except: return json_response(status=400, error_codename=ErrorCodes.BAD_REQUEST) if pk is None: # create permission_required(request.user, 'AuthEvent', 'create') auth_method = req.get('auth_method', '') msg = check_authmethod(auth_method) if msg: return json_response(status=400, message=msg) auth_method_config = { "config": METHODS.get(auth_method).CONFIG, "pipeline": METHODS.get(auth_method).PIPELINES } config = req.get('auth_method_config', None) if config: msg += check_config(config, auth_method) extra_fields = req.get('extra_fields', None) if extra_fields: msg += check_extra_fields( extra_fields, METHODS.get(auth_method).USED_TYPE_FIELDS) census = req.get('census', '') # check census mode if not census in ('open', 'close'): return json_response(status=400, error_codename="INVALID_CENSUS_TYPE") error_kwargs = plugins.call("extend_type_census", census) if error_kwargs: return json_response(**error_kwargs[0]) real = req.get('real', False) based_in = req.get('based_in', None) if based_in and not ACL.objects.filter(user=request.user.userdata, perm='edit', object_type='AuthEvent', object_id=based_in): msg += "Invalid id to based_in" if msg: return json_response(status=400, message=msg, error_codename=ErrorCodes.BAD_REQUEST) if config: auth_method_config.get('config').update(config) ae = AuthEvent(auth_method=auth_method, auth_method_config=auth_method_config, extra_fields=extra_fields, census=census, real=real, based_in=based_in) # Save before the acl creation to get the ae id ae.save() acl = ACL(user=request.user.userdata, perm='edit', object_type='AuthEvent', object_id=ae.id) acl.save() acl = ACL(user=request.user.userdata, perm='create', object_type='UserData', object_id=ae.id) acl.save() # if necessary, generate captchas from authmethods.utils import have_captcha if have_captcha(ae): generate_captcha(settings.PREGENERATION_CAPTCHA) else: # edit permission_required(request.user, 'AuthEvent', 'edit', pk) auth_method = req.get('auth_method', '') msg = check_authmethod(auth_method) if msg: return json_response(status=400, message=msg) config = req.get('auth_method_config', None) if config: msg += check_config(config, auth_method) extra_fields = req.get('extra_fields', None) if extra_fields: msg += check_extra_fields(extra_fields) if msg: return json_response(status=400, message=msg) ae = AuthEvent.objects.get(pk=pk) ae.auth_method = auth_method if config: ae.auth_method_config.get('config').update(config) if extra_fields: ae.extra_fields = extra_fields ae.save() # TODO: Problem if object_id is None, change None by 0 acl = get_object_or_404(ACL, user=request.user.userdata, perm='edit', object_type='AuthEvent', object_id=ae.pk) data = {'status': 'ok', 'id': ae.pk, 'perm': acl.get_hmac()} return json_response(data)
def add(): data = request.get_json() # log(data) b = Book.isbn(data["isbn"]) return json_response(b.json())
def get(self, request, pk=None): data = {} extended = plugins.call("extend_get_legal", pk) if len(extended) > 0: data = extended[0] return json_response(data)
def book_id(id): b = Book.get(id) return json_response(b.json())
def get(request): '''Retrieve a list of all speakers.''' person_list = Person.objects.all().values() return json_response(person_list)
async def index(request): r = {'status': 'success', 'text': 'Hello, im index handler'} return json_response(r)
def switch(request): todo_id = int(request.query.get('id')) check_id(request, id=todo_id) status = request.query.get('status') t = Todo.complete(todo_id, status) return json_response(t.json())