Exemplo n.º 1
0
def setShopGrade(request):
    d = request.REQUEST
    data = json.loads(d['data'])
    print data
    result = Anlysis.judgeShop(data)

    shop = Shop(shopId=data["id"], grade=result["grade"], rid=result["rid"])
    # print shop["shopId"]
    shop.save()
    return HttpResponse(json.dumps({"status": "success", "grade": shop.grade}))
Exemplo n.º 2
0
def new_shop():
    form = ShopForm()
    if form.validate_on_submit():
        if Shop.query.filter_by(name=form.name.data).first():
            flash('Shop already exists. Enter new one...')
        else:
            shop = Shop(name=form.name.data)
            db.session.add(shop)
            db.session.commit()
            return redirect('/new-shop')
    return render_template('shop.html', shops=Shop.query.all(), form=form)
Exemplo n.º 3
0
    def insert_data(self):
        self.session.add_all([
            Shop(name="Auchan", address=None, staff_amount=250),
            Shop(name="IKEA", address="Street Žirnių g. 56, Vilnius, Lithuania.",
                 staff_amount=250)
        ])
        self.session.commit()

        self.session.add_all([
            Department(sphere="Furniture", staff_amount=250, shop_id=1),
            Department(sphere="Furniture", staff_amount=300, shop_id=2),
            Department(sphere="Dishes", staff_amount=200, shop_id=2)
        ])
        self.session.commit()

        self.session.add_all([
            Item(name="Table", description="Cheap wooden table", price=300, department_id=1),
            Item(name="Table", description=None, price=750, department_id=2),
            Item(name="Bed", description="Amazing wooden table", price=1200, department_id=2),
            Item(name="Cup", description=None, price=10, department_id=3),
            Item(name="Plate", description="Glass Plate", price=20, department_id=3)
        ])
        self.session.commit()
Exemplo n.º 4
0
def generate_shop(session: Session, count: int) -> list:
    faker = Faker()
    result = []
    for i in range(count):
        name = faker.company()
        description = faker.bs()
        site = faker.domain_name()
        shop = Shop(name=name, description=description, site=site)
        result.append(shop)
        session.add(shop)
        log.debug(f"Generate shop: {shop}")
    session.commit()
    for i in result:
        session.refresh(i)
    return result
Exemplo n.º 5
0
def callback():
    shop = request.args.get('shop')
    code = request.args.get('code')
    given_hmac = request.args.get('hmac')

    #validate the hmac, to make sure we're not being screwed around with
    h = dict([(key, value) for key, value in request.args.items()
              if key not in ['hmac', 'signature']])

    # now sort lexicographically and turn into querystring
    query = '&'.join(["{0}={1}".format(key, h[key]) for key in sorted(h)])

    # generate the digest
    digest = hmac.new(app.config['SHOPIFY_APPLICATION_SECRET'],
                      msg=query,
                      digestmod=hashlib.sha256).hexdigest()

    if given_hmac != digest:
        abort(403,
              "Authentication failed. Digest provided was: {0}".format(digest))
    else:
        # we're in! get an access token
        payload = {
            'client_id': app.config['SHOPIFY_APPLICATION_KEY'],
            'client_secret': app.config['SHOPIFY_APPLICATION_SECRET'],
            'code': code
        }

        result = requests.post(
            "https://{}/admin/oauth/access_token".format(shop), data=payload)

        current_shop = Shop.query.filter(Shop.shopify_domain == shop).first()

        if current_shop is None:
            access_token = json.loads(result.text)['access_token']
            current_shop = Shop(shop, access_token)
            current_shop.Save()

        if current_shop is not None:
            session["shop_id"] = current_shop.id
            session["shopify_domain"] = current_shop.shopify_domain

        return redirect("/")
Exemplo n.º 6
0
    def get(self, request):
        state = request.GET.get('state', None)
        session_state = request.session.get('state', None)
        if not state or not session_state or state != session_state:
            return HttpResponseForbidden()
        params = {
            'shop': request.GET.get('shop', None),
            'code': request.GET.get('code', None),
            'timestamp': request.GET.get('timestamp', None),
            'signature': request.GET.get('signature', None),
            'state': request.GET.get('state', None),
            'hmac': request.GET.get('hmac', None),
        }
        session = shopify.Session(
            'https://%s.%s%s' %
            (request.GET.get('shop', None), settings.SHOPIFY_URL,
             settings.SHOPIFY_AUTHORIZE_SUFIX))

        session.setup(api_key=settings.SHOPIFY_API_KEY,
                      secret=settings.SHOPIFY_SECRET)
        try:
            token = session.request_token(params)
        except shopify.ValidationException:
            return HttpResponseForbidden()
        context = {}
        context["shop"] = request.GET.get('shop', None)
        context["api_key"] = settings.SHOPIFY_API_KEY

        shop = Shop.objects.filter(name=context["shop"])
        request.session['shop_name'] = request.GET.get('shop', None)
        request.session['shop_token'] = token
        if not shop:
            shop_obj = Shop(name=context["shop"], token=token)
            shop_obj.save()
            activate_shopify_session(request)
            webhook = shopify.Webhook()
            webhook.topic = "app/uninstalled"
            webhook.address = "https://app.roojet.com/uninstall/"
            webhook.format = "json"
            success = webhook.save()

        return render(request, self.template_name, context)
