示例#1
0
def test_raise_does_not_exist():
    try:
        raise DoesNotExist("My Test Message")
    except DoesNotExist as e:
        pickle_instance = pickle.dumps(e)
        assert pickle_instance
        assert pickle.loads(pickle_instance)
        assert isinstance(pickle.loads(pickle_instance), DoesNotExist)
示例#2
0
def update_search_query(username, query_param, keywords):
    """
    This task creates a search query node then calls the task to create and
    attach keyword nodes to the search query node

    :param username:
    :param query_param:
    :param keywords:
    :return:
    """
    try:
        res, _ = db.cypher_query("MATCH (a:Pleb {username:'******'}) RETURN a" %
                                 username)
        if res.one:
            res.one.pull()
            pleb = Pleb.inflate(res.one)
        else:
            raise update_search_query.retry(exc=DoesNotExist(
                "Profile with username: "******"%s does not exist" % username),
                                            countdown=3,
                                            max_retries=None)
    except (CypherException, IOError) as e:
        raise update_search_query.retry(exc=e, countdown=3, max_retries=None)
    try:
        search_query = SearchQuery.nodes.get(search_query=query_param)
        if pleb.searches.is_connected(search_query):
            rel = pleb.searches.relationship(search_query)
            rel.times_searched += 1
            rel.last_searched = datetime.now(pytz.utc)
            rel.save()
            return True
        else:
            rel = pleb.searches.connect(search_query)
            rel.save()
            search_query.searched_by.connect(pleb)
            return True
    except (SearchQuery.DoesNotExist, DoesNotExist):
        search_query = SearchQuery(search_query=query_param)
        search_query.save()
        search_query.searched_by.connect(pleb)
        rel = pleb.searches.connect(search_query)
        rel.save()
        for keyword in keywords:
            keyword['query_param'] = query_param
            spawned = spawn_task(task_func=create_keyword, task_param=keyword)
            if isinstance(spawned, Exception) is True:
                return spawned
        return True
    except (CypherException, IOError) as e:
        raise update_search_query.retry(exc=e, countdown=3, max_retries=None)
    except Exception as e:
        raise update_search_query.retry(exc=e, countdown=3, max_retries=None)
示例#3
0
 def get(cls, object_uuid):
     mission = cache.get("%s_mission" % object_uuid)
     if mission is None:
         query = 'MATCH (c:`Mission` {object_uuid: "%s"}) RETURN c' % \
                 object_uuid
         res, _ = db.cypher_query(query)
         if res.one:
             res.one.pull()
             mission = cls.inflate(res.one)
             cache.set("%s_mission" % object_uuid, mission)
         else:
             raise DoesNotExist("Mission does not exist")
     return mission
示例#4
0
 def get(cls, owner_username, cache_buster=False):
     quest = None
     if cache_buster is False:
         quest = cache.get("%s_quest" % owner_username)
     if quest is None or cache_buster:
         query = 'MATCH (c:Quest {owner_username: "******"}) RETURN c' % \
                 owner_username
         res, _ = db.cypher_query(query)
         if res.one:
             res.one.pull()
             quest = cls.inflate(res.one)
             cache.set("%s_quest" % owner_username, quest)
         else:
             raise DoesNotExist("Quest does not exist")
     return quest
示例#5
0
 def get(cls, username, cache_buster=False):
     profile = None
     if username is None:
         return None
     if cache_buster is False:
         profile = cache.get(username)
     if profile is None or cache_buster:
         res, _ = db.cypher_query(
             "MATCH (a:%s {username:'******'}) RETURN a" % (
                 cls.__name__, username))
         if res.one:
             res.one.pull()
             profile = cls.inflate(res.one)
         else:
             raise DoesNotExist('Profile with username: %s '
                                'does not exist' % username)
         cache.set(username, profile)
     return profile
示例#6
0
 def get(cls, object_uuid):
     question = cache.get(object_uuid)
     if question is None:
         res, _ = db.cypher_query(
             "MATCH (a:%s {object_uuid:'%s'}) RETURN a" % (
                 cls.__name__, object_uuid))
         try:
             try:
                 res[0][0].pull()
             except(ClientError, Exception):
                 # This is here because in local development we've seen
                 # res[0][0] create a runtime exception
                 pass
             question = cls.inflate(res[0][0])
         except IndexError:
             raise DoesNotExist('Question with id: %s '
                                'does not exist' % object_uuid)
         cache.set(object_uuid, question)
     return question
