Example #1
0
class FooterLinkSerializer(PassiveSerializer):
    """Links returned in Config API"""

    href = CharField(read_only=True)
    name = CharField(read_only=True)
Example #2
0
class PropertyMappingTestResultSerializer(PassiveSerializer):
    """Result of a Property-mapping test"""

    result = CharField(read_only=True)
    successful = BooleanField(read_only=True)
Example #3
0
class CaptchaChallenge(WithUserInfoChallenge):
    """Site public key"""

    site_key = CharField()
    component = CharField(default="ak-stage-captcha")
Example #4
0
 def __init__(self, *args, **kwargs):
     Serializer.__init__(self, *args, **kwargs)
     for x in kwargs["context"]["axes"]:
         self.fields[x] = CharField()
Example #5
0
class CursorUUIDResponseSerializer(CursorUUIDUncountedResponseSerializer):
    total = IntegerField(help_text=_('Total result size'))
    last_url = CharField(help_text=_('Last page URL'), allow_null=True)
Example #6
0
class CollectionCreateSerializer(CollectionCreateOrUpdateSerializer):
    type = CharField(source='resource_type', read_only=True)
    uuid = CharField(source='id', read_only=True)
    id = CharField(required=True,
                   validators=[RegexValidator(regex=NAMESPACE_REGEX)],
                   source='mnemonic')
    short_code = CharField(source='mnemonic', read_only=True)
    name = CharField(required=True)
    full_name = CharField(required=False)
    description = CharField(required=False, allow_blank=True)
    text = CharField(required=False, allow_blank=True)
    collection_type = CharField(required=False)
    custom_validation_schema = CharField(required=False,
                                         allow_blank=True,
                                         allow_null=True)
    public_access = ChoiceField(required=False, choices=ACCESS_TYPE_CHOICES)
    default_locale = CharField(required=False, allow_blank=True)
    supported_locales = ListField(required=False, allow_empty=True)
    website = CharField(required=False, allow_blank=True)
    url = CharField(read_only=True)
    canonical_url = CharField(required=False,
                              allow_null=True,
                              allow_blank=True)
    custom_resources_linked_source = CharField(required=False,
                                               allow_null=True,
                                               allow_blank=True)
    repository_type = CharField(required=False,
                                allow_null=True,
                                allow_blank=True)
    preferred_source = CharField(required=False,
                                 allow_null=True,
                                 allow_blank=True)
    versions_url = CharField(read_only=True)
    concepts_url = CharField(read_only=True)
    mappings_url = CharField(read_only=True)
    owner = CharField(source='parent_resource', read_only=True)
    owner_type = CharField(source='parent_resource_type', read_only=True)
    owner_url = CharField(source='parent_url', read_only=True)
    versions = IntegerField(source='num_versions', read_only=True)
    created_on = DateTimeField(source='created_at', read_only=True)
    updated_on = DateTimeField(source='updated_at', read_only=True)
    created_by = CharField(source='owner', read_only=True)
    updated_by = CharField(read_only=True)
    extras = JSONField(required=False, allow_null=True)
    external_id = CharField(required=False, allow_blank=True)
    user_id = PrimaryKeyRelatedField(required=False,
                                     queryset=UserProfile.objects.all(),
                                     allow_null=True)
    organization_id = PrimaryKeyRelatedField(
        required=False, queryset=Organization.objects.all(), allow_null=True)
    version = CharField(default=HEAD)
    identifier = JSONField(required=False, allow_null=True)
    contact = JSONField(required=False, allow_null=True)
    jurisdiction = JSONField(required=False, allow_null=True)
    meta = JSONField(required=False, allow_null=True)
    publisher = CharField(required=False, allow_null=True, allow_blank=True)
    purpose = CharField(required=False, allow_null=True, allow_blank=True)
    copyright = CharField(required=False, allow_null=True, allow_blank=True)
    experimental = BooleanField(required=False, allow_null=True, default=None)
    locked_date = DateTimeField(required=False, allow_null=True)

    def create(self, validated_data):
        collection = self.prepare_object(validated_data)
        user = self.context['request'].user
        errors = Collection.persist_new(collection, user)
        self._errors.update(errors)
        return collection

    def create_version(self, validated_data):
        collection = self.prepare_object(validated_data)
        user = self.context['request'].user
        errors = Collection.persist_new_version(collection, user)
        self._errors.update(errors)
        return collection
