Example #1
0
def artist_list(request):
    user = request.user.myuser
    if anti_spider(request):
        return response.HttpResponseNotFound(
            content="<h1>Not Found</h1><p>The requested URL " +
                    request.path_info +
                    " was not found on this server.</p>"
        )

    artists = Artist.objects.all()

    query = request.GET.get("q")
    if query:
        artists = artists.filter(
            Q(name__icontains=query)
        )
        artists = artists.distinct()

    datas = cache.get(user.key("like"))
    if not datas:
        datas = map(
            lambda x: {
                "artist": x,
                "status": (True if Like.objects.filter(user=user, artist=x) else False),
            }, artists)
        cache.set(user.key("like"), list(datas), 5 * 60)

    context = {
        "datas": datas,
    }

    return render (request, "artists/artist_list.html", context)
Example #2
0
def user_list(request):
    user = request.user.myuser
    if anti_spider(request):
        return response.HttpResponseNotFound(
            content="<h1>Not Found</h1><p>The requested URL " +
            request.path_info + " was not found on this server.</p>")

    users = MyUser.objects.all()
    now = datetime.date.today()
    start = now - datetime.timedelta(days=3)

    datas = cache.get(user.key("list"))
    if not datas:
        datas = map(
            lambda x: {
                "user":
                x,
                "num": (lambda y: len(y) if y else 0)(x.playlist.all()),
                "new": (lambda y: len(y) if y else 0)
                (x.playlist.filter(year_released__gt=start)),
                "status":
                (True if Follow.objects.filter(fan=user, star=x) else False),
            }, users)

        cache.set(user.key("list"), list(datas), 5 * 60)

    context = {
        "datas": datas,
    }

    return render(request, "core/user_list.html", context)
Example #3
0
    def correct_url(request, object_id):
        """修正请求url"""
        resolved_url = resolve(request.path_info)
        url_name = resolved_url.url_name
        url_kwargs = resolved_url.kwargs

        if object_id:
            # 对于只有object_id没有app_id的 重定向到有app_id的url
            modeladmin = view.__self__
            try:
                obj = modeladmin.model.objects.get(pk=object_id)
            except modeladmin.model.DoesNotExist:
                return response.HttpResponseBadRequest()

            url_kwargs.update(wechat_app_id=obj.app_id, object_id=object_id)
            return response.HttpResponseRedirect(reverse("admin:" + url_name,
                                                         kwargs=url_kwargs),
                                                 status=307)
        else:
            # 对于没有app_id的listview请求 优先取referrer的app_id
            referrer = request.META.get("HTTP_REFERER", "")
            path_info = urlparse(referrer).path
            try:
                app_id = resolve(path_info).kwargs["wechat_app_id"]
            except (KeyError, Resolver404):
                return response.HttpResponseNotFound()

            url_kwargs.update(wechat_app_id=app_id)
            resp = response.HttpResponseRedirect(
                reverse("admin:" + url_name, kwargs=url_kwargs))
            resp.status_code = 307
            return resp
Example #4
0
 def dispatch(self, request):
     """
     :type request: wechat_django.models.request.WeChatMessageRequest
     """
     if not request.wechat.app.interactable():
         return response.HttpResponseNotFound()
     log = MessageHandler.handlerlog(request)
     try:
         self._verify(request)
         resp = super(Handler, self).dispatch(request)
         if not isinstance(resp, response.HttpResponseNotFound):
             log(logging.DEBUG, "receive a message")
         return resp
     except MultiValueDictKeyError:
         log(logging.WARNING, "bad request args", exc_info=True)
         return response.HttpResponseBadRequest()
     except BadMessageRequest:
         log(logging.WARNING, "bad request", exc_info=True)
         return response.HttpResponseBadRequest()
     except InvalidSignatureException:
         log(logging.WARNING, "invalid signature", exc_info=True)
         return response.HttpResponseBadRequest()
     except xmltodict.expat.ExpatError:
         log(logging.WARNING, "deserialize message failed", exc_info=True)
         return response.HttpResponseBadRequest()
     except MessageHandleError:
         log(logging.WARNING, "handle message failed", exc_info=True)
         return ""
     except:
         log(logging.ERROR, "an unexcepted error occurred", exc_info=True)
         return ""
