示例#1
0
文件: views.py 项目: wohui/pxiv
 def get_img_data(request):
     if request.method == 'POST':
         # 获取10个img_url
         pxiv_url = "https://api.imjad.cn/pixiv/v1/"
         pxiv_data = {
             "type": "search",
             "per_page": 10,
             "word": "初音",
             "page": 1,
         }
         pxiv_res = requests.get(pxiv_url, pxiv_data, verify=False)
         json_obj = json.loads(pxiv_res.text)
         data = []
         for i in range(0, 10):
             pxiv_img_url = json_obj['response'][i]['image_urls'][
                 'px_480mw']
             pxiv_img_base64_data = "data:image/jpeg;base64," + get_img_base64_data(
                 pxiv_img_url)
             data.append(pxiv_img_base64_data)
         res = {}
         if data:
             res['msg'] = "获取图片成功"
             res['status'] = True
             LOGGER.info("获取图片成功")
         else:
             res['msg'] = "获取图片失败"
             res['status'] = False
             LOGGER.error("获取图片失败")
         response_data = {
             "msg": res['msg'],
             "status": res['status'],
             "data": data
         }
         return JsonResponse(response_data)
示例#2
0
 def show_user_plist(self):
     """
     Method to check user plists.
     """
     if os.path.exists(self.path):
         plr  = Plist_Reader(self.path)
         for i in plr.main():
             self.plist_list.append(i)
     else:
         #print "[?] Path: %s not found" % self.path
         LOGGER.error('plist_user show_user_plist path not found: %s' % self.path)
示例#3
0
def aquire_token():
    LOGGER.info('Trying to aquire token from server')
    token_file = open(CONFIG.TOKEN_FILE, 'w')
    req = requests.put(CONFIG.SERVER_ADDR + TOKENS_RES, json={'system_name': CONFIG.SYSTEM_NAME})
    if req.ok:
        LOGGER.info('Aquiring token from server succeeded')
        generated_token = req.json()['generated_token']
        token_file.write('\n'.join([TOKEN_START, generated_token, TOKEN_END]))
        return generated_token
    else:
        LOGGER.error('Failed to aquire token from server')
        raise TokenNotFoundException()
示例#4
0
def register(request):
    user_model = get_user_model()

    try:
        email = BaseUserManager.normalize_email(request.data["email"])
        if not is_email_valid(email):
            raise ValueError

        if settings.OPEN_REGISTRATION:
            preexisting_user, _ = user_model.objects.get_or_create(email=email)
        else:
            preexisting_user = user_model.objects.get(email__iexact=email)

        preexisting_user.register_preexisting_user(request.data.get("name"))
        LOGGER.info(
            log_filter(
                request,
                "registration succeded; "
                "email: '" + str(email) + "'",
            ))
        return Response({}, status=status.HTTP_201_CREATED)
    except IntegrityError:
        LOGGER.error(
            log_filter(
                request,
                "Registration failed: IntegrityError; "
                "email: '" + str(email) + "'",
            ))
        return Response({}, status=status.HTTP_201_CREATED)
    except user_model.DoesNotExist:
        LOGGER.error(
            log_filter(
                request,
                "Registration failed: Email or Researcher Id not found; "
                "email: '" + str(email) + "'",
            ))
        return Response(
            {
                "error_msg": ("Registration is closed."
                              " Please contact an administrator.")
            },
            status=status.HTTP_403_FORBIDDEN)
    except KeyError:
        LOGGER.error(
            log_filter(request,
                       "Registration failed: KeyError; " + str(request.data)))
        return Response({}, status=status.HTTP_201_CREATED)
    except ValueError:
        LOGGER.error(
            log_filter(
                request,
                f"Registration failed: Invalid email; email: '{str(email)}'"))
        return Response(
            {
                "error_msg": ("Invalid email address entered."
                              " Please use a valid email address.")
            },
            status=status.HTTP_400_BAD_REQUEST)
