示例#1
0
文件: views.py 项目: Yu-python/learn
    def get(self, request):
        # 验证码
        def generate_code(n=4):
            code = ''
            for i in range(n):
                # 小写字符
                lower_character = chr(random.randint(97, 122))
                # 大写字符
                upper_character = chr(random.randint(65, 90))
                # 数字
                number = random.randint(0, 9)
                # 合并一起
                code += str(
                    random.choice([lower_character, upper_character, number]))
            return code

        code = generate_code()
        image = ImageCaptcha(width=115, height=38,
                             font_sizes=(30, 30, 30)).generate_image(code)

        request.session['code'] = code

        print(request.session.get('code'))
        f = BytesIO()
        image.save(f, 'png')
        data = f.getvalue()
        return HttpResponse(data)
def captcha_pic_builder():
    '''
    生成序列验证码图片及包含其对应目标值的csv文件,哈哈哈....
    :return:
    '''
    list = [
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
        'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
    ]
    #因为csv标签名不能放在循环里的缘故,故将创建及增加内容放在外面
    #newline='',是为了防止以Excel打开时会多出空行
    with open('./captcha_pic/labels.csv', 'a+', newline='') as csvfile:
        writer = csv.writer(csvfile, dialect='excel')
        writer.writerow(['file_num', 'chars'])
        for j in range(20):
            chars = ''
            for i in range(4):
                chars += list[randint(0, 25)]
                print(chars)
            #生成图片
            image = ImageCaptcha().generate_image(chars)
            # image.show()
            filename = str(j) + '.jpg'
            #将图片保存到本地
            image.save(os.path.join('./captcha_pic/', filename))
            #添加样本序列及目标值
            writer.writerow([j, chars])
    return None
示例#3
0
def generate_captcha(number=None):
    if not number:
        number = str(random.randint(10001, 99999))
    captcha = ImageCaptcha(fonts=ALL_FONTS, width=200, height=100).generate_image(number)
    img = io.BytesIO()
    captcha.save(img, 'PNG')
    img.seek(0)
    return img, number
示例#4
0
def gene_captcha_b64img(captcha_str):
    img = ImageCaptcha().generate_image(captcha_str)
    img_buffer = BytesIO()
    img.save(img_buffer, 'png')
    res = img_buffer.getvalue()
    img_buffer.close()

    return f'data:image/png;base64,{base64.b64encode(res).decode("utf-8")}'
示例#5
0
def generate_code():
    captcha_str = ''.join(random.sample(captcha_choices, 4))
    sha256_hash = hashlib.sha256()
    sha256_hash.update(captcha_str.encode('utf-8'))
    hash_str = sha256_hash.hexdigest()
    img = ImageCaptcha().generate_image(captcha_str)
    # TODO: 删除文件
    img.save(os.path.join('front-end', 'static', 'tmp', hash_str+'.png'))
    return make_response(jsonify({'captcha': hash_str}))
示例#6
0
def captcha2():
    code = random_string(4)
    image = ImageCaptcha().generate_image(code)

    img_io = BytesIO()
    image.save(img_io, "JPEG", quality=70)
    img_io.seek(0)

    return code, img_io
示例#7
0
def make_code(chars):
    """
    生成验证码图片,图片名为:验证码内容.jpg
    :param chars: 验证码内容
    :return: None
    """
    image = ImageCaptcha().generate_image(chars)
    # 验证码图片保存到./imgs/文件夹下
    filename = './imgs/' + chars + '.jpg'
    image.save(filename)
    print(f'{threading.current_thread().name}_done:{filename}')
示例#8
0
def verify():
    list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
            'V',
            'W', 'X', 'Y', 'Z']
    chars = ''
    for i in range(4):
        chars += list[randint(0, 35)]
    image = ImageCaptcha().generate_image(chars)
    image.save('static/yanzheng.png')
    return chars