Example #7
0
class CollectionVersionDetailSerializer(CollectionCreateOrUpdateSerializer):
    type = CharField(source='resource_version_type')
    uuid = CharField(source='id')
    id = CharField(source='version')
    short_code = CharField(source='mnemonic')
    owner = CharField(source='parent_resource')
    owner_type = CharField(source='parent_resource_type')
    owner_url = CharField(source='parent_url')
    created_on = DateTimeField(source='created_at')
    updated_on = DateTimeField(source='updated_at')
    supported_locales = ListField(required=False, allow_empty=True)
    is_processing = BooleanField(read_only=True)
    released = BooleanField(default=False)
    version_url = CharField(source='uri')
    url = CharField(source='versioned_object_url')
    previous_version_url = CharField(source='prev_version_uri')
    created_by = CharField(read_only=True, source='created_by.username')
    updated_by = CharField(read_only=True, source='updated_by.username')
    summary = SerializerMethodField()

    class Meta:
        model = Collection
        lookup_field = 'mnemonic'
        fields = (
            'type',
            'uuid',
            'id',
            'short_code',
            'name',
            'full_name',
            'description',
            'collection_type',
            'custom_validation_schema',
            'public_access',
            'default_locale',
            'supported_locales',
            'website',
            'url',
            'owner',
            'owner_type',
            'owner_url',
            'version_url',
            'previous_version_url',
            'created_on',
            'updated_on',
            'created_by',
            'updated_by',
            'extras',
            'external_id',
            'version',
            'version',
            'concepts_url',
            'mappings_url',
            'is_processing',
            'released',
            'retired',
            'canonical_url',
            'identifier',
            'publisher',
            'contact',
            'jurisdiction',
            'purpose',
            'copyright',
            'meta',
            'immutable',
            'revision_date',
            'summary',
            'text',
            'experimental',
            'locked_date',
            'internal_reference_id',
        )

    def __init__(self, *args, **kwargs):
        params = get(kwargs, 'context.request.query_params')
        self.include_summary = False
        if params:
            self.query_params = params.dict()
            self.include_summary = self.query_params.get(INCLUDE_SUMMARY) in [
                'true', True
            ]

        try:
            if not self.include_summary:
                self.fields.pop('summary', None)
        except:  # pylint: disable=bare-except
            pass

        super().__init__(*args, **kwargs)

    def get_summary(self, obj):
        summary = None

        if self.include_summary:
            summary = CollectionVersionSummarySerializer(obj).data

        return summary
Example #8
0
class PasswordChallenge(WithUserInfoChallenge):
    """Password challenge UI fields"""

    recovery_url = CharField(required=False)
Example #9
0
class PasswordChallengeResponse(ChallengeResponse):
    """Password challenge response"""

    password = CharField()