示例#5
0
文件: http_client.py 项目: wohui/pxiv
def get_response(req_type="POST",
                 url=None,
                 data=None,
                 headers=DEFAULT_HEADER,
                 cookies=COOKIES):
    """ http请求 """
    LOGGER.info(url + " " + str(data) + " " + str(COOKIES))
    try:
        if req_type.upper() == "POST":

            r = requests.post(url=url,
                              data=data,
                              headers=headers,
                              allow_redirects=True,
                              cookies=cookies)

        elif req_type.upper() == "GET":
            param_list = []
            for key, value in data.items():
                param_list.append(key + "=" + value)
            r = requests.get(url=url + "?" + "&".join(param_list),
                             data={},
                             headers=headers,
                             allow_redirects=True,
                             cookies=cookies)
        else:
            raise TypeError("http method error")
    except (requests.exceptions.ConnectionError, TypeError) as e:
        LOGGER.error("send request fail " + str(e))
        return None

    if r.status_code == requests.codes.ok:
        # LOGGER.info(r.text)
        # 更新cookies
        if len(r.cookies) != 0:
            COOKIES.update(r.cookies)
        for res in r.history:
            if len(res.cookies) != 0:
                COOKIES.update(res.cookies)

        return r.text
    else:
        LOGGER.error("status code " + str(r.status_code))
        return None
示例#6
0
    def _send_mail(self, subject, body):
        """
            Send a simple text e-mail. Settings are used to get the recipient.

            :param str subject: Subject of the email
            :param str body: Body content of the email
        """
        try:
            msg = MIMEText(body)

            msg['Subject'] = subject
            msg['From'] = secrets.SCORING_EMAIL['reporting']['from']
            msg['To'] = secrets.SCORING_EMAIL['reporting']['to']

            smtp = smtplib.SMTP_SSL(secrets.SCORING_EMAIL['host'])
            smtp.sendmail(msg['From'], msg['To'], msg.as_string())
            smtp.quit()
        except Exception as ex:
            LOGGER.error('Something went wrong when sending the email: %s', ex)
示例#7
0
    def _send_mail(self, subject, body):
        """
            Send a simple text e-mail. Settings are used to get the recipient.

            :param str subject: Subject of the email
            :param str body: Body content of the email
        """
        try:
            msg = MIMEText(body)

            msg['Subject'] = subject
            msg['From'] = settings.SCORING_EMAIL['reporting']['from']
            msg['To'] = settings.SCORING_EMAIL['reporting']['to']

            smtp = smtplib.SMTP_SSL(settings.SCORING_EMAIL['host'])
            smtp.sendmail(msg['From'], msg['To'], msg.as_string())
            smtp.quit()
        except Exception as ex:
            LOGGER.error('Something went wrong when sending the email: %s', ex)
    def run(self):
        """
            Run the parser.
        """
        with mongo.Mongo() as database:
            current = self.next()
            while current:
                try:
                    addr = self.get_ip(current)
                    if not addr:
                        LOGGER.info('Entry skipped because no specified IP.')
                        current = self.next()
                        continue

                    if not utils.is_managed_ip(addr):
                        LOGGER.debug('Not a managed IP [%s].', addr)
                        current = self.next()
                        continue

                    doc_ts = int(
                        time.mktime(self.get_date(current).timetuple()))
                    if doc_ts < YESTERDAY:
                        LOGGER.debug('This entry is too old [%s].',
                                     self.get_date(current))
                        current = self.next()
                        continue

                    document = {
                        'ip': addr,
                        'timestamp': doc_ts,
                        'weight': self.compute_weight(current),
                        'source': self.get_source(current),
                        'raw': self.get_raw(current)
                    }
                    database.push_ip_document(document)
                except Exception as exc:
                    LOGGER.error('Unexpected error: %s [%s]', type(exc),
                                 exc.message)
                    LOGGER.error(traceback.format_exc())

                current = self.next()
            self.close()
示例#9
0
def change_password(request):
    password = request.data["password"]
    verif_path = request.data["verifPath"]

    if not is_password_valid(password):
        LOGGER.error(
            log_filter(
                request,
                f"Password change failed: Invalid password: '******'")
        )
        return Response(
            {
                "error_msg":
                ("Invalid password entered. Password is either too"
                 " short (<10 symbols) or too weak.")
            },
            status=status.HTTP_400_BAD_REQUEST)

    get_user_model().change_password(verif_path, password)
    return Response({}, status.HTTP_201_CREATED)
示例#10
0
    def base64_to_html(self, encoded_html):
        """
            Decodes given encoded html into String
            Args:
                encoded_html (str): Base64 + URI Encoded Html
            Example:
                Decoder.base64ToHtml("JTNDaDElM0VIZWxsbyUyMFdvcmxkJTNDL2gxJTNF")
                <h1>Hello World</h1>
        """
        try:
            LOGGER.info('Attempting to decode %s', encoded_html)
            if encoded_html in self.memo:
                return self.memo[encoded_html]
            else:
                decoded_html = unquote(b64decode(encoded_html).decode())
                self.memo[encoded_html] = decoded_html
        except:
            LOGGER.error('Failed to decode %s', encoded_html)
            raise Exception('Failure to decode %s', encoded_html)

        return decoded_html