示例#9
0
    def generate(self, img_count, char_count):
        file_suffix = "png"

        for i in range(img_count):
            text = ""
            for j in range(char_count):
                text += random.choice(self.characters)
            img = ImageCaptcha(self.width, self.height).generate_image(text)
            now_time = str(time.time()).replace(".", "")
            path = os.path.join(self.root_dir,
                                "{}_{}.{}".format(text, now_time, file_suffix))
            img.save(path)
示例#10
0
def generate_captcha():
    captchas_dir = os.path.join(settings.MEDIA_ROOT, 'captchas')
    if not os.path.exists(captchas_dir):
        os.mkdir(captchas_dir, 0o777)

    letters = ''.join(
        random.choice(string.ascii_uppercase + string.digits)
        for _ in range(4))
    filename = 'captcha_' + secrets.token_hex(8) + '.png'
    path = '/'.join([settings.MEDIA_URL.rstrip('/'), 'captchas', filename])
    img = ImageCaptcha().generate_image(letters)
    img.save(os.path.join(captchas_dir, filename))
    return letters, path
示例#11
0
    def captcha():
        # 网络问题,captcha包未下载,先注释
        from captcha.image import ImageCaptcha

        random_lower = chr(random.randint(97, 122))
        random_upper = chr(random.randint(65, 90))
        random_num = str(random.randint(0, 9))

        chars = ''
        for i in range(4):
            chars += random.choice([random_lower, ranom_upper, random_num])
        image = ImageCaptcha().generate_image(chars)
        image.save("./%s.jpg" % chars)  # 保存
示例#12
0
 def get():
     if not option.get_option(Config.captcha):
         abort(404)
     answer = ''.join([choice(alphabet) for i in range(4)])
     captcha = ImageCaptcha().generate_image(answer)
     buf = BytesIO()
     captcha.save(buf, format='GIF')
     b64_payload = b64encode(buf.getvalue())
     payload = {
         'image': 'data:image/gif;base64,' + b64_payload.decode('ascii'),
         'answer_enc': jwt_encode(interval=timedelta(minutes=5),
                                  data={'answer': answer})
     }
     return api_jsonify(payload)
示例#13
0
def make_vcode():
    str_list = [
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
        'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
        's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '', 'B', 'C', 'D', 'E', 'F',
        'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
        'U', 'V', 'W', 'X', 'Y', 'Z'
    ]
    chars = ''.join(random.choices(str_list, k=4))
    print(chars)
    cache.set('vcode', chars, timeout=300)
    image = ImageCaptcha().generate_image(chars)
    image.save('vcode.jpg')
    with open('vcode.jpg', 'rb') as f:
        ls_f = base64.b64encode(f.read()).decode()
    return ls_f
示例#14
0
def verifyCode(request):
    # 初始化画布,初始化画笔
    from captcha.image import ImageCaptcha
    from random import randint
    list = [
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
        'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
        's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '', 'B', 'C', 'D', 'E', 'F',
        'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
        'U', 'V', 'W', 'X', 'Y', 'Z'
    ]
    chars = ''
    for i in range(4):
        chars += list[randint(0, 61)]
    image = ImageCaptcha().generate_image(chars)

    fp = BytesIO()
    image.save(fp, "png")
    request.session['code'] = chars
    return HttpResponse(fp.getvalue(), content_type="image/jpeg")
示例#15
0
def get_valid_img(request):
    from captcha.image import ImageCaptcha
    from random import randint
    lst = [
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
        'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r',
        's', 't', 'u', 'v', 'w', 'x', 'y', 'z'
    ]
    chars = ''
    for i in range(4):
        chars += lst[randint(0, 36)]
    request.session['valid_code'] = chars
    image = ImageCaptcha(width=80, height=35,
                         font_sizes=(35, 35, 35)).generate_image(chars)
    from io import BytesIO
    io_obj = BytesIO()

    # 将生成的图片数据保存在io对象中
    image.save(io_obj, "png")
    data = io_obj.getvalue()
    return HttpResponse(data)