Example #5
0
    def decorated_func(request, *args, **kwargs):
        app_id = kwargs.pop("wechat_app_id", None)
        object_id = kwargs.get("object_id", None)
        if not app_id:
            resolved_url = resolve(request.path_info)
            url_name = resolved_url.url_name
            url_kwargs = resolved_url.kwargs
            if object_id:
                # 对于只有object_id没有app_id的 重定向到有app_id的url
                modeladmin = view.__self__
                try:
                    obj = modeladmin.model.objects.get(pk=object_id)
                except modeladmin.model.DoesNotExist:
                    return response.HttpResponseBadRequest()

                url_kwargs.update(wechat_app_id=obj.app_id,
                                  object_id=object_id)
                return response.HttpResponseRedirect(
                    reverse("admin:" + url_name, kwargs=url_kwargs))
            else:
                # 对于没有app_id的listview请求 优先取referrer的app_id
                referrer = request.META.get("HTTP_REFERER", "")
                path_info = urlparse(referrer).path
                try:
                    app_id = resolve(path_info).kwargs["wechat_app_id"]
                except (KeyError, Resolver404):
                    return response.HttpResponseNotFound()

                url_kwargs.update(wechat_app_id=app_id)
                resp = response.HttpResponseRedirect(
                    reverse("admin:" + url_name, kwargs=url_kwargs))
                resp.status_code = 307
                return resp

        extra_context = kwargs.pop("extra_context", None) or {}
        try:
            app = site.wechat_site.app_queryset.get(id=app_id)
        except WeChatApp.DoesNotExist:
            return response.HttpResponseNotFound()

        # 附上app
        request.app = app
        request.app_id = app_id
        # 增加模板context
        extra_context.update(wechat_app=app, wechat_app_id=app_id)
        kwargs["extra_context"] = extra_context
        return view(request, *args, **kwargs)
Example #6
0
def not_found(*args, **kwargs):
    payload = _get_error_payload(
        'Not Found',
        'Not Found',
        '404')
    return django_resp.HttpResponseNotFound(
        content=json.dumps(payload),
        content_type=const.HTTP_RESPONSE_CONTENT_TYPE)
Example #7
0
        def decorated_view(request, appname, *args, **kwargs):
            # 只允许queryset内的appname访问本站点
            try:
                app = self.app_queryset.get_by_name(appname)
            except WeChatApp.DoesNotExist:
                return response.HttpResponseNotFound()

            request = patch_request(request, appname, _app=app)
            resp = view(request, *args, **kwargs)
            return auto_response(resp)
Example #8
0
def material_proxy(request, media_id):
    """代理下载微信的素材"""
    app = request.wechat.app
    try:
        resp = app.client.material.get(media_id)
    except WeChatClientException as e:
        if e.errcode == WeChatErrorCode.INVALID_MEDIA_ID:
            return response.HttpResponseNotFound()
        logging.getLogger("wechat.views.{0}".format(app.name)).warning(
            "an exception occurred when download material", exc_info=True)
        return response.HttpResponseServerError()
    if not isinstance(resp, requests.Response):
        # 暂时只处理image和voice
        return response.HttpResponseNotFound()

    rv = response.FileResponse(resp.content)
    for k, v in resp.headers.items():
        if k.lower().startswith("content-"):
            rv[k] = v
    return rv
Example #9
0
    def get(self, request, appname, media_id):
        """代理下载微信的素材"""
        app = request.wechat.app
        try:
            resp = app.download_material(media_id)
        except WeChatClientException as e:
            if e.errcode == WeChatErrorCode.INVALID_MEDIA_ID:
                return response.HttpResponseNotFound()
            app.logger("site").warning(
                "an exception occurred when download material", exc_info=True)
            raise
        if not isinstance(resp, requests.Response):
            # 暂时只处理image和voice
            return response.HttpResponseNotFound()

        rv = response.FileResponse(resp.content)
        for k, v in resp.headers.items():
            if k.lower().startswith("content-"):
                rv[k] = v
        return rv