示例#11
0
    def next(self):
        if self._current >= len(self._queue):
            self._feed_queue()

        res = self._queue[self._current]

        LOGGER.debug('Parsing mail...')
        try:
            self._parser = MailReaderFactory.get_reader_for_mail(res)
            self._current = self._current + 1
        except Exception as ex:
            LOGGER.error('Error while parsing mail #%s', self._uids[self._current])
            LOGGER.error('Unable to determine source of this mail (raw content follows): %s', ex)
            LOGGER.error('Retrieved email:\n%s', res)

            LOGGER.debug('-- Recovery mode --')
            # Add this uid to the failed list so don't retry to parse this mail anymore
            self._failed_uids.append(self._uids[self._current])
            # Remove uid from the list so this email won't be deleted.
            self._uids.remove(self._uids[self._current])
            # Remove mail from the queue
            self._queue.remove(res)

            LOGGER.debug('Ok. Now, try to fetch another mail...')

            # Try to fetch next mail one more time...
            return self.next()

        return res
示例#12
0
    def run(self):
        """
            Run the parser.
        """
        with mongo.Mongo() as database:
            current = self.next()
            while current:
                try:
                    addr = self.get_ip(current)
                    if not addr:
                        LOGGER.info('Entry skipped because no specified IP.')
                        current = self.next()
                        continue

                    if not utils.is_managed_ip(addr):
                        LOGGER.debug('Not a managed IP [%s].', addr)
                        current = self.next()
                        continue

                    doc_ts = int(time.mktime(self.get_date(current).timetuple()))
                    if doc_ts < YESTERDAY:
                        LOGGER.debug('This entry is too old [%s].', self.get_date(current))
                        current = self.next()
                        continue

                    document = {
                        'ip': addr,
                        'timestamp': doc_ts,
                        'weight': self.compute_weight(current),
                        'source': self.get_source(current),
                        'raw': self.get_raw(current)
                    }
                    database.push_ip_document(document)
                except Exception as exc:
                    LOGGER.error('Unexpected error: %s [%s]', type(exc), exc.message)
                    LOGGER.error(traceback.format_exc())

                current = self.next()
            self.close()
示例#13
0
文件: views.py 项目: wohui/pxiv
 def get_hito_data(request):
     if request.method == 'POST':
         # 获取一言
         hitoko_url = "https://api.imjad.cn/hitokoto"
         hitoko_data = {
             "c": "c",
             "encode": "json",
             "charset": "utf-8",
             "length": 50,
         }
         data = []
         for i in range(0, 10):
             hitoko_res = requests.get(hitoko_url,
                                       hitoko_data,
                                       verify=False)
             hitoko_res_text = str(hitoko_res.text)
             json_obj = json.loads(hitoko_res_text)
             if json_obj:
                 hito_text = json_obj['hitokoto']
                 LOGGER.info(hito_text)
                 data.append(hito_text)
         res = {}
         if data:
             res['msg'] = "获取一言完成"
             res['status'] = True
             LOGGER.info("获取一言完成")
         else:
             res['msg'] = "获取一言失败"
             res['status'] = False
             LOGGER.error("获取一言失败")
         response_data = {
             "msg": res['msg'],
             "status": res['status'],
             "data": data
         }
         return JsonResponse(response_data)
示例#14
0
            username = raw_input('Please enter a username to search: ').lower()
            if username.isalnum():
                LOGGER.info('Option 3 chosen gather plist for user %s ' %
                            username)
                # GSI()
                # Checks that the user account has a home directory listed
                if username in GSI.return_home_dirs():
                    print "username"
                    PLR = Return_User_Plists(username)
                    # TODO adjust the code to take the username in the main PLR.Return_User_Plists()
                    # PPrints for readability
                    PLR.main()
                else:
                    print "[!] Username not found on system"
                    LOGGER.error(
                        'Choice 3 but username: %s not found on system' %
                        username)
            else:
                print "[!] Error problem with username: %s " % username
                LOGGER.error('Choice 3 - Problem with username: %s' % username)

        elif user_input == "4":
            # Returns the root level plists for launchA / launchD
            # Return_Root_Level_Plists()
            RRLP.main()

        elif user_input == "5":
            # Returns the tar of the log directories
            # Gather_System_Info()
            print "[+] Taring up the root logging directory ..."
            GSI.tar_log_directory()