Exemplo n.º 7
0
async def command_add_new_shop_action_final(message: types.Message,
                                            state: FSMContext):
    cash_machine = message.text
    cash_machine = cash_machine.strip()
    await state.update_data(cash_machine=cash_machine)
    data = await state.get_data()
    new_shop = Shop(data['district'], data['shop_name'],
                    data['official_shop_name'], data['address'], data['owner'],
                    data['phone_number'], data['seller_name'],
                    data['cash_machine'])
    new_shop.add_shop()
    await message.answer(f"Готово!\n"
                         f"Торговая точка была добавлена в базу!\n\n"
                         f"{data['shop_name']}\n"
                         f"{data['owner']} {data['official_shop_name']}\n"
                         f"Адрес: {data['district']}, {data['address']}\n"
                         f"Телефон: {data['phone_number']}\n"
                         f"Продавец: {data['seller_name']}\n"
                         f"Кассовый аппарат: {data['cash_machine']}")
    await state.finish()
Exemplo n.º 8
0
    def setUp(self):
        """Make demo data."""

        Image.query.delete()
        Shop.query.delete()
        User.query.delete()

        user = User.signup(**USER)
        shop = Shop(**SHOP)
        image_1 = Image(**IMAGE_1)
        image_2 = Image(**IMAGE_2)
        db.session.add_all([user, shop, image_1, image_2])
        db.session.commit()
        db.session.refresh(user)
        db.session.refresh(shop)
        db.session.refresh(image_1)
        db.session.refresh(image_2)
        db.session.expunge_all()

        self.user = user
        self.shop = shop
        self.image_1 = image_1
        self.image_2 = image_2
Exemplo n.º 9
0
def fill_db(name):
    shop = Shop(name)
    list_supplier = [['reep', '*****@*****.**'],
                     ['megacorp', '*****@*****.**'],
                     ['ajax', '*****@*****.**'],
                     ['jungle', '*****@*****.**'],
                     ['gnom', '*****@*****.**'],
                     ['qwerty', '*****@*****.**']]

    list_product = [['автомобили', 122, 953, 4], ['авиатехника', 121, 755, 3],
                    ['автомобили_грузовые', 8123, 56, 2],
                    ['корабли', 125, 978, 1], ['одежда', 126, 877, 4],
                    ['электроинструменты', 126, 777, 2],
                    ['мотоциклы', 126, 677, 3], ['украшения', 126, 777, 1],
                    ['мебель', 345, 889,
                     5], ['игрушки_авиамодели', 324, 998, 6],
                    ['drons', 234, 876, 3], ['книги_журналы', 324, 898, 5],
                    ['робототехника', 567, 987, 6]]

    list_foodstaff = [['бананы', 124, 23, 'аргентина', '11,09,17', 1],
                      ['киви', 127, 234, 'chili', '12,09,17', 2],
                      ['апельсины', 128, 73, 'египет', '13,09,17', 3],
                      ['виноград', 120, 355, 'chili', '12,09,17', 4],
                      ['манго', 128, 70, 'египет', '13,09,17', 3],
                      ['яблоки', 528, 71, 'черногория', '13,09,17', 4],
                      ['лимоны', 128, 70, 'марокко', '13,07,17', 5],
                      ['сахар', 128, 70, 'куба', '13,09,17', 6],
                      ['персики', 328, 77, 'армения', '23,11,17', 2]]

    for i in list_supplier:
        shop.add_supplier(i[0], i[1])

    for i in list_product:
        shop.add_product(i[0], i[1], i[2], i[3])

    for i in list_foodstaff:
        shop.add_foodstuff(i[0], i[1], i[2], i[3], i[4], i[5])
Exemplo n.º 10
0
#  запись результата запросов потоками в .txt файлы и запуск сервера
from models import Shop
from fill_db import fill_db
import os
import json
import threading
import sys

DIR = 'save_query_files'
shop = Shop('shop_base.db')  # имя бд sqlite
shop.create_new()
fill_db('shop_base.db')  # автозаполнение бд


class WriteStream(threading.Thread):
    def __init__(self, name_file, query):
        super().__init__()
        self.name_file = name_file
        self.query = query

    def run(self):
        result = []
        for i in self.query:
            result.append(i)
        with open(os.path.join(DIR, self.name_file), 'w',
                  encoding='UTF-8') as f:
            json.dump(result, f)


