示例#1
0
文件: main.py 项目: Rthe1st/bars
def run(args):

    release_id = 'b2ac073a-4b6b-3fb2-95e7-c3434792b46a'

    response = requests.get(
        'http://musicbrainz.org/ws/2/release/{}?fmt=json'.format(release_id)
    ).json()

    correct_barcode = response['barcode']

    ean = barcode.EAN13(response['barcode'], writer=ImageWriter())
    _ = ean.save('ean13_barcode')

    response = requests.get(
        'http://coverartarchive.org/release/{}/'.format(release_id)
    ).json()

    front_path = './front-cover.jpg'
    back_path = './back-cover.jpg'

    for image in response['images']:
        if 'Front' in image['types']:
            response = requests.get(
                image['image']
            )
            with open(front_path, 'wb') as f:
                f.write(response.content)
        elif 'Back' in image['types']:
            response = requests.get(
                image['image']
            )
            with open(back_path, 'wb') as f:
                f.write(response.content)
            
    # Scan cover to see if it has the (correct) barcode
    # If not, we'll have to paste one on

    barcode_found = False

    for path in [front_path, back_path]:
        raw_barcodes, _ = input_methods.from_image(path)

        if raw_barcodes is not None:
            for raw_barcode in raw_barcodes:
                the_barcode = (raw_barcode.data).decode("utf-8")
                if the_barcode ==  correct_barcode:
                    barcode_found = True
                    break

    if not barcode_found:

        # Some logic for working out where to place it would be cool

        background = Image.open(back_path)
        foreground = Image.open("ean13_barcode.png")

        background.paste(foreground, (0, 0))
        background.save('./printable_album.jpg', "JPEG")

    return
示例#2
0
    def get_barcode():
        prod_id = request.query.get('prod_id')
        almacen_id = request.query.get('almacen_id')
        quantity = int(request.query.get('quantity', 1))

        prod = dbapi.getone(PriceList, prod_id=prod_id, almacen_id=almacen_id)

        if quantity > 1000:
            redirect('/app/barcode_form?msg=cantidad+muy+grande')

        if not prod:
            redirect('/app/barcode_form?msg=producto+no+existe')

        encoded_string = '{:03d}{:09d}'.format(quantity, prod.pid)
        bar = barcode.EAN13(encoded_string)
        filename = bar.ean + '.svg'
        path = imagefiles.make_fullpath(filename)
        if not os.path.exists(path):
            with open(path, 'w') as barcode_file:
                bar.write(barcode_file)
        url = '/app/img/{}'.format(filename)

        column = 5
        row = 9
        price = int(prod.precio1 * quantity * Decimal('1.12') + Decimal('0.5'))

        temp = jinja_env.get_template('prod/barcode.html')
        return temp.render(url=url,
                           row=row,
                           column=column,
                           prodname=prod.nombre,
                           price=price)
示例#3
0
def genBarcode(count):
    num = random.randrange(1, 9000000000000)
    print(num)
    path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    bar_code = barcode.EAN13(str(num), writer=ImageWriter())
    file = open('./static/images/product/' + str(count) + '.svg', "wb")
    bar_code.write(file, BytesIO())
    return num