示例#16
0
def recapp():
    letters = string.ascii_lowercase + string.digits + string.ascii_uppercase
    result_str = ''.join(random.choice(letters) for i in range(9))
    image = ImageCaptcha(width=250, height=100)
    text = random

    image = image.create_captcha_image("{}".format(result_str),
                                       color="white",
                                       background="black")

    # image.show()
    return image.save("gen1.jpg")
示例#17
0
def gen_captcha(img_dir, num_per_image, number, choices):
    if os.path.exists(img_dir):
        shutil.rmtree(img_dir, ignore_errors=True)
    if not os.path.exists(img_dir):
        os.makedirs(img_dir)
    count = 0
    random_widths = list(range(64, 100, 1))
    for _ in range(number):
        for i in itertools.permutations(choices, num_per_image):
            if count >= number:
                break
            else:
                captcha = ''.join(i)
                fn = os.path.join(img_dir, '%s_%s.jpg' % (captcha, count))
                ima = ImageCaptcha(width=random_widths[int(random.random() *
                                                           36)],
                                   height=32,
                                   font_sizes=(26, 28, 30))
                ima = ima.create_captcha_image(chars=captcha,
                                               color='white',
                                               background='black')
                ima.save(fn)
                count += 1
示例#18
0
def demo(name=None):
    if request.method == "POST":
        from captcha.image import ImageCaptcha
        import string
        characters = string.digits + string.ascii_uppercase
        width, height, n_len, n_class = 170, 80, 4, len(characters) + 1
        user_inputs = request.get_json()
        if user_inputs.get("origin_string", None):
            image_name = request.get_json()["origin_string"]
            ImageCaptcha(width=width, height=height)
            img = ImageCaptcha(width=width, height=height).generate_image(image_name)
            img_file = "{}.png".format(image_name)
            img.save(os.path.join(app.static_folder, img_file))
            return jsonify({
                "url": "/static/{}".format(img_file)
            })
        if user_inputs.get("filename", None):
            filename = user_inputs.get("filename", None)
            img_path = os.path.join(app.static_folder, filename)
            img = Image.open(img_path)
            return predict(img)

    return render_template('demo.html', name=name)
示例#19
0
def get_captchas(response: Response) -> Dict:
    """
    获取验证码信息
    {status: 1, code:'图片url'}

    """
    code = str(int(random.random() * 9000 + 1000))
    logger.info(f'验证码为:{str(code)}')
    image = ImageCaptcha().generate_image(code)
    image.save('./%s.jpg' % code)
    file_path = os.path.join(os.getcwd(), f'{code}.jpg')
    try:
        with open(file_path, 'rb') as f:
            base64_data = base64.b64encode(f.read())
            s = base64_data.decode()
            url = 'data:image/jpeg;base64,%s' % s
            response.set_cookie(key='cap', value=code, max_age=3600)
            return {'status': 1, 'code': url}
    except Exception as e:
        raise CustomErr(ERROR_CODE,
                        msg_dict={"REASON": "获取验证码信息失败:{}".format(e)})
    finally:
        os.remove(file_path)