Example #10
0
class TicketSerializer(MHacksModelSerializer):
    id = CharField(read_only=True)
    creator = MHacksUserSerializer(read_only=True)
    mentor = MHacksUserSerializer(read_only=True)
    title = CharField(required=True)
    description = CharField(required=True)

    _remove_from_request = ('id', 'creator', 'mentor')

    class Meta:
        model = TicketModel
        fields = ('id', 'title', 'description', 'creator', 'mentor',
                  'accepted', 'completed', 'area')

    # TODO better validation (invalid fields within mentor, check for required fields)
    # TODO raise validation errors when data is invalid
    def run_validation(self, data=None):
        for key in data.keys():
            if key in self._remove_from_request or key not in self.fields:
                data.pop(key)
        return data

    def create(self, validated_data):
        creator = self.context.get('request').user
        ticket = TicketModel.objects.create(creator=creator, **validated_data)
        ticket.save()
        return ticket

    def update(self, instance, validated_data):
        user = self.context.get('request').user

        if 'accepted' in validated_data.keys():
            instance = self._assign_ticket(instance,
                                           validated_data.get('accepted'),
                                           user)
            return instance

        if 'completed' in validated_data.keys():
            instance = self._complete_ticket(instance,
                                             validated_data.get('completed'),
                                             user)
            return instance

        if instance.creator.id != user.id and not user.is_superuser:
            raise Exception('You can\'t modify this.')
        for attr, value in validated_data.iteritems():
            setattr(instance, attr, value)
        instance.save()
        return instance

    @staticmethod
    def _assign_ticket(instance, value, user):
        if value:
            if instance.mentor:
                raise Exception('A mentor has already taken this ticket.')
            instance.mentor = user
            instance.accepted = True
        else:
            if not instance.mentor:
                raise Exception('This ticket is already unassigned')
            if instance.mentor.id != user.id and instance.creator.id != user.id:
                raise Exception('You can\'t unassign someone else')
            instance.mentor = None
            instance.accepted = False
        instance.save()
        return instance

    @staticmethod
    def _complete_ticket(instance, value, user):
        if not (user.id == instance.creator.id or
                (instance.mentor and user.id == instance.mentor.id)):
            raise Exception(
                'Only individuals associated with a ticket can mark it completed.'
            )
        if value:
            instance.completed = True
        else:
            instance.mentor = None
            instance.accepted = False
            instance.completed = False

        instance.save()
        return instance
class ServiceConnectionStateSerializer(PassiveSerializer):
    """Serializer for Service connection state"""

    healthy = BooleanField(read_only=True)
    version = CharField(read_only=True)
Example #12
0
class LocationSerializer(MHacksModelSerializer):
    id = CharField(read_only=True)

    class Meta:
        model = LocationModel
        fields = ('id', 'name', 'latitude', 'longitude')
Example #13
0
class UserCommentEditReqSerializer(Serializer):

    movie_id = IntegerField(required=True)
    score = IntegerField(required=True, max_value=10, min_value=0)
    body = CharField(required=False)
Example #14
0
class UserLoginReqSerializer(Serializer):

    email = CharField(required=True)
    password = CharField(required=True)
Example #15
0
class PlexAuthenticationChallengeResponse(ChallengeResponse):
    """Pseudo class for plex response"""

    component = CharField(default="ak-flow-sources-plex")
Example #16
0
class UserTokenSerializer(TokenObtainPairSerializer):  # noqa
    token = CharField(min_length=7, required=True)
Example #17
0
class PartSerializer(Serializer):
    ETag = CharField()
    PartNumber = IntegerField(min_value=1, max_value=10_000)
    LastModified = DateTimeField()
    Size = IntegerField(min_value=0)
Example #18
0
class TestSerializer(NoneOmittedSerializerMixin, Serializer):
    data_field = CharField()
    empty_field = CharField()