示例#4
0
    async def next(request):
        token = request.match_info["token"]
        form = await request.post()
        try:
            cookie = decrypt(request.cookies.get("wstate", ""))
        except:
            cookie = {"token": token, "sum": 0}

        if cookie["token"] != token:
            return web.Response(text="HTTP/1.1 400 Это всё обман", status=400)

        this_barcode = form.get("barcode", "")
        if this_barcode:
            if this_barcode != cookie.get("next_barcode"):
                return web.Response(text="HTTP/1.1 422 Всё не так", status=422)
            else:
                cookie["sum"] += GOODS[this_barcode][1]

        if this_barcode or "next_barcode" not in cookie:
            next_barcode = random.choice(list(GOODS.keys()))
            cookie["next_barcode"] = next_barcode
        else:
            next_barcode = cookie.get("next_barcode")

        barcode_io = io.BytesIO()
        barcode.EAN13(next_barcode,
                      writer=barcode.writer.ImageWriter()).write(barcode_io)

        resp = web.StreamResponse()
        resp.headers["Content-type"] = "application/json"
        resp.set_cookie("wstate", encrypt(cookie).decode())
        await resp.prepare(request)
        await resp.write(
            json.dumps({
                "sum":
                cookie["sum"],
                "last":
                get_flag(token) if cookie["sum"] >= 100000000 else
                (GOODS[this_barcode][0] if this_barcode else None),
                "last_price":
                GOODS[this_barcode][1] if this_barcode else None,
                "next_pic":
                GOODS[next_barcode][2],
                "next_barcode":
                base64.b64encode(barcode_io.getvalue()).decode()
            }).encode())
        return resp
示例#5
0
import barcode

#----------------------------------------------
# Settings
ASK_USER_SAVE_TO_DISK = False  # True to ask the user to save on disk. Otherwise, uses temp folder and add to RoboDK.

#----------------------------------------------
# Create the bar code
data = mbox("Enter your bar code (EAN 13 digits)", entry='5701234567899')
if data is None or data is False or type(data) is not str:
    # User cancelled
    quit()
if not data.isdecimal() or len(data) != 13:
    # Invalid input
    quit()
img = barcode.EAN13(data, writer=barcode.writer.ImageWriter())

# You can easily copy this script to generate other bar codes type, such as UPC-A
#img = barcode.UPCA(data, writer=barcode.writer.ImageWriter())

#----------------------------------------------
# Save to file
name = "EAN13_" + data.replace('.', '').replace(':', '').replace('/', '')

filename = None
if ASK_USER_SAVE_TO_DISK:
    filename = getSaveFileName(
        strtitle='Save bar code on disk, or cancel to skip',
        strfile=name,
        defaultextension='.png',
        filetypes=[('PNG files', '*.png')])