示例#20
0
def signup(request):
    global temp
    if request.method != 'POST':
        randint = random.randint(1, 100000000)
        imagepart = ImageCaptcha(width=250, height=100)
        temp = str(randint)
        imagepart = imagepart.generate_image(str(randint))
        imagepart.save("./MEDIA/another/image/trial1.png")
    if request.method == 'POST':
        fname1 = request.POST['firstname']
        lname1 = request.POST['lastname']
        contact1 = request.POST['contact']
        email1 = request.POST['email']
        state1 = request.POST['state']
        city1 = request.POST['city']
        password1 = request.POST['password']
        password12 = request.POST['confirm_pass']
        captcha1 = request.POST['captcha']
        now = datetime.datetime.now()
        if captcha1 == str(temp):
            if (fname1 == '') or (lname1 == '') or (contact1 == '') or (
                    email1 == '') or (state1 == '') or (city1 == ''):
                print(fname1)
                messages.error(request,
                               "you can not leave the field empty....")
            elif Person.objects.filter(email=email1.lower()).exists():
                messages.error(request, "this email id already exists...")
                return render(
                    request, './newaccount/signup.html', {
                        "fname": fname1,
                        "lname": lname1,
                        "contact": contact1,
                        "email": email1,
                        "state": state1,
                        "city": city1
                    })

            elif ((password1 != '') and (password12 != '')):
                if ((password1 == password12)):
                    # https://docs.djangoproject.com/en/3.1/topics/signing/
                    #  This is like for cryptographic signing
                    # signer = Signer()
                    # value = signer.sign(password1)
                    s = random.randrange(20, 100000000)
                    if Person.objects.filter(userslug=s):
                        s = random.randrange(20, 100000000)
                        x = Person(fname=fname1.lower(),
                                   lname=lname1.lower(),
                                   userslug=fname1 + lname1 + str(s),
                                   contact=contact1,
                                   email=email1.lower(),
                                   state=state1.lower(),
                                   city=city1.lower(),
                                   password=password1)
                        x.save()
                        messages.success(
                            request,
                            "wooo....! your Account has successfully created...! Thankyou for connecting with us..."
                        )
                        return render(request, "./newaccount/signin.html",
                                      {"email": email1})
                    else:
                        x = Person(fname=fname1.lower(),
                                   lname=lname1.lower(),
                                   userslug=fname1 + lname1 + str(s),
                                   contact=contact1,
                                   email=email1.lower(),
                                   state=state1.lower(),
                                   city=city1.lower(),
                                   password=password1)
                        x.save()
                        messages.success(
                            request,
                            "wooo....! your Account has successfully created...! Thankyou for connecting with us..."
                        )
                        return render(request, "./newaccount/signin.html")
                else:
                    messages.error(
                        request,
                        "Your Password did not matched please make it correct..."
                    )
                    return render(
                        request, './newaccount/signup.html', {
                            "fname": fname1,
                            "lname": lname1,
                            "contact": contact1,
                            "email": email1,
                            "state": state1,
                            "city": city1
                        })
        else:
            randint = random.randint(1, 100000000)
            imagepart = ImageCaptcha(width=250, height=100)
            temp = str(randint)
            imagepart = imagepart.generate_image(str(randint))
            imagepart.save("./MEDIA/another/image/trial1.png")
            messages.error(request,
                           "captcha did not matched please try again...")
            return render(
                request, './newaccount/signup.html', {
                    "fname": fname1,
                    "lname": lname1,
                    "contact": contact1,
                    "email": email1,
                    "state": state1,
                    "city": city1,
                    "password1": password1,
                    "password12": password12
                })
    return render(request, './newaccount/signup.html')
示例#21
0
# -*- coding:utf-8 -*-
# @author :adolf
from captcha.image import ImageCaptcha
from random import randint
import os
from tqdm import tqdm

english_alphabet = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                    'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P',
                    'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L',
                    'Z', 'X', 'C', 'V', 'B', 'N', 'M',
                    'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p',
                    'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l',
                    'z', 'x', 'c', 'v', 'b', 'n', 'm']
# print(len(english_alphabet))
#
for i in tqdm(range(100000)):
    chars = ''
    for i in range(4):
        chars += english_alphabet[randint(0, 61)]
    image = ImageCaptcha().generate_image(chars)

    label_path = 'gen_ver'
    if not os.path.exists(label_path):
        os.mkdir(label_path)
    label = chars + '.png'
    image.save(os.path.join(label_path, label))

# for i in range(199999):
#     print(randint(0, 4))
#pip install captcha 


#图片类型不可定制化

from captcha.image import ImageCaptcha
import random,string

chr_all = string.ascii_letters + string.digits
chr_4 = ''.join(random.sample(chr_all, 4))
image = ImageCaptcha().generate_image(chr_4)
image.save('./%s.jpg' % chr_4)