Example #19
0
class CollectionDetailSerializer(CollectionCreateOrUpdateSerializer):
    type = CharField(source='resource_type')
    uuid = CharField(source='id')
    id = CharField(source='mnemonic')
    short_code = CharField(source='mnemonic')
    owner = CharField(source='parent_resource')
    owner_type = CharField(source='parent_resource_type')
    owner_url = CharField(source='parent_url')
    created_on = DateTimeField(source='created_at')
    updated_on = DateTimeField(source='updated_at')
    supported_locales = ListField(required=False, allow_empty=True)
    created_by = CharField(read_only=True, source='created_by.username')
    updated_by = CharField(read_only=True, source='updated_by.username')
    references = SerializerMethodField()
    summary = SerializerMethodField()
    client_configs = SerializerMethodField()

    class Meta:
        model = Collection
        lookup_field = 'mnemonic'
        fields = ('type', 'uuid', 'id', 'short_code', 'name', 'full_name',
                  'description', 'collection_type', 'custom_validation_schema',
                  'public_access', 'default_locale', 'supported_locales',
                  'website', 'url', 'owner', 'owner_type', 'owner_url',
                  'created_on', 'updated_on', 'created_by', 'updated_by',
                  'extras', 'external_id', 'versions_url', 'version',
                  'concepts_url', 'mappings_url',
                  'custom_resources_linked_source', 'repository_type',
                  'preferred_source', 'references', 'canonical_url',
                  'identifier', 'publisher', 'contact', 'jurisdiction',
                  'purpose', 'copyright', 'meta', 'immutable', 'revision_date',
                  'logo_url', 'summary', 'text', 'client_configs',
                  'experimental', 'locked_date', 'internal_reference_id')

    def __init__(self, *args, **kwargs):
        params = get(kwargs, 'context.request.query_params')
        self.query_params = params.dict() if params else dict()
        self.include_summary = self.query_params.get(INCLUDE_SUMMARY) in [
            'true', True
        ]
        self.include_client_configs = self.query_params.get(
            INCLUDE_CLIENT_CONFIGS) in ['true', True]

        try:
            if not self.include_summary:
                self.fields.pop('summary', None)
            if not self.include_client_configs:
                self.fields.pop('client_configs', None)
        except:  # pylint: disable=bare-except
            pass

        super().__init__(*args, **kwargs)

    def get_summary(self, obj):
        summary = None

        if self.include_summary:
            summary = CollectionSummarySerializer(obj).data

        return summary

    def get_client_configs(self, obj):
        if self.include_client_configs:
            return ClientConfigSerializer(
                obj.client_configs.filter(is_active=True), many=True).data

        return None

    def get_references(self, obj):
        if self.context.get(INCLUDE_REFERENCES_PARAM, False):
            return CollectionReferenceSerializer(obj.references.all(),
                                                 many=True).data

        return []
Example #20
0
class UsersSerializers(serializers.ModelSerializer):
    password_confirm = CharField(label="确认密码",
                                 help_text="确认密码",
                                 max_length=128,
                                 write_only=True)
    token = CharField(label="token",
                      help_text="token",
                      max_length=128,
                      read_only=True)

    class Meta:
        model = models.User
        fields = ("id", "username", "email", "password", "password_confirm",
                  "token")
        write_only = ["email", "password"]
        extra_kwargs = {
            "username": {
                "label": "用户名",
                "help_text": "用户名",
                "min_length": 6,
                "max_length": 20,
                "error_messages": {
                    "min_length": "仅允许输入6-20个字符",
                    "max_length": "仅允许输入6-20个字符",
                }
            },
            "email": {
                "label":
                "邮箱",
                "help_text":
                "邮箱",
                "write_only":
                True,
                "required":
                True,
                "validators": [
                    UniqueValidator(queryset=models.User.objects.all(),
                                    message="此邮箱已被注册")
                ]
            },
            "password": {
                "label": "密码",
                "help_text": "密码",
                "min_length": 6,
                "max_length": 20,
                "write_only": True,
                "error_messages": {
                    "min_length": "仅允许输入6-20个字符",
                    "max_length": "仅允许输入6-20个字符",
                }
            },
        }

    def validate(self, attrs):
        password_ = attrs["password_confirm"]
        if attrs["password"] != password_:
            raise serializers.ValidationError("密码与确认密码必须一致")
        del attrs["password_confirm"]
        return attrs

    def create(self, validated_data):
        # 重置加密密码
        # create_user会对密码进行加密
        user = models.User.objects.create_user(**validated_data)
        # 生成token
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user
Example #21
0
class CollectionReferenceSerializer(ModelSerializer):
    reference_type = CharField(read_only=True)

    class Meta:
        model = CollectionReference
        fields = ('expression', 'reference_type', 'id')
