Ejemplo n.º 1
0
def index(request, methods=METHODS):
    """
    Распределяет запросы либо отдавая страницу документации, либо
    вызывая метод.

    Структура запроса для выполнения метода:

        {
            'method': 'Имя вызываемого метода',
            'kwargs': { Словарь параметров },
            # Необязательные ключи могут браться из сессии, либо из
            # заголовков запроса (например HTTP Basic Authorization).
            # Список необязательные ключей:
            'username': '******',
            'password': '******',
        }

    Параметр "methods" может использоваться сторонними приложениями
    для организации определённых наборов методов API.

    По-умолчанию словарь методов может определяться в переменной
    `settings.QUICKAPI_DEFINED_METHODS` главного проекта.

    """

    switch_language(request)

    if is_callable(request):
        return run(request, methods)

    ctx = {}
    ctx['api_url'] = clean_uri(request)
    ctx['methods'] = methods.values()
    ctx['test_method_doc'] = test.__doc__ if not 'quickapi.test' in methods else None

    return render(request, 'quickapi/index.html', ctx)
Ejemplo n.º 2
0
def run(request, methods):
    """
    Авторизует пользователя, если он не авторизован и запускает методы.

    Параметры авторизации запрещается передавать в GET-запросе, для
    таких случаев их необходимо передавать в заголовке запроса,
    специально предназначенного для Basic-авторизации.

    """

    is_authenticated = request.user.is_authenticated()

    # Нарушителей правил передачи параметров авторизации
    # направляем на страницу документации
    if warning_auth_in_get(request):
        url = clean_uri(request)+'#requests-auth'
        msg = _('You made a dangerous request. Please, read the docs: %s') % url
        return HttpResponseBadRequest(content=force_text(msg))

    if request.method == 'GET':
        REQUEST = request.GET
    else:
        REQUEST = request.POST

    real_method = None
    def get_real_method(name):
        if method in methods:
            return methods[method]['method']
        elif method == 'quickapi.test':
            return test

    if 'method' in REQUEST:
        method = REQUEST.get('method')
        real_method = get_real_method(method)

        kwargs = clean_kwargs(request, REQUEST)

        if not is_authenticated:
            is_authenticated = request_login(real_method, request, REQUEST)

    elif 'jsonData' in REQUEST:
        try:
            data   = json.loads(REQUEST.get('jsonData'))
            method = data.get('method')
            real_method = get_real_method(method)
            kwargs = data.get('kwargs', clean_kwargs(request, data))
        except Exception as e:
            return HttpResponseBadRequest(content='%s\n%s' % (force_text(MESSAGES[400]), force_text(e)))

        if not is_authenticated:
            is_authenticated = request_login(real_method, request, data)

    else:
        return HttpResponseBadRequest(content=force_text(MESSAGES[400]))

    if not is_authenticated:
        if conf.QUICKAPI_ONLY_AUTHORIZED_USERS and method != 'quickapi.test':
            meta = request.META
            ip = meta.get("HTTP_X_REAL_IP", meta.get("REMOTE_ADDR", None))
            logger.info('The attempt unauthorized access to method `%s` on %s from IP: %s.',
                        method, request.path, ip)
            return HttpResponseBadRequest(status=401, content=force_text(MESSAGES[401]))

    if conf.QUICKAPI_DEBUG:
        logger.debug('Run method `%s` on %s', method, request.path)

    if not real_method:
        return HttpResponseBadRequest(status=405, content=force_text(MESSAGES[405]))

    return real_method(request, **kwargs)