Example #10
0
def like_list(request):

    if anti_spider(request):
        return response.HttpResponseNotFound(
            content="<h1>Not Found</h1><p>The requested URL " +
            request.path_info + " was not found on this server.</p>")

    user = request.user.myuser
    likes = Like.objects.filter(user=user)
    artists = [l.artist for l in likes]
    context = {
        "artists": artists,
    }
    return render(request, "core/like_list.html", context)
Example #11
0
def song_list(request):

    if anti_spider(request):
        return response.HttpResponseNotFound(
            content="<h1>Not Found</h1><p>The requested URL " +
            request.path_info + " was not found on this server.</p>")

    f = SongFilter(request.GET, queryset=Song.objects.all())

    context = {
        "filter": f,
    }

    return render(request, "songs/song_list.html", context)
Example #12
0
def follow_list(request):

    if anti_spider(request):
        return response.HttpResponseNotFound(
            content="<h1>Not Found</h1><p>The requested URL " +
            request.path_info + " was not found on this server.</p>")

    user = request.user.myuser
    follow = Follow.objects.filter(fan=user)
    stars = [f.star for f in follow]
    context = {
        "stars": stars,
    }
    return render(request, "core/follow_list.html", context)
Example #13
0
def play_history(request):
    if anti_spider(request):
        return response.HttpResponseNotFound(
            content="<h1>Not Found</h1><p>The requested URL " +
            request.path_info + " was not found on this server.</p>")

    user = request.user.myuser
    play = Play.objects.filter(user=user)
    song = [p.song for p in play]
    timestamp = [p.timestamp for p in play]
    context = {
        "song": song,
        "timestamp": timestamp,
    }
    return render(request, "core/play_history.html", context)
Example #14
0
def get_speech_from_text(request):
    if request.method == 'GET' and request.is_ajax():
        try:
            res = requests.get(url=TTS_URL,
                               params={
                                   'key': TTS_KEY,
                                   'keyword': request.GET['keyword'],
                                   'return_type': 'code'
                               })
            data = json.loads(res.text)

            return response.JsonResponse(
                {'content': data['return_object']['content']})
        except Exception:
            return response.HttpResponseNotFound()
    else:
        return response.HttpResponseNotAllowed(['GET'])
Example #15
0
 def get(self,request,pk):
     """
     Carga la página de detalle de una tipo
     :param request:
     :param pk:
     :return: HttpResponse
     """
     possible_types = self.get_types_queryset(request).filter(pk=pk)
     tipo = possible_types[0] if len(possible_types) == 1 else None
     if tipo is not None:
         #cargamos el detalle
         context = {
             'form': TipoServicioForm(instance=tipo),
             'id': tipo.pk,
         }
         return render(request, 'servicios/edit_type_servicio.html',context)
     else:
         return response.HttpResponseNotFound('No existe el Tipo de servicio')#error 404
Example #16
0
 def get(self, request, pk):
     """
     Carga la página de detalle de una foto
     :param request:
     :param pk:
     :return: HttpResponse
     """
     #        possible_photos = Photo.objects.filter(pk=pk).select_related('owner')
     possible_users = self.get_users_queryset(request).filter(
         pk=pk)  #.select_related('owner')
     usuario = possible_users[0] if len(possible_users) == 1 else None
     if usuario is not None:
         #cargamos el detalle
         context = {'form': UsuarioForm(instance=usuario), 'id': usuario.pk}
         return render(request, 'users/edit_user.html', context)
     else:
         return response.HttpResponseNotFound(
             'No existe el usuario')  #error 404