示例#7
0
 def set_encompassing(self):
     from .tasks import connect_to_state_districts
     try:
         encompassed_by = Location.nodes.get(name=self.city)
         if Location.get_single_encompassed_by(
                 encompassed_by.object_uuid) != \
                 us.states.lookup(self.state).name:
             # if a location node exists with an incorrect encompassing
             # state
             raise DoesNotExist("This Location does not exist")
     except (Location.DoesNotExist, DoesNotExist):
         encompassed_by = Location(name=self.city, sector="local").save()
         try:
             city_encompassed = Location.nodes.get(
                 name=us.states.lookup(self.state).name)
         except (Location.DoesNotExist, DoesNotExist):
             city_encompassed = Location(name=us.states.lookup(
                 self.state).name,
                                         sector="federal").save()
         if city_encompassed not in encompassed_by.encompassed_by:
             encompassed_by.encompassed_by.connect(city_encompassed)
         if encompassed_by not in city_encompassed.encompasses:
             city_encompassed.encompasses.connect(encompassed_by)
     except (MultipleNodesReturned, Exception):
         query = 'MATCH (l1:Location {name:"%s"})-[:ENCOMPASSED_BY]->' \
                 '(l2:Location {name:"%s"}) RETURN l1' % \
                 (self.city, self.state)
         res, _ = db.cypher_query(query)
         if res.one is not None:
             encompassed_by = Location.inflate(res.one)
         else:
             encompassed_by = None
     if encompassed_by is not None:
         if encompassed_by not in self.encompassed_by:
             self.encompassed_by.connect(encompassed_by)
     # get or create the state level districts and attach them to the
     # address
     spawn_task(task_func=connect_to_state_districts,
                task_param={'object_uuid': self.object_uuid})
     return self
示例#8
0
def update_search_object(object_uuid,
                         label=None,
                         object_data=None,
                         index="full-search-base"):
    from plebs.serializers import PlebSerializerNeo
    from sb_quests.serializers import QuestSerializer
    from sb_quests.neo_models import Quest
    from sb_missions.serializers import MissionSerializer
    from sb_missions.neo_models import Mission
    from sb_questions.serializers import QuestionSerializerNeo
    from sb_base.neo_models import get_parent_votable_content
    if label is None:
        label = get_parent_votable_content(
            object_uuid).get_child_label().lower()
    logger.critical("Updating Search Object")
    logger.critical({"object_uuid": object_uuid})
    query = 'MATCH (a:%s {object_uuid:"%s"}) RETURN a' % \
            (label.title(), object_uuid)
    res, _ = db.cypher_query(query)
    if res.one:
        res.one.pull()
    else:
        raise update_search_object.retry(exc=DoesNotExist(
            'Object with uuid: %s '
            'does not exist' % object_uuid),
                                         countdown=3,
                                         max_retries=None)
    if label == "question":
        instance = Question.inflate(res.one)
        object_data = QuestionSerializerNeo(instance).data
        if 'mission' in object_data:
            object_data.pop('mission')
        if 'profile' in object_data:
            object_data.pop('profile')
        logger.critical(object_data)
    elif label == "quest":
        instance = Quest.inflate(res.one)
        object_data = QuestSerializer(instance).data
        logger.critical(object_data)
    elif label == "mission":
        instance = Mission.inflate(res.one)
        object_data = MissionSerializer(instance).data
        # Need to pop review_feedback because ES's serializer cannot parse
        # set types.
        # If we don't pop it we receive
        # TypeError("Unable to serialize set([]) (type: <type 'set'>)",))
        # If we can submit a JSON serialized version we can get around this by
        # using:
        # from rest_framework.renderers import JSONRenderer
        # JSONRenderer().render(serializer.data)
        # Also please note python's json.dumps() function runs into this same
        # issue.
        if 'review_feedback' in object_data:
            object_data.pop('review_feedback', None)
        if 'quest' in object_data:
            object_data.pop('quest')
        logger.critical(object_data)
    elif label == "pleb":
        instance = Pleb.inflate(res.one)
        object_data = PlebSerializerNeo(instance).data
        if 'quest' in object_data:
            object_data.pop('quest')
        logger.critical(object_data)
    else:
        # Currently we only need this functionality for Questions as
        # they are the only objects in search that we display votes
        # for in the search interface.
        error_dict = {
            "message": "Search False setup. "
            "Object Data None, Instance not None",
            "instance_label": label,
            "instance_uuid": object_uuid,
        }
        logger.critical(error_dict)
        return False
    try:
        es = Elasticsearch(settings.ELASTIC_SEARCH_HOST)
        res = es.index(index=index,
                       doc_type=object_data['type'],
                       id=object_uuid,
                       body=object_data)
    except (ElasticsearchException, TransportError, ConflictError,
            RequestError) as e:
        logger.exception("Failed to connect to Elasticsearch")
        logger.critical(object_data)
        raise update_search_object.retry(exc=e, countdown=5, max_retries=None)
    except KeyError:
        error_dict = {
            "message": "Search: KeyError False creation",
            "instance_uuid": object_uuid,
            "object_data": object_data
        }
        logger.critical(error_dict)
        return False
    try:
        if instance.search_id is None:
            instance.search_id = res['_id']
            instance.populated_es_index = True
            instance.save()
    except AttributeError:
        pass

    cache.delete("%s_vote_search_update" % object_uuid)
    return res