class ReadStream(threading.Thread):
    def __init__(self, name_file):
Exemplo n.º 11
0
     Publisher(id=1, name='Поставщик №1'),
     Publisher(id=2, name='Поставщик №2'),
     Publisher(id=3, name='Поставщик №3')
 ])
 session.commit()
 session.add_all([
     Book(id=1, title='Книга 1 поставщика №1', id_publisher=1),
     Book(id=2, title='Книга 2 поставщика №1', id_publisher=1),
     Book(id=3, title='Книга 3 поставщика №1', id_publisher=1),
     Book(id=4, title='Книга 1 поставщика №2', id_publisher=2),
     Book(id=5, title='Книга 2 поставщика №2', id_publisher=2),
     Book(id=6, title='Книга 1 поставщика №3', id_publisher=3)
 ])
 session.commit()
 session.add_all([
     Shop(id=1, name='Магазин №1'),
     Shop(id=2, name='Магазин №2')
 ])
 session.commit()
 session.add_all([
     Stock(id=1, count=3, id_book=1, id_shop=1),
     Stock(id=2, count=2, id_book=1, id_shop=2),
     Stock(id=3, count=5, id_book=2, id_shop=2),
     Stock(id=4, count=0, id_book=3, id_shop=1),
     Stock(id=5, count=2, id_book=4, id_shop=1),
     Stock(id=6, count=3, id_book=4, id_shop=2),
     Stock(id=7, count=4, id_book=6, id_shop=1)
 ])
 session.commit()
 session.add_all([
     Sale(id=1, price=15, date_sale='11.02.2020', id_stock=1, count=3),
Exemplo n.º 12
0
 def make_shop(self, data):
     return Shop(**data)
Exemplo n.º 13
0
users = [
    User.signup(username="******",
                password="******",
                first_name="Desmond",
                last_name="McLemore"),
    User.signup(username="******",
                password="******",
                first_name="Justin",
                last_name="Ludington")
]

db.session.add_all(users)

shops = [
    Shop(name="Dog Photos",
         description="Just a bunch of cute dog pics!!",
         is_private=False,
         user="******"),
    Shop(name="Practice Shots",
         description="Practice shots",
         is_private=True,
         user="******"),
    Shop(name="Not Practice Shots",
         description="These ones aren't practice.",
         is_private=False,
         user="******")
]

db.session.add_all(shops)

images = [
    Image(
Exemplo n.º 14
0
def build_db():

    db.drop_all()
    db.create_all()

    wr_bielany = Shop(name=u"Wrocław-Bielany",
                      start_time=time(8),
                      end_time=time(19),
                      shift_length=time(8))
    wr_olawska = Shop(name=u"Wrocław-Oławska",
                      start_time=time(8),
                      end_time=time(19),
                      shift_length=time(8))

    roles = [
        Role(name=u'Admin'),
        Role(name=u'Kierownik'),
        Role(name=u'Zastępca kierownika'),
        Role(name=u'Starszy sprzedawca'),
        Role(name=u'Sprzedawca'),
    ]

    employees = [
        (u"Fredynand", u"Kiepski", roles[1], wr_bielany),
        (u"Marian", u"Paździoch", roles[2], wr_bielany),
        (u"Arnold", u"Boczek", roles[3], wr_bielany),
        (u"Waldemar", u"Kiepski", roles[4], wr_bielany),
        (u"Janusz", u"Socha", roles[4], wr_bielany),
        (u"Władysław", u"Słoik", roles[1], wr_olawska),
        (u"Alojzy", u"Pęduszko", roles[2], wr_olawska),
        (u"Barbara", u"Kwarc", roles[3], wr_olawska),
        (u"Izaak", u"Rosenfeld", roles[4], wr_olawska),
        (u"Grażyna", u"Janusz", roles[4], wr_olawska),
    ]

    with app.app_context():

        db.session.add(wr_bielany)
        db.session.add(wr_olawska)
        db.session.commit()

        for role in roles:
            db.session.add(role)
        db.session.commit()

        for first_name, last_name, role, shop in employees:
            username = first_name[0].lower() + last_name.lower()
            user_datastore.create_user(username=username,
                                       first_name=first_name,
                                       last_name=last_name,
                                       email=username + u"@Shop.pl",
                                       password=encrypt_password(username),
                                       roles=[role],
                                       shops=[shop])
        db.session.commit()

        user_datastore.create_user(username='******',
                                   first_name='Admin',
                                   email='*****@*****.**',
                                   password=encrypt_password('admin'),
                                   roles=[roles[0]],
                                   shops=[wr_bielany, wr_olawska])
        db.session.commit()