Example #22
0
class UserWorkedOnSerializer(Serializer):
    id = IntegerField()
    title = CharField()
    position = CharField()
    start_datetime = DateTimeField()
    end_datetime = DateTimeField()
Example #23
0
class PageNumberResponseSerializer(PageNumberUncountedResponseSerializer):
    total = IntegerField(help_text=_('Total result size'))
    last_url = CharField(help_text=_('Last page URL'), allow_null=True)
Example #24
0
class UserDetailSerializer(ModelSerializer):
    AVATAR_PROVIDER_CHOICES = (
        ("facebook", "Facebook"),
        ("google-oauth2", "Google"),
        ("gravatar", "Gravatar"),
    )

    first_name = CharField(max_length=150, required=False)
    last_name = CharField(max_length=150, required=False)
    email = EmailField(required=False)
    profile = UserProfileSerializerWithAvatar(read_only=True,
                                              source="userprofile")
    ban = BanUserSerializer(read_only=True)
    if all(elem in settings.INSTALLED_APPS for elem in
           ["rest_social_auth", "social_django"]):  # pragma: no cover
        social_accounts = UserSocialProfileSerializer(many=True,
                                                      read_only=True,
                                                      source="social_auth")
    groups = SlugRelatedField(many=True, read_only=True, slug_field="name")
    role = SerializerMethodField(read_only=True)
    phone_number = PhoneNumberField(write_only=True, required=False)
    avatar_provider = ChoiceField(write_only=True,
                                  choices=AVATAR_PROVIDER_CHOICES,
                                  required=False)

    class Meta:
        model = User
        fields = (
            "id",
            "first_name",
            "last_name",
            "username",
            "email",
            "profile",
            "ban",
            "groups",
            "role",
            "phone_number",
            "avatar_provider",
        )
        read_only_fields = ("id", "username", "profile", "ban", "groups",
                            "role")
        write_only_fields = ("phone_number", "avatar_provider")

        if all(elem in settings.INSTALLED_APPS for elem in
               ["rest_social_auth", "social_django"]):  # pragma: no cover
            fields += ("social_accounts", )
            read_only_fields += ("social_accounts", )

    def update(self, instance, validated_data):
        if "phone_number" in validated_data:
            instance.userprofile.phone_number = validated_data.pop(
                "phone_number")
        if "avatar_provider" in validated_data and instance.userprofile.avatar.get(
                validated_data["avatar_provider"], None):
            instance.userprofile.avatar["provider"] = validated_data.pop(
                "avatar_provider")
        return super(UserDetailSerializer,
                     self).update(instance, validated_data)

    @staticmethod
    def get_role(user):
        return user.role
Example #25
0
class MHacksUserSerializer(MHacksModelSerializer):
    id = CharField(read_only=True)

    class Meta:
        model = MHacksUser
        fields = ('id', 'first_name', 'last_name', 'email')
Example #26
0
class ModifiedFilesSerializer(serializers.Serializer):
    modifiedFile = CharField(max_length=200)
    additions = IntegerField()
    changes = IntegerField()
    deletions = IntegerField()
    status = CharField(max_length=30)
Example #27
0
class PositionFileSerializer(Serializer):
    positionFile = FileField()
    portfolio = CharField(max_length=20)

    class Meta:
        fields = '__all__'
Example #28
0
class PlexAuthenticationChallenge(Challenge):
    """Challenge shown to the user in identification stage"""

    client_id = CharField()
    slug = CharField()
    component = CharField(default="ak-flow-sources-plex")
Example #29
0
class TimezoneSerializer(Serializer):
    """Serialize Timezone submission from front end."""

    timezone = CharField(min_length=2)