示例#6
0
def AddPurchase():
    if request.method == 'GET':
        idPharmacy = session.get('pharmacy')
        _pharmacy = Pharmacy.get_by_id(idPharmacy)
        _departs = Department.select().where(Department.pharmacy == idPharmacy)
        nextPurchase = Purchase.select(fn.MAX(Purchase.id) + 1).scalar()

        return render_template('selller/selller_Purchase_add.html',
                               departments=_departs,
                               pharmacy=_pharmacy,
                               nextPurchase=nextPurchase,
                               name=GetName())

    if request.method == 'UPDATE':
        data = {}
        _data = request.json

        if _data.get('name'):
            temp = Drugs.get_or_none(Drugs.name == _data.get('name'))
            if temp == None:
                temp = DrugsCatalog.get_or_none(
                    DrugsCatalog.name == _data.get('name'))

        else:
            temp = Drugs.get_or_none(Drugs.barcode == _data.get('barcode'))
            if temp == None:
                temp = DrugsCatalog.get_or_none(
                    DrugsCatalog.barcode == _data.get('barcode'))

        if temp != None:
            data = {
                'status': 'ok',
                'id': temp.id,
                'unit': temp.unit,
                'name': temp.name,
                'barcode': temp.barcode,
                'city_of_dev': temp.city_of_dev
            }
        else:
            data = {'status': 'noExsists'}

        return jsonify(data)

    if request.method == 'PUT':
        generated_code = '96'
        generated_code += str(randint(0, 6))

        for i in range(10):
            generated_code += str(randint(0, 9))

        ISBN_code = barcode.generate(name='EAN13',
                                     code=generated_code,
                                     output='PNG')
        print(generated_code, barcode.EAN13(generated_code))

        return jsonify({'generated_barcode': generated_code})

    try:
        _data = request.json
        _drug_data_from_db = DrugsCatalog.get_or_none(
            DrugsCatalog.barcode == _data.get('barcode'))

        maxValueOfDepartment = int(
            str(
                max(
                    Department.select(fn.MAX(Department.id)).where(
                        Department.pharmacy == session['pharmacy']))))
        minValueOfDepartment = int(
            str(
                min(
                    Department.select(fn.MIN(Department.id)).where(
                        Department.pharmacy == session['pharmacy']))))

        if _drug_data_from_db == None:
            _drug_data_from_db = DrugsCatalog(
                barcode=_data.get('barcode'),
                name=_data.get('name').capitalize(),
                unit=_data.get('unit'),
                category=_data.get('category').capitalize(),
                subcategory=_data.get('subcategory').capitalize(),
                city_of_dev='no'.capitalize())
            _drug_data_from_db.save()

        for i in range(minValueOfDepartment, maxValueOfDepartment + 1):
            if _data.get(f'department_{i}') != '':
                tempDrug = Drugs(
                    department=i,
                    city_of_dev='no'.capitalize(),
                    pharmacy=session['pharmacy'],
                    unit=_drug_data_from_db.unit,
                    barcode=_data.get('barcode'),
                    price_sale=_data.get('price_sale'),
                    shelf_life=_data.get('shelf_life'),
                    name=_data.get('name').capitalize(),
                    clean_price=_data.get('clear_price'),
                    quantity=_data.get(f'department_{i}'),
                    category=_drug_data_from_db.category.capitalize(),
                    price_with_discount=_data.get('price_with_discount'),
                    subcategory=_drug_data_from_db.subcategory.capitalize(),
                )
                tempDrug.save()

                Purchase(
                    department=i,
                    date=date.today(),
                    pharmacy_id=session['pharmacy'],
                    drug=tempDrug.id,
                    provide=_data.get('provide').capitalize(),
                    quantity=_data.get(f'department_{i}'),
                    total_sum=_data.get('price_with_discount'),
                ).save()

            if 'onlyForThisPharmacy' in _data:
                DrugsCatalog.delete_by_id(int(str(_drug_data_from_db)))

        return jsonify({"status": "purchase_add"})

    except IntegrityError:
        return jsonify({
            "status": "error",
            "error": "purchase_error_find_drug"
        })
    except:
        return jsonify({"status": "error", "error": "purchase_add"})
示例#7
0
import barcode.writer

from jinja2 import FileSystemLoader

BASE_DIR = os.path.dirname(__file__)
STATIC_DIR = os.path.join(BASE_DIR, 'static')

PREFIX = "ugra_must_be_funny_in_a_rich_man_s_world_"
SECRET2 = b"liver-float-practice-list-inhabitant"
SALT2_SIZE = 12
SECRET3 = b'?g7P\x02\xc6\x82n\xa3fMhnb?\xa6'

GOODS = {
    b: v
    for b, v in pickle.load(open("goods.pkl", "rb")).items()
    if barcode.EAN13(b).ean == b
}
# {"4607046123647": ('САХАР "ХОРОШИЙ/РУССКИЙ" РАФИНАД 1 КГ.', 6999, 'https://grozd.ru/content/images/thumbs/5ea139b8fb678c28bba4d0d9_sahar-horoijrusskij-rafinad-1-kg.jpeg')}


def encrypt(s):
    iv = Crypto.Random.get_random_bytes(Crypto.Cipher.AES.block_size)
    cipher = Crypto.Cipher.AES.new(SECRET3, Crypto.Cipher.AES.MODE_CBC, iv)
    return base64.b64encode(iv + cipher.encrypt(
        Crypto.Util.Padding.pad(
            json.dumps(s).encode(), Crypto.Cipher.AES.block_size)))


def decrypt(s):
    data = base64.b64decode(s)
    cipher = Crypto.Cipher.AES.new(SECRET3, Crypto.Cipher.AES.MODE_CBC,