Example #17
0
 def get(self,request,pk):
     """
     Carga la página de detalle de una Solicitud
     :param request:
     :param pk:
     :return: HttpResponse
     """
     possible_solicitudes = self.get_servicios_queryset(request).filter(pk=pk)
     soli = possible_solicitudes[0] if len(possible_solicitudes) == 1 else None
     if soli is not None:
         #cargamos el detalle
         context = {
             'form': SolicitudForm(instance=soli),
             'id': soli.pk,
         }
         return render(request, 'servicios/edit_solicitud.html',context)
     else:
         return response.HttpResponseNotFound('No existe la Solicitud')#error 404
Example #18
0
 def get(self,request,pk):
     """
     Carga la página de detalle de una Agendamiento
     :param request:
     :param pk:
     :return: HttpResponse
     """
     possible_agendamientos = self.get_agendamientos_queryset(request).filter(pk=pk)
     agen = possible_agendamientos[0] if len(possible_agendamientos) == 1 else None
     if agen is not None:
         #cargamos el detalle
         context = {
             'form': AgendamientoForm(instance=agen),
             'id': agen.pk,
         }
         return render(request, 'servicios/edit_agendamiento.html',context)
     else:
         return response.HttpResponseNotFound('No existe el Agendamiento')#error 404
Example #19
0
def album_detail(request, id):

    if anti_spider(request):
        return response.HttpResponseNotFound(
            content="<h1>Not Found</h1><p>The requested URL " +
                    request.path_info +
                    " was not found on this server.</p>"
        )
    album = get_object_or_404(Album, pk=id)

    context = {
        "album": album,
        "songs": album.track.all(),


    }

    return render(request, "albums/album_detail.html", context)
Example #20
0
 def get(self, request, pk):
     """
     Carga la página de detalle del producto
     :param request:
     :param pk:
     :return: HttpResponse
     """
     #        possible_photos = Photo.objects.filter(pk=pk).select_related('owner')
     possible_productos = self.get_productos_queryset(request).filter(
         pk=pk)  # .select_related('owner')
     producto = possible_productos[0] if len(
         possible_productos) == 1 else None
     if producto is not None:
         # cargamos el detalle
         context = {'prod': producto}
         return render(request, 'producto/detail_producto.html', context)
     else:
         return response.HttpResponseNotFound(
             'No existe el producto')  # error 404
Example #21
0
    def decorated_func(request, *args, **kwargs):
        app_id = kwargs.pop("wechat_app_id", None)
        object_id = kwargs.get("object_id", None)
        if not app_id:
            return correct_url(request, object_id)

        extra_context = kwargs.pop("extra_context", None) or {}
        try:
            app = site.wechat_site.get_app_queryset().get(id=app_id)
        except WeChatApp.DoesNotExist:
            return response.HttpResponseNotFound()

        # 附上app
        request.app = app
        request.app_id = app_id
        # 增加模板context
        extra_context.update(wechat_app=app, wechat_app_id=app_id)
        kwargs["extra_context"] = extra_context
        return view(request, *args, **kwargs)
Example #22
0
    def get(self,request,pk):
        """
        esto cmuestra un formulario para crear un Solicitud
        :param request:
        :return:
        """
        possible_types = TipoServicio.objects.filter(pk=pk)
        tipo = possible_types[0] if len(possible_types) == 1 else None
        if tipo is not None:
            soli = Solicitud()
            soli.tipo = tipo
            form = SolicitudForm(instance=soli)

            context = {
                'form': form,
                'success_message': ''
            }
            return render(request, 'servicios/add_solicitud.html', context)
        else:
            return response.HttpResponseNotFound('No existe la Solicitud')#error 404
Example #23
0
def playlist_list(request, uid):

    if anti_spider(request):
        return response.HttpResponseNotFound(
            content="<h1>Not Found</h1><p>The requested URL " +
            request.path_info + " was not found on this server.</p>")

    if uid == '0':
        playlists = Playlist.objects.all()
        creator = None
    else:
        playlists = Playlist.objects.filter(creator_id=uid)
        creator = MyUser.objects.get(pk=uid)
    f = PlaylistFilter(request.GET, queryset=playlists)
    context = {
        "playlists": playlists,
        "creator": creator,
        "filter": f,
    }

    return render(request, "playlists/playlist_list.html", context)