示例#9
0
def watch(bot, update):
    ''' Returns a link to the video of episode. '''
    def parse(text):
        matches = [
            re.search(r'/watch (.+) s(\d+) e(\d+)', text),
            re.search(r'/watch (.+) s(\d+)', text),
            re.search(r'/watch (.+)', text)
        ]

        if not matches[0] is None:
            show_title, season_number, episode_number = matches[0].group(
                1, 2, 3)
        elif not matches[1] is None:
            show_title, season_number, episode_number = matches[1].group(
                1, 2) + (None, )
        elif not matches[2] is None:
            show_title, season_number, episode_number = (matches[2].group(1),
                                                         None, None)
        else:
            show_title, season_number, episode_number = ('', None, None)

        return show_title.strip().lower(), season_number, episode_number

    chat = Chat.get_or_create(id=update.message.chat_id)

    response, reply_markup = None, ReplyKeyboardHide()

    if not chat.referer:
        show_title, season_number, episode_number = parse(update.message.text)
    else:
        show_title, season_number, episode_number = parse(chat.referer)

        if not show_title:
            show_title = update.message.text[7:].strip().lower()
        elif not season_number:
            try:
                season_number = int(
                    update.message.text.split(chat.referer + ' s')[1])
            except ValueError:
                response = _('Invalide season number.')
        else:
            try:
                episode_number = int(
                    update.message.text.split(chat.referer + ' e')[1])
            except ValueError:
                response = _('Invalid episode number.')

    if not response:
        if show_title:
            try:
                show = Show.nodes.get(title_lower=show_title)

                if show.is_available:
                    if season_number:
                        try:
                            season = show.seasons.get(number=season_number)

                            if season.is_available:
                                if episode_number:
                                    try:
                                        episode = season.episodes.get(
                                            number=episode_number)

                                        if episode.is_available:

                                            response = _(
                                                'We will send you video soon.')
                                            chat.referer = update.message.text

                                            VideoFinder(
                                                bot=bot,
                                                chat_id=update.message.chat_id,
                                                episode=episode).start()

                                        else:
                                            raise DoesNotExist({
                                                'episode_number':
                                                episode_number
                                            })
                                    except DoesNotExist:
                                        response = _(
                                            'This episode is not available.')
                                        chat.referer = ''
                                else:
                                    response = _(
                                        'Which episode would you like to see?')
                                    chat.referer, l = update.message.text, sorted(
                                        [
                                            str(ep.number)
                                            for ep in season.available_episodes
                                        ],
                                        key=lambda x: int(x))
                                    reply_markup = ReplyKeyboardMarkup([
                                        l[i:i + 3]
                                        for i in range(0, len(l), 3)
                                    ])
                            else:
                                raise DoesNotExist(
                                    {'season_number': season_number})
                        except DoesNotExist:
                            response = _('This season is not available.')
                            chat.referer = ''
                    else:
                        response = _('Which season would you like to see?')
                        chat.referer, l = update.message.text, sorted(
                            [str(s.number) for s in show.available_seasons],
                            key=lambda x: int(x))
                        reply_markup = ReplyKeyboardMarkup(
                            [l[i:i + 3] for i in range(0, len(l), 3)])
                else:
                    raise DoesNotExist({'show_title': show_title})
            except DoesNotExist:
                response = _('Specified series is not on my list, '
                             'but we will try to find this series.')
                ShowFinder(bot=bot,
                           chat_id=update.message.chat_id,
                           show_title=show_title).start()
        else:
            response = _('Which TV show would you like to see?')
            chat.referer = update.message.text

    bot.sendMessage(chat_id=update.message.chat_id,
                    text=response,
                    reply_markup=reply_markup)
    chat.save()