Example #30
0
class main_analysis(models.Model):

    text = CharField(max_length=200)
    coord = CharField(max_length=200)
    # 환경변수 불러오기(서비스 계정 키가 저장된 경로로 설정)
    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'files/toycherry3-f3c605d8bce5.json'
    
    # 형태소 분석
    def morp_analysis(self):
        noun_text = re.sub('[-_=+,#/\?:^$.@*\"※~&%ㆍ·!』\\‘’|\(\)\[\]\<\>`\'…》]', '', str(self))

        noun_text = re.sub('\n', '', noun_text)

        hannanum = Hannanum()
        text_list = hannanum.nouns(noun_text)  # 명사 분석

        word_list = pd.Series(text_list)
        result = word_list.value_counts().head(10)
        result_values = list(result.values)

        for i in range(len(result_values)):
            result_values[i] = np.int16(result_values[i]).item()

        freq_lst = []
        for i in range(len(result)):
            freq_lst.append({'word': result.keys()[i], 'freq': result_values[i]})

        return freq_lst

    # 개체명 인식(장소, 이벤트 인식)
    def NER(self, coord):
        # 클라이언트 인스턴스화
        NER_client = language_v1.LanguageServiceClient()
        # translate_client = translate.Client()

        # 요청 보낼 document 설정
        # Document.Type: TYPE_UNSPECIFIED, PLAIN_TEXT, HTML
        # translated_text = translate_client.translate(text, target_language='en')['translatedText']
        document = language_v1.Document(
            content=self,
            type_=language_v1.Document.Type.PLAIN_TEXT
        )

        # translated_document = language_v1.Document(
        #     content=translated_text,
        #     type_=language_v1.Document.Type.PLAIN_TEXT
        # )

        # 감정(Sentiment)
        # sentiment = client.analyze_sentiment(request={'document': document}).document_sentiment
        # 개체(Entity)
        entities = NER_client.analyze_entities(request={'document': document}).entities
        # translated_entities = NER_client.analyze_entities(request={'document': translated_document}).entities
        # sentiment = NER_client.analyze_sentiment(request={'document': document}).sentences

        entities_lst = []
        # translated_entities_lst = []
        entities_name_lst = []
        entities_type_lst = []
        # translated_entities_name_lst = []
        # translated_entities_type_lst = []

        for i in range(len(entities)):
            entity_name = entities[i].name  # 개체 이름
            entity_type = str(entities[i].type_)[5:]  # 개체 종류
            entities_lst.append((entity_name, entity_type))
            entities_name_lst.append(entity_name)
            entities_type_lst.append(entity_type)

        entities_lst = list(set(entities_lst))

        # for i in range(len(translated_entities)):
        #     entity_name = translated_entities[i].name  # 개체 이름
        #     entity_type = str(translated_entities[i].type_)[5:]  # 개체 종류
        #     translated_entities_lst.append((entity_name, entity_type))
        #     translated_entities_name_lst.append(entity_name)
        #     translated_entities_type_lst.append(entity_type)
        #
        # translated_entities_lst = list(set(translated_entities_lst))

        # 장소만 추출하기
        loc_lst = []

        for i in range(len(entities_lst)):
            if entities_lst[i][1] == 'LOCATION' or entities_lst[i][1] == 'ADDRESS':
                loc_lst.append(entities_lst[i])

        # # 이벤트만 추출하기
        # event_lst = []
        #
        # for i in range(len(translated_entities_lst)):
        #     if translated_entities_lst[i][1] == 'EVENT':
        #         event_lst.append(translated_entities_lst[i])
        #
        # event_cnt = len(event_lst)  # 이벤트 개수

        # 텍스트 기반 저장
        if len(loc_lst) > 0:
            korea_geo = pd.read_csv('files/korea_geo.csv',encoding='CP949')
            ctp_lst = list(korea_geo['ctp_kor'])
            geo_lst = ['시', '군', '구', '읍', '면', '동', '리', '통', '반']

            for i in range(len(ctp_lst)):
                if ctp_lst[i][-1] in geo_lst:
                    new_ctp = ctp_lst[i][0:-1]
                    ctp_lst.append(new_ctp)

            r_loc = []
            for i in range(len(loc_lst)):
                if loc_lst[i][0] in ctp_lst:
                    r_loc.append({'loc': loc_lst[i][0], 'tag': loc_lst[i][1]})

        # 유저 좌표 기반 저장
        else:
            if len(coord) == 0:
                r_loc = []
                r_loc.append({'loc': None, 'tag': None})
            else:
                coord_lst = coord.split(' ')
                city_lst = ['시', '군', '구']
                town_lst = ['읍', '면', '동', '리', '통', '반']
                city_name = ''
                town_name = ''

                for i in range(len(coord_lst)):
                    # 시, 군, 구
                    if coord_lst[i][-1] in city_lst:
                        city_name = coord_lst[i]

                    # 읍, 면, 동, 리
                    elif coord_lst[i][-1] in town_lst:
                        town_name = coord_lst[i]

                if len(city_name) != 0 or len(town_name) != 0:
                    r_loc = []
                    r_loc.append({'loc': city_name + ' ' + town_name, 'tag': 'LOCATION'})
                else:
                    r_loc = []
                    r_loc.append({'loc': None, 'tag': None})

        return r_loc

    # 해당 지역의 날씨
    def crawling_temp(self):  # 튜플
        loc_querry = urllib.parse.quote(self[0]['loc'] + ' 날씨')

        url = 'https://search.naver.com/search.naver?ie=utf8&query=' + loc_querry
        req = Request(url)
        page = urlopen(req)
        html = page.read()
        soup = bs4.BeautifulSoup(html, 'html5lib')

        # print(loc, '|', soup.find('p', class_='info_temperature').find('span', class_='todaytemp').text + '도')
        temp = soup.find('p', class_='info_temperature').find('span', class_='todaytemp').text
        cast_txt = soup.find('p', class_='cast_txt').text
        min_temp = soup.find('span', class_='min').text
        max_temp = soup.find('span', class_='max').text
        sensible_temp = soup.find('span', class_='sensible').text

        tomorrow_info = soup.findAll('div', class_='main_info morning_box')

        temp_D1_AM = tomorrow_info[0].find('p', class_='info_temperature').find('span', class_='todaytemp').text
        temp_D1_PM = tomorrow_info[1].find('p', class_='info_temperature').find('span', class_='todaytemp').text
        cast_txt_D1_AM = tomorrow_info[0].find('p', class_='cast_txt').text
        cast_txt_D1_PM = tomorrow_info[1].find('p', class_='cast_txt').text
        temp_D2_AM = tomorrow_info[2].find('p', class_='info_temperature').find('span', class_='todaytemp').text
        temp_D2_PM = tomorrow_info[3].find('p', class_='info_temperature').find('span', class_='todaytemp').text
        cast_txt_D2_AM = tomorrow_info[2].find('p', class_='cast_txt').text
        cast_txt_D2_PM = tomorrow_info[3].find('p', class_='cast_txt').text

        temp_info = {
            'loc': self[0]['loc'],
            'today':
                {
                    'temp': temp,
                    'cast_txt': cast_txt,
                    'min_temp': min_temp,
                    'max_temp': max_temp,
                    'sensible_temp': sensible_temp,
                },
            'D1':
                {
                    'temp_D1_AM': temp_D1_AM,
                    'temp_D1_PM': temp_D1_PM,
                    'cast_txt_D1_AM': cast_txt_D1_AM,
                    'cast_txt_D1_PM': cast_txt_D1_PM,
                },
            'D2':
                {
                    'temp_D2_AM': temp_D2_AM,
                    'temp_D2_PM': temp_D2_PM,
                    'cast_txt_D2_AM': cast_txt_D2_AM,
                    'cast_txt_D2_PM': cast_txt_D2_PM,
                }
        }

        return temp_info

    def crawling_res(self):
        loc_querry = urllib.parse.quote(self[0]['loc'] + ' 맛집')
        url = 'https://m.search.naver.com/search.naver?ie=utf8&query=' + loc_querry

        whole_lst = []

        # 맛집리스트 형식이 맞게 나올 때까지 반복
        req = Request(url)
        page = urlopen(req)
        html = page.read()
        soup = bs4.BeautifulSoup(html, 'html5lib')
        whole_lst = soup.findAll('li', class_='_3t81n')

        new_dict = []
        for i in range(len(whole_lst)):
            rest_name = whole_lst[i].find('span', class_='_3Yilt').text[2:]
            # try:
            #     rest_category = whole_lst[i].find('span', class_='category').text
            # except:
            #     rest_category = ''
            try:
                rest_rate = whole_lst[i].find('span', class_='_3Yzhl _1ahw0').text[2:]
            except:
                rest_rate = '0.00'
            try:
                sub_lst = whole_lst[i].find('div', class_='cb7hz undefined')['style'].split(';')
                img_path = sub_lst[2].split('(')[1].split(')')[0]
            except:
                img_path = '#'
            try:
                rest_url = whole_lst[i].find('a', class_='Ow5Yt')['href']
            except:
                rest_url = '#'

            sub_dict = {
                'rest_name': rest_name,
                # 'rest_category': rest_category,
                'rest_rate': rest_rate,
                'rest_url': rest_url,
                'img_path': img_path,
            }

            new_dict.append(sub_dict)

        rest_info = {
            'loc': self[0]['loc'],
            'rest_lst': new_dict
        }

        return rest_info

    # def crawling_res_2(location):
    #     # 웹 드라이버 설정
    #     options = webdriver.ChromeOptions()
    #     options.add_argument('headless')  # 웹 브라우저를 띄우지 않는 headless chrome 옵션 적용
    #     options.add_argument('window-size=1920x1080')
    #     options.add_argument('disable-infobars')
    #     options.add_argument('--disable-extensions')
    #     options.add_argument('disable-gpu')  # GPU 사용 안함
    #     options.add_argument('lang=ko_KR')  # 언어 설정
    #     driver = webdriver.Chrome('files/chromedriver.exe', options=options)
    #
    #     # 검색
    #     driver.get('https://www.google.co.kr/maps')  # 구글 열기
    #
    #     search_box = driver.find_element_by_name("q")  # 검색창 찾기
    #     search_box.clear()  # 검색창 비우기(채워져 있는 경우가 있음)
    #     search_box.send_keys(location[0] + '의 맛집')  # 검색어 입력
    #
    #     search_btn = driver.find_element_by_id('searchbox-searchbutton')
    #     search_btn.click()
    #     time.sleep(5)
    #
    #     # 가게 정보 찾기
    #     whole_lst = driver.find_element_by_xpath("//*[@class='section-layout section-scrollbox scrollable-y scrollable-show section-layout-flex-vertical']")
    #     item = whole_lst.find_elements_by_xpath("//*[@class='section-result']")
    #     rest_lst = []
    #
    #     for i in range(len(item)):
    #         splited_item = item[i].text.split('\n')
    #
    #         if '광고·' in splited_item:
    #             pass
    #         else:
    #             try:
    #                 rest_img_path = item[i].find_element_by_xpath("div//*[@class='section-result-image']")
    #                 style_attribute = rest_img_path.get_attribute('style')
    #                 rest_img_url = re.search(r"\((.+)\)(.+)", style_attribute).groups()[0][1:-1]
    #
    #                 splited_item[1] = float(splited_item[1][0:3])
    #                 new_row = (splited_item[0], splited_item[1], rest_img_url)
    #                 rest_lst.append(new_row)
    #
    #                 # rest_img = item[i].find_element_by_xpath("div//*[@class='tLipRb']")
    #                 # img_path = 'rest_img/' + splited_item[0] + '_img.png'
    #                 # rest_img.screenshot(img_path)
    #             except:
    #                 pass
    #     rest_dict = {'loc': location[0], 'rest_lst': rest_lst}
    #
    #     # 드라이버 종료
    #     driver.quit()
    #
    #     return rest_dict