Example #24
0
    def _response_schema(self,
                         request,
                         request_obj,
                         response_schema,
                         logic_method,
                         is_paging=False):
        try:
            if is_paging:
                path = self._parse_path(request)
                response_obj = logic_method(request_obj, path)
            else:
                response_obj = logic_method(request_obj)

        except RequestParameterException as e:
            return {}, response.HttpResponseBadRequest(content=e)
        except ResourceNotFoundException as e:
            return {}, response.HttpResponseNotFound(content=e)
        except ForbiddenException as e:
            return {}, response.HttpResponseForbidden(content=e)
        except ConflictException as e:
            return {}, response.HttpResponse(content=e,
                                             status=status.HTTP_409_CONFLICT)
        return response_schema.dump(response_obj)
Example #25
0
def user_detail(request, id):

    if anti_spider(request):
        return response.HttpResponseNotFound(
            content="<h1>Not Found</h1><p>The requested URL " +
            request.path_info + " was not found on this server.</p>")

    user = get_object_or_404(MyUser, pk=id)
    loginuser = request.user
    state = 'unfollow'
    if Follow.objects.filter(star=user, fan=loginuser.myuser):
        state = 'follow'
    if loginuser.pk == user.user.pk:
        editable = True
    else:
        editable = False
    context = {
        "user": user,
        "editable": editable,
        "state": state,
    }

    return render(request, "core/user_detail.html", context)
Example #26
0
def artist_detail(request, id):

    if anti_spider(request):
        return response.HttpResponseNotFound(
            content="<h1>Not Found</h1><p>The requested URL " +
                    request.path_info +
                    " was not found on this server.</p>"
        )

    artist = get_object_or_404(Artist, pk=id)
    user = request.user
    state = 'unlike'
    if Like.objects.filter(user=user.myuser, artist=artist):
        state = 'like'
    songs = artist.song.all()
    context = {
        "state": state,
        "artist": artist,
        "songs": songs,
    }

    # return HttpResponse("Here are the artists")
    return render (request, "artists/artist_detail.html", context)
Example #27
0
def playlist_detail(request, id):

    if anti_spider(request):
        return response.HttpResponseNotFound(
            content="<h1>Not Found</h1><p>The requested URL " +
            request.path_info + " was not found on this server.</p>")

    try:
        playlist = Playlist.objects.get(pk=id)
    except Playlist.DoesNotExist:
        raise Http404
    user = request.user.myuser
    creator = playlist.creator
    if creator.pk == user.pk:
        editable = True
    else:
        editable = False
    context = {
        "playlist": playlist,
        "songs": playlist.song.all(),
        "editable": editable,
    }

    return render(request, "playlists/playlist_detail.html", context)
Example #28
0
def song_detail(request, id):

    if anti_spider(request):
        return response.HttpResponseNotFound(
            content="<h1>Not Found</h1><p>The requested URL " +
            request.path_info + " was not found on this server.</p>")

    song = get_object_or_404(Song, pk=id)

    try:
        rate = Rate.objects.get(user=request.user.myuser, song=song)
        scores = [False for i in range(5)]
        scores[rate.score - 1] = True
    except Rate.DoesNotExist:
        scores = [False for i in range(5)]
        scores[0] = True

    context = {
        "song": song,
        "scores": scores,
    }

    # return HttpResponse("song details!")
    return render(request, "songs/song_detail.html", context)
Example #29
0
def open(request, slug):
    try:
        obj = URL.objects.get(slug=slug)
    except:
        return response.HttpResponseNotFound()
    return response.HttpResponseRedirect(obj.original_link, status=301)
Example #30
0
def handler404(request, *args, **kwargs):
    return response.HttpResponseNotFound()