Exemplo n.º 1
0
 def multi_insert_mysql_data(self, engine, data_dict, logger):
     # 连接引擎
     # conn = engine.connect()
     # 传递参数并执行语句
     try:
         # 绑定引擎
         metadata = MetaData(engine)
         # 连接数据表
         # print("all_insert_data_dict:",data_dict)
         new_dict = {}
         for data_list in data_dict:
             for table, data in data_list.items():
                 tb_bdm_employee = Table(table, metadata, autoload=True)
                 ins = tb_bdm_employee.insert()
                 new_dict[ins] = data
         print('new_dict', new_dict)
         with engine.begin() as conn:
             # conn = engine.begin()
             for ins, data in new_dict.items():
                 result = conn.execute(ins, **data)
         return result.lastrowid
     except Exception as e:
         file_path = os.path.join(
             sys.path[0], "logs", "%s.log" % datetime.datetime.strftime(
                 datetime.datetime.now(), "%Y_%m_%d"))
         log = logger(filename=file_path)
         log.removeHandler(log.handlers)
         log.info(e.__str__())
         traceback.print_exc()
         return False
Exemplo n.º 2
0
def form(request):

    if request.method == "POST":

        try:
            num = Table.objects.get(url=request.POST["nombre"]).id
            return HttpResponse("La url cortada es :" + str(num))
        except Table.DoesNotExist:
            record = Table(url=request.POST["nombre"].replace(
                '%3A', ':').replace('%2F', '/'))
            record.save()
            return HttpResponse(
                "La url cortada es :" + "<a href=" +
                Table.objects.get(url=request.POST["nombre"]).url + ">" +
                str(Table.objects.get(url=request.POST["nombre"]).id) + "</a>")
    form = ""
    form += "<body><h1>Url Shortener </h1><form method=post>Escribe la url:<input type=text name= nombre value=http:// /> <br/><input type=submit value=Enviar /></form>"
    contents = Table.objects.all()
    respues = "<ul>"
    for cont in contents:
        print cont
        respues += "<li> <a href=" + str(cont.id) + ">" + str(
            cont.url) + "</a></li>"
    respues += "</ul></body></html>"
    return HttpResponse(form + respues)
Exemplo n.º 3
0
def analyze(request, recurso):

    salida = ""
    if request.method == 'GET':
        print str(request.user.is_authenticated())
        try:
            record = Table.objects.get(resource=recurso)
            return HttpResponse(record.name)
        except Table.DoesNotExist:

            lista = Table.objects.all()
            for fila in lista:
                salida += "<ul><li> Recurso: " + str(
                    fila.resource) + "\r" + str(fila.name) + "</li></ul>"
            return HttpResponseNotFound('<br>Recurso no disponible' + salida)
    elif request.method == 'PUT':
        print str(request.user.is_authenticated())
        if request.user.is_authenticated():
            record = Table(resource=recurso, name=request.body)
            record.save()
            return HttpResponse("<h1><p>Logged in as " +
                                request.user.username +
                                "</p>Actualizando.../h1>" + str(recurso) +
                                "......" + str(request.body))

        else:
            return HttpResponse("Not logged in" + "<a href=http://" +
                                request.get_host() + "/admin" + "> Log in</a>")
Exemplo n.º 4
0
def produceTable():
    session = CreateSession()
    p = session.query(Table).delete()
    session.commit()
    managers = session.query(Managers).all()
    for m in managers:
        f = session.query(Fixtures).filter_by(managerId=m.id).all()
        score = sum([i.score for i in f if i.score is not None])
        points = sum([i.points for i in f if i.score is not None])
        tb = Table(managerId=m.id, score=score, points=points)
        session.add(tb)
    session.commit()
    t = session.query(Table).order_by(desc(Table.points)).order_by(
        desc(Table.score)).all()
    p = session.query(Table).delete()
    session.commit()
    x = 0
    for i in t:
        x += 1
        tb = Table(position=x,
                   managerId=i.managerId,
                   score=i.score,
                   points=i.points)
        session.add(tb)
    session.commit()
    session.close()
Exemplo n.º 5
0
 def update_mysql_data(self, engine, schema, table_name, data_dict, where,
                       logger):
     # sql_comment = 'UPDATE %s SET ' % table_name + ','.join(['%s=%r' % (k, data_dict[k]) for k in data_dict]) + ' WHERE %s=%r;' % (where[0], where[1])
     # cursor = session.execute(sql_comment)
     # session.commit()
     # result = cursor.lastrowid
     # print("cursor",cursor)
     # print("result",result)
     # print(cursor.lastrowid)
     try:
         # 绑定引擎
         metadata = MetaData(engine)
         # 连接数据表
         tb_bdm_employee = Table(table_name, metadata, autoload=True)
         # 连接引擎
         conn = engine.connect()
         ins = tb_bdm_employee.update().where(
             schema.Column(where[0]) == where[1]).values(
                 **data_dict
             )  # table.update().where(table.c.id==7).values(name='foo')
         # 传递参数并执行语句
         result = conn.execute(ins)
         return result
     except Exception as e:
         print("error_update_dict:", data_dict)
         file_path = os.path.join(
             sys.path[0], "logs", "%s.log" % datetime.datetime.strftime(
                 datetime.datetime.now(), "%Y_%m_%d"))
         log = logger(filename=file_path)
         log.removeHandler(log.handlers)
         log.info(e.__str__())
         traceback.print_exc()
         return None
Exemplo n.º 6
0
 def test_models(self):
     #Create a Table and a Waiter
     table = Table(table_no="table1")
     db.session.add(table)
     table2 = Table(table_no="table2")
     db.session.add(table2)
     table3 = Table(table_no="table3")
     db.session.add(table3)
     table4 = Table(table_no="table4")
     db.session.add(table4)
     table5 = Table(table_no="table4")
     db.session.add(table4)
     waiter = Waiter(name="Juan")
     db.session.add(waiter)
     db.session.commit()
     service = Service(tip=90.80)
     db.session.add(service)
     db.session.commit()
     service = Service(tip=90.80)
     db.session.add(service)
     db.session.commit()
     service = Service(tip=90.80)
     db.session.add(service)
     db.session.commit()
     service = Service(tip=90.80)
     db.session.add(service)
     db.session.commit()
     try:
         service = Service(tip=90.80)
     except Exception:
         pass
Exemplo n.º 7
0
    def insert_mysql_data(self, engine, table_name, data_dict, logger):
        # sql_comment = "insert into  {table_name} {filed_list}  values {data_tuple}".format(
        #                 table_name=table_name,filed_list=filed_list, data_tuple=data_tuple)
        # sql_comment = "insert into tb_bdm_employee 'EmployeeID'  values 5"
        # # print(sql_comment)
        # cursor = session.execute(sql_comment)
        # session.commit()
        # result = cursor.lastrowid
        # print(cursor.lastrowid)
        try:
            # 绑定引擎
            metadata = MetaData(engine)
            # 连接数据表
            tb_bdm_employee = Table(table_name, metadata, autoload=True)
            # 连接引擎
            conn = engine.connect()
            ins = tb_bdm_employee.insert()
            # 传递参数并执行语句
            result = conn.execute(ins, **data_dict)
            return result.lastrowid

        except Exception as e:
            traceback.print_exc()
            file_path = os.path.join(
                sys.path[0], "logs", "%s.log" % datetime.datetime.strftime(
                    datetime.datetime.now(), "%Y_%m_%d"))
            log = logger(filename=file_path)
            log.removeHandler(log.handlers)
            log.info(e.__str__())
            traceback.print_exc()
            return None
def analyze (request,recurso):

    theParser = make_parser()
    theHandler = myContentHandler()
    theParser.setContentHandler(theHandler)
    file = urllib2.urlopen( 'http://barrapunto.com/index.rss')
    theParser.parse(file)
    theHandler.htmlFile.close()

    print "Parse complete"


    if request.method == 'GET':
        index = open("index.html","r")
        html=index.read()

        try:
            record = Table.objects.get(resource=recurso)
            return HttpResponse(record.name+"<ul>"+html.decode('utf-8')+"</ul>")
        except Table.DoesNotExist:
            return HttpResponseNotFound('Page not found:')

    elif request.method == 'PUT':
        record = Table(resource= recurso,name =request.body)
        record.save()
        return HttpResponse('<h1>Actualizando.../h1>'+ request.body)
Exemplo n.º 9
0
def read_sales_by_employee_over_time():
    table = Table(connection, q.query_rental_by_staff)
    table.df = table.df[['staff_id', 'month(rental_date)', 'total_sales']]
    table.df = table.df.pivot(index='month(rental_date)',
                              columns='staff_id', values='total_sales')
    table.df = table.df.reset_index()
    result_json = table.df.to_json(orient='records')
    return Markup(result_json)
Exemplo n.º 10
0
 def insert_sqlserver_data(self, engine, table_name, data_dict):
     # 绑定引擎
     metadata = MetaData(engine)
     # 连接数据表
     tb_bdm_employee = Table(table_name, metadata, autoload=True)
     # 连接引擎
     conn = engine.connect()
     ins = tb_bdm_employee.insert()
     # 传递参数并执行语句
     result = conn.execute(ins, **data_dict)
     return result
Exemplo n.º 11
0
 def update_sqlserver_data(self, engine, table_name, data_dict, where):
     metadata = MetaData(engine)
     # 连接数据表
     tb_bdm_employee = Table(table_name, metadata, autoload=True)
     # 连接引擎
     conn = engine.connect()
     ins = tb_bdm_employee.update().where(
         schema.Column(where[0]) == where[1]).values(
             **data_dict
         )  # table.update().where(table.c.id==7).values(name='foo')
     # 传递参数并执行语句
     result = conn.execute(ins)
     return result
Exemplo n.º 12
0
def read_sales_over_inventory():
    table_sales_by_category = Table(connection,
        q.query_sales_by_movie)
    table_inventory_by_category = Table(connection,
        q.query_movie_inventory_by_category)
    table_inventory_by_category.df.columns = ['category_id', 'name',
        'inventory_count']
    table_sales_by_category.df['sales_over_inventory'] = \
        table_sales_by_category.df['total_sales'] / \
        table_inventory_by_category.df['inventory_count']
    columns = ['Category', 'Total Sales', 'Sales Over Inventory']
    result_json = table_sales_by_category.get_json_rep(columns)
    return result_json
Exemplo n.º 13
0
def analyze(request, recurso):

    if request.method == 'GET':
        try:
            record = Table.objects.get(resource=recurso)
            return HttpResponse(record.name)
        except Table.DoesNotExist:
            return HttpResponseNotFound('Page not found:')

    elif request.method == 'PUT':
        record = Table(resource=recurso, name=request.body)
        record.save()
        return HttpResponse('<h1>Actualizando.../h1>' + request.body)
Exemplo n.º 14
0
class TestTable(unittest.TestCase):

    def setUp(self):
        self.table1 = Table('table1', 5, 5)
        self.table2 = Table('table1', 10, 10)
        self.table3 = Table('table1', 50, 50, {'TO_SOUTH': 1, 'TO_NORTH': -1, 'TO_WEST': 1, 'TO_EAST': -1})
        self.table4 = Table('table1', 100, 100, {'TO_SOUTH': 1, 'TO_NORTH': -1, 'TO_WEST': -1, 'TO_EAST': 1})

    def test_get_coordinate(self):
        self.assertTrue(Coordinate(3, 3) == self.table1.get_coordinate(3, 3))
        self.assertTrue(Coordinate(8, 9) == self.table2.get_coordinate(8, 9))
        self.assertTrue(Coordinate(34, 45) == self.table3.get_coordinate(34, 45))
        self.assertTrue(Coordinate(78, 88) == self.table4.get_coordinate(78, 88))
Exemplo n.º 15
0
def show_css (request,recurso):
    
    if request.method == 'GET':
       
        try:
            record = Table.objects.get(resource=recurso)
            return HttpResponse(record.name, content_type="text/css")
        except Table.DoesNotExist:
            return HttpResponseNotFound('Page not found:')
        
    elif request.method == 'PUT':
        record = Table(resource= recurso,name =request.body)  
        record.save()
        return HttpResponse('<h1>Actualizando.../h1>'+ request.body)
Exemplo n.º 16
0
    def create_snapshot(self, snapshot_name, before_copy=None):
        snapshot = Snapshot(snapshot_name=snapshot_name,
                            project_name=self.config['project_name'])
        self.db.session.add(snapshot)
        self.db.session.flush()

        for table_name in self.config['tracked_databases']:
            if before_copy:
                before_copy(table_name)
            table = Table(table_name=table_name, snapshot=snapshot)
            self.operations.copy_database(table_name,
                                          table.get_table_name('master'))
            self.db.session.add(table)
        self.db.session.commit()

        self.start_background_slave_copy(snapshot)
Exemplo n.º 17
0
def urls(request, resource):
    if request.method == "GET":
        list = Table.objects.filter(blog=resource)
        if not list:
            return notfound(request, resource)
        out = " "
        for i in list:
            out += 'Blog \" ' + i.blog + ' \": '
            out += "<a href=http://" + i.url + ">" + i.url + "</a>\n"
        return HttpResponse(out)
    elif request.method == "PUT":
        new_blog = Table(blog=resource, url=request.body)
        new_blog.save()
        out = ("New blog added. ")
        return HttpResponse(out)
    else:
        return HttpResponseForbidden
Exemplo n.º 18
0
def show_html(request,recurso):
     
      if request.method == 'PUT':
        pos_in= request.body.find("<body>")
        pos_fin= request.body.find("</body>")
        record = Table(resource= recurso,name =request.body[pos_in+7:pos_fin]) 
        record.save()
        return HttpResponse('<h1>Actualizando.../h1>'+ request.body)
      elif request.method == 'GET':
       
        try:
            record = Table.objects.get(resource=recurso)
            
            template = get_template("index.html")
            return HttpResponse(template.render(Context({'body': record.name})))
        except Table.DoesNotExist:
            return HttpResponseNotFound('Page not found:')
Exemplo n.º 19
0
def create_table():
    deck_identifier = ''.join(
        random.choice(string.ascii_uppercase + string.digits)
        for _ in range(40))
    init_deck(deck_identifier)

    db.session.add(Table(deck_identifier))
    db.session.commit()
Exemplo n.º 20
0
def group(id):
    record = Group.query.get(id)
    members_only(current_user, record)
    if request.method == "POST":
        table = Table.create(group_id=record.id)
        return redirect(url_for("show_table", table_name=table.name))
    return render_template("group.html",
                           group=record,
                           tables=record.tables,
                           current_table=current_user.current_table)
Exemplo n.º 21
0
def addTable(request):
    data = {}
    data.update(csrf(request))
    if request.method == 'POST': #jak wyslano formularza
        form = AddTableForm(request.POST)
        if form.is_valid(): #jak wszystko okej
            #to pozmieniaj dane
            newTable = Table();
            newTable.maxClientsCount = form.cleaned_data['maxClients']
            newTable.addedBy = request.user
            newTable.save()
            #informacje
            data['information'] = 'Dodano stolik numer '+newTable.pk.__str__()
            data['back']='../'
            return render_to_response('info.html',data)
    else:
        form = AddTableForm()
        data['form'] = form
        return render_to_response('addTable.html',data)
Exemplo n.º 22
0
def form(request):
    if request.method == "GET":
        out = ""
        form = '<form action="" method="POST">'
        form += 'URL a acortar: <input type="text" name="real_url">'
        form += '<input type="submit" value="Enviar">'
        form += '</form>'

        out += form
        list = Table.objects.all()
        if list:
            out += "The previous searches are: "
            out += "<html><body><ul>\n"
            for i in list:
                out += "<li><a href=" + str(i.id) + ">"
                out += i.real_url + "</a></li>\n"
            out += "</ul></body></html>"
        else:
            out += "There are no previous searches on this page"
            out += "</ul></body></html>"
        return HttpResponse(out)
    elif request.method == "PUT" or request.method == "POST":
        out = ""
        url = request.body
        url = url.split("real_url=")[1]
        if url == "":
            return HttpResponseBadRequest("Empty url")
        elif not url.startswith("http://") and not url.startswith("https://"):
            url = "http://" + url
        else:
            url = url.split("%3A%2F%2F")[0]
        try:
            new = Table.objects.get(real_url=request.body)
        except Table.DoesNotExist:
            new = Table(real_url=url)
            new.save()

        out += ("<html><body>" + "URL buscada: " + "<a href=" + url + ">" +
                url + "</href></br>" + "URL acortada: " + "<a href=" +
                str(new.id) + ">" + str(new.id) + "</href></br>" +
                "</body></html>")
        return HttpResponse(out)
Exemplo n.º 23
0
def form(request):
    if request.method == "GET":
        out = ""
        form = '<form action="" method="POST">'
        form += 'URL a acortar: <input type="text" name="real_url">'
        form += '<input type="submit" value="Enviar">'
        form += '</form>'

        out += form
        list = Table.objects.all()
        if list:
            out += "The previous searches are: "
            out += "<html><body><ul>\n"
            for i in list:
                out += "<li><a href=" + str(i.id) + ">"
                out += i.real_url + "</a></li>\n"
            out += "</ul></body></html>"
        else:
            out += "There are no previous searches on this page"
            out += "</ul></body></html>"
        return HttpResponse(out)
    elif request.method == "PUT" or request.method == "POST":
        out = ""
        url = request.body
        url = url.split("real_url=")[1]
        if url == "":
            return HttpResponseBadRequest("Empty url")
        elif not url.startswith("http://") and not url.startswith("https://"):
            url = "http://" + url
        else:
            url = url.split("%3A%2F%2F")[0]
        try:
            new = Table.objects.get(real_url=request.body)
        except Table.DoesNotExist:
            new = Table(real_url=url)
            new.save()

        out += ("<html><body>" + "URL buscada: "
                + "<a href=" + url + ">" + url + "</href></br>"
                + "URL acortada: " + "<a href=" + str(new.id) + ">"
                + str(new.id) + "</href></br>" + "</body></html>")
        return HttpResponse(out)
Exemplo n.º 24
0
def form(request):

    if request.method == "POST":

        try:
            num = Table.objects.get(url=request.POST["nombre"]).id
            return HttpResponse("La url cortada es :"+str(num))
        except Table.DoesNotExist:
            record = Table(url= request.POST["nombre"].replace('%3A',':').replace('%2F','/'))
            record.save()
            return HttpResponse("La url cortada es :" +"<a href="+Table.objects.get(url=request.POST["nombre"]).url +">"+str(Table.objects.get(url=request.POST["nombre"]).id)+"</a>")
    form=""
    form+="<body><h1>Url Shortener </h1><form method=post>Escribe la url:<input type=text name= nombre value=http:// /> <br/><input type=submit value=Enviar /></form>"
    contents=Table.objects.all()
    respues="<ul>"
    for cont in contents:
        print cont
        respues+="<li> <a href="+str(cont.id)+">"+str(cont.url)+"</a></li>"
    respues+="</ul></body></html>"
    return HttpResponse(form+respues)
Exemplo n.º 25
0
def sendmail(text):
    # check optional params on type
    if type(text["optional"]) != str or not text:
        return "Error optional"
    # write data and time for identification to db and give result
    try:
        # add time in text
        text["time"] = time.time()

        # connect to db
        db = Table("email", "email")
        #db.show_db()

        # insert data + time
        data = db.insert(**text)
        #print(data)
        return "Success"
    except:
        pass
        return "Error email"
Exemplo n.º 26
0
def newtable(request):
	if request.method == 'POST': # If the form has been submitted...
		# ContactForm was defined in the the previous section
		form = NewTableForm(request.POST) # A form bound to the POST data
		if form.is_valid(): # All validation rules pass
	# Process the data in form.cleaned_data
	# ...

			newTableEntry = Table(currentUsers=1, tableLimit=form.cleaned_data['tableLimit'], tableBlind=form.cleaned_data['tableBlind'] )
			newTableEntry.save()
			args = RequestContext(request)
			
			args['user']= request.user
		return redirect( '/tables/'+ str(newTableEntry.id));
	else:
		form = NewTableForm() # An unbound form

		return render(request, 'createTable.html', {
		'form': form,
		})
Exemplo n.º 27
0
def newtable(request):
    if request.method == 'POST':  # If the form has been submitted...
        # ContactForm was defined in the the previous section
        form = NewTableForm(request.POST)  # A form bound to the POST data
        if form.is_valid():  # All validation rules pass
            # Process the data in form.cleaned_data
            # ...

            newTableEntry = Table(currentUsers=1,
                                  tableLimit=form.cleaned_data['tableLimit'],
                                  tableBlind=form.cleaned_data['tableBlind'])
            newTableEntry.save()
            args = RequestContext(request)

            args['user'] = request.user
        return redirect('/tables/' + str(newTableEntry.id))
    else:
        form = NewTableForm()  # An unbound form

        return render(request, 'createTable.html', {
            'form': form,
        })
Exemplo n.º 28
0
def urls(request, resource):
    if request.method == "GET":
        list = Table.objects.filter(blog=resource)
        if not list:
            return notfound(request, resource)
        out = " "
        for i in list:
            out += 'Blog \" ' + i.blog + ' \": '
            out += "<a href=http://" + i.url + ">" + i.url + "</a>\n"
        out += login_message(request)
        return HttpResponse(out)
    elif request.method == "PUT":
        if request.user.is_authenticated():
            new_blog = Table(blog=resource, url=request.body)
            new_blog.save()
            out = ("New blog added. ")
        else:
            out = ("You must log in.")
        out += login_message(request)
        return HttpResponse(out)
    else:
        return HttpResponseForbidden
Exemplo n.º 29
0
def json2schema(schema_json, commit = True, destdb = None):
    """
    Creates Database, Table, and Column objects as needed to satisfy the incoming schema.
    If the table is already present, assume we are updating: delete all columns and recreate from the schema.
    Unless commit is false, call the required sql to create the incoming tables in the destination database.
    """

    schema = json.loads(schema_json)

    for dbname, table_schema in schema.iteritems():
        if destdb:
            dbname = destdb

        try:
            db = Database.objects.get(name=dbname)
        except Database.DoesNotExist:
            db = Database(name=dbname)
            db.save()

        for tablename, column_schema in table_schema.iteritems():
            try:
                table = Table.objects.get(db=db, name=tablename)
                for column in Column.objects.filter(table=table):
                    column.delete()
            except Table.DoesNotExist:
                table = Table(db=db, name=tablename)
                table.save()

            for columnname, columntype in column_schema.iteritems():
                column = Column(table=table, name=columnname, type=columntype)
                column.save()

            if commit:
                model = ModelGenerator.getModel(dbname, tablename)
                cursor = connections[dbname].cursor()
                for sql in ModelGenerator.getSQL(model):
                    cursor.execute(sql)
    return None
Exemplo n.º 30
0
    def create_snapshot(self, snapshot_name, before_copy=None):
        snapshot = Snapshot(
            snapshot_name=snapshot_name,
            project_name=self.config['project_name']
        )
        self.db.session.add(snapshot)
        self.db.session.flush()

        for table_name in self.config['tracked_databases']:
            if before_copy:
                before_copy(table_name)
            table = Table(
                table_name=table_name,
                snapshot=snapshot
            )
            self.operations.copy_database(
                table_name,
                table.get_table_name('master')
            )
            self.db.session.add(table)
        self.db.session.commit()

        self.start_background_slave_copy(snapshot)
Exemplo n.º 31
0
def analyze (request,recurso):
    
    salida =""
    if request.method == 'GET':
        print str(request.user.is_authenticated())
        try:
            record = Table.objects.get(resource=recurso)
            return HttpResponse(record.name)
        except Table.DoesNotExist:
            
            lista=Table.objects.all()
            for fila in lista:
                salida += "<ul><li> Recurso: "+str(fila.resource)+"\r"+str(fila.name)+"</li></ul>" 
            return HttpResponseNotFound('<br>Recurso no disponible'+salida)
    elif request.method == 'PUT':
        print str(request.user.is_authenticated())
        if request.user.is_authenticated():
            record = Table(resource= recurso,name =request.body)  
            record.save()
            return HttpResponse("<h1><p>Logged in as "  + request.user.username+"</p>Actualizando.../h1>"+ str(recurso)+"......"+str(request.body))
            
        else:
            return HttpResponse("Not logged in"+"<a href=http://"+request.get_host()+"/admin"+"> Log in</a>")
Exemplo n.º 32
0
    def _getDbTables(self, cur, schema_id):
        tables = []

        db_tables = cur.execute(
            """ SELECT * from dbd$tables
                                    WHERE schema_id = :id
                                    GROUP BY id""", {
                "id": schema_id
            }).fetchall()
        tables_metadata = self._getMetadata(cur, "dbd$tables")

        for table in db_tables:
            table_dictionary = dict(zip(tables_metadata, list(table)))
            tmp = Table(table_dictionary)

            if table_dictionary.get("id") is not None:
                tmp.fields = self._getDbFields(cur, table_dictionary["id"])
                tmp.constraints = self._getDbConstraints(
                    cur, table_dictionary["id"])
                tmp.indices = self._getDbIndices(cur, table_dictionary["id"])

            tables.append(tmp)

        return tables
Exemplo n.º 33
0
 def update_mysql_data(self, engine, schema, table_name, data_dict, where, logger):
     try:
         # 绑定引擎
         metadata = MetaData(engine)
         # 连接数据表
         tb_bdm_employee = Table(table_name, metadata, autoload=True)
         # address_table = Table('address', metadata, autoload=True)
         # 连接引擎
         conn = engine.connect()
         # print('where', where)
         # print('data_dict', data_dict)
         ins = tb_bdm_employee.update().where(schema.Column(where[0]) == where[1]).values(
             **data_dict)  # table.update().where(table.c.id==7).values(name='foo')
         # 传递参数并执行语句
         result = conn.execute(ins)
         return result
     except Exception as e:
         file_path = os.path.join(sys.path[0], "logs",
                                  "%s.log" % datetime.datetime.strftime(datetime.datetime.now(), "%Y_%m_%d"))
         log = logger(filename=file_path)
         log.removeHandler(log.handlers)
         log.info(e.__str__())
         traceback.print_exc()
         return None
Exemplo n.º 34
0
    def test_models(self):
        #Create a Table and a Waiter
        table = Table(table_no="table1")
        db.session.add(table)
        waiter = Waiter(name="Juan")
        db.session.add(waiter)
        db.session.commit()
        service = Service(tip=90.80)
        db.session.add(service)
        db.session.commit()

        query = Service.query.all()
        #Check that all users exist
        assert len(query) == 1
        assert query[0].table_id == 1
        assert query[0].waiter_id == 1
        assert ((query[0].exit - query[0].arrival).seconds / 60) >= 90
Exemplo n.º 35
0
    def deploy(self, table_params=[{}], robot_names=[]):
        if table_params and robot_names:
            for t in table_params:
                if set(Table.attributes) <= set(t):
                    self.tables[t['name']] = Table(t['name'], t['dx'], t['dy'],
                                                   t['rule'])
                else:
                    print('Table parameters "%s" not valid!' % t)

            for name in robot_names:
                self.robots[str(name)] = Robot(str(name))

            return True

        else:
            print("No valid data for creating tables and robots!")
            return False
Exemplo n.º 36
0
 def post(self):
     status_code = 200
     parser = reqparse.RequestParser()
     parser.add_argument("table_category_id")
     parser.add_argument("restaurant_id")
     parser.add_argument("seat_count")
     parser.add_argument("count")
     args = parser.parse_args()
     try:
         table = Table(category_id=args['table_category_id'], restaurant_id=args['restaurant_id'],
                                     seat_count=args['seat_count'], count=args['count'])
         db.session.add(table)
         db.session.commit()
         result = {'Table': table.id}
     except:
         status_code = 404
         result = {'message': 'There is some error'}
     return result, status_code
Exemplo n.º 37
0
    def get(self):
        user = users.get_current_user()
        restaurant = Restaurant.query(Restaurant.user == user.email()).fetch()
        if restaurant:
            log_url = users.create_logout_url('/')
            restaurant = restaurant[0]
            tables = Table.query(Table.restaurant_id == restaurant.key).order(
                Table.time_filled).fetch()
            template_vars = {
                "tables": tables,
                "restaurant": restaurant,
                "log_url": log_url,
            }
            tables_template = jinja_current_directory.get_template(
                "templates/tables.html")
            self.response.write(tables_template.render(template_vars))

        else:
            self.response.write(users.create_logout_url('/'))
Exemplo n.º 38
0
    def post(self):
        user = users.get_current_user()
        Restaurant(
            name=self.request.get('name_r'),
            phone=self.request.get('phone_r'),
            street_address=self.request.get('street'),
            city=self.request.get('city'),
            state=self.request.get('state'),
            zip_code=self.request.get('zip'),
            user=user.email(),
        ).put()

        Table(
            description=self.request.get('table_description'),
            max=self.request.get('table_size_max'),
            min=self.request.get('table_size_min'),
            #restaurant_id = self.request.get(),
            full=False,
            time_filled=datetime.datetime.now(),
        ).put()
Exemplo n.º 39
0
def read_sales_last_month_over_time():
    table = Table(connection, q.query_payments_by_date_month)
    table.df = table.df[['day(payment_date)', 'sum(amount)']]
    columns = ['Day', 'Payments']
    result_json = table.get_json_rep(columns)
    return result_json
Exemplo n.º 40
0
def read_films_in_inventory_by_category():
    table = Table(connection, q.query_movie_inventory_by_category)
    columns = ['Category', 'Inventory Count']
    table.df = table.df[['name', 'count(*)']]
    result_json = table.get_json_rep(columns)
    return result_json
Exemplo n.º 41
0
def read_films_in_inventory_by_store():
    table = Table(connection, q.query_films_in_inventory_by_store)
    columns = ['Store ID', 'Number of Films']
    result_json = table.get_json_rep(columns)
    return result_json
Exemplo n.º 42
0
def read_films_in_inventory_most_rented():
    this_table = Table(connection, q.query_top_rented_films)
    columns = ['Film ID', 'Title', 'Release Year', 'Number of Rentals']
    html_rep = this_table.get_html_rep(columns)
    return html_rep
Exemplo n.º 43
0
from models import Table
from utils import clearscreen

# start with blank screen
clearscreen()
# building the blank sudoku table
sudoku = Table()
# Having the user enter the sudoku puzzle
sudoku.get_table()

print("This is your sudoku puzzle:")
print(sudoku)
num = 1
row = 0
col = 0
counter = 0
max_tries = 1000
# This will loop through while the puzzle isn't solved, or until it's
# reached the maximum tries.
while sudoku.puzzle_has_blanks() and counter < max_tries:
    for num in range(10):
        # this will cause it to iterate through the sectors in the grid
        for sector_id in range(9):
            # setting the number of flagged/possible spots to 0
            sudoku.flagged_spots = 0
            # the massive if statements that looks at a box in the puzzle to
            # determine if those things are all true.
            for number_in_block, row, col in sudoku.iter_sector(sector_id):
                if (sudoku.current_box_is_blank(row, col)
                        and sudoku.num_is_not_in_sector(row, col, num)
                        and sudoku.num_is_not_in_row(row, col, num)
Exemplo n.º 44
0
 def __init__(self, grammar, input_buffer):
     self.grammar = grammar
     self.input_buffer = input_buffer
     self.states = []
     self.table = Table()
Exemplo n.º 45
0
def read_customers_lost_by_country():
    this_table = Table(connection, q.query_customers_lost_by_country)
    columns = ['Country', 'Number of Customers Lost']
    html_rep = this_table.get_html_rep(columns)
    return html_rep
Exemplo n.º 46
0
 def setUp(self):
     self.table1 = Table('table1', 5, 5)
     self.table2 = Table('table1', 10, 10)
     self.table3 = Table('table1', 50, 50, {'TO_SOUTH': 1, 'TO_NORTH': -1, 'TO_WEST': 1, 'TO_EAST': -1})
     self.table4 = Table('table1', 100, 100, {'TO_SOUTH': 1, 'TO_NORTH': -1, 'TO_WEST': -1, 'TO_EAST': 1})
Exemplo n.º 47
0
def seed_data():
    #restaurants
    shake_key = Restaurant(name="Shake Shack",
                           phone="3234883010",
                           street_address="8520 Santa Monica Blvd",
                           city="West Hollywood",
                           state="CA",
                           zip_code="90069",
                           user="******").put()
    in_key = Restaurant(name="In n Out",
                        phone="8007861000",
                        street_address="13425 Washington Blvd",
                        city="Marina Del Rey",
                        state="CA",
                        zip_code="90292",
                        user="******").put()
    cheese_key = Restaurant(name="Cheescake Factory",
                            phone="3102601296",
                            street_address="395 Santa Monica Place",
                            city="Santa Monica",
                            state="CA",
                            zip_code="90401",
                            user="******").put()
    blaze_key = Restaurant(name="Blaze Pizza",
                           phone="3103400638",
                           street_address="4114 Sepulveda Blvd",
                           city="Culver City",
                           state="CA",
                           zip_code="90230",
                           user="******").put()

    #tables
    shake1_table_key = Table(max="5",
                             table_name="table1",
                             restaurant_id=shake_key,
                             full=False).put()
    shake2_table_key = Table(max="2",
                             table_name="table2",
                             restaurant_id=shake_key,
                             full=False).put()
    shake3_table_key = Table(max="4",
                             table_name="table3",
                             restaurant_id=shake_key,
                             full=False).put()
    shake4_table_key = Table(max="5",
                             table_name="table4",
                             restaurant_id=shake_key,
                             full=False).put()

    in1_table_key = Table(max="5",
                          table_name="table1",
                          restaurant_id=in_key,
                          full=False).put()
    in2_table_key = Table(max="4",
                          table_name="table2",
                          restaurant_id=in_key,
                          full=False).put()
    in3_table_key = Table(max="2",
                          table_name="table3",
                          restaurant_id=in_key,
                          full=False).put()

    cheese1_table_key = Table(max="5",
                              table_name="table1",
                              restaurant_id=cheese_key,
                              full=False).put()
    cheese2_table_key = Table(max="4",
                              table_name="table2",
                              restaurant_id=cheese_key,
                              full=False).put()
    cheese3_table_key = Table(max="2",
                              table_name="table3",
                              restaurant_id=cheese_key,
                              full=False).put()

    blaze1_table_key = Table(max="5",
                             table_name="table1",
                             restaurant_id=blaze_key,
                             full=False).put()
    blaze2_table_key = Table(max="4",
                             table_name="table2",
                             restaurant_id=blaze_key,
                             full=False).put()
    blaze3_table_key = Table(max="2",
                             table_name="table3",
                             restaurant_id=blaze_key,
                             full=False).put()

    #wait
    shake_c1_key = Wait(customer="John Doe",
                        phone="3107176463",
                        party_size="5",
                        restaurant_key=shake_key).put()
    shake_c2_key = Wait(customer="Jane Doe",
                        phone="3107176463",
                        party_size="2",
                        restaurant_key=shake_key).put()
    shake_c3_key = Wait(customer="Bob",
                        phone="3107176463",
                        party_size="4",
                        restaurant_key=shake_key).put()

    in_c1_key = Wait(customer="John Doe",
                     phone="3107176463",
                     party_size="5",
                     restaurant_key=in_key).put()
    in_c2_key = Wait(customer="Jane Doe",
                     phone="3107176463",
                     party_size="2",
                     restaurant_key=in_key).put()
    in_c3_key = Wait(customer="Bob",
                     phone="3107176463",
                     party_size="4",
                     restaurant_key=in_key).put()

    cheese_c1_key = Wait(customer="John Doe",
                         phone="3107176463",
                         party_size="5",
                         restaurant_key=blaze_key).put()
    cheese_c2_key = Wait(customer="Jane Doe",
                         phone="3107176463",
                         party_size="2",
                         restaurant_key=blaze_key).put()
    cheese_c3_key = Wait(customer="Bob",
                         phone="3107176463",
                         party_size="4",
                         restaurant_key=blaze_key).put()

    blaze_c1_key = Wait(customer="John Doe",
                        phone="3107176463",
                        party_size="5",
                        restaurant_key=blaze_key).put()
    blaze_c2_key = Wait(customer="Jane Doe",
                        phone="3107176463",
                        party_size="2",
                        restaurant_key=blaze_key).put()
    blaze_c3_key = Wait(customer="Bob",
                        phone="3107176463",
                        party_size="4",
                        restaurant_key=blaze_key).put()
Exemplo n.º 48
0
import sys
import smtplib
import logging
from time import sleep
from daemon_email import Daemon
from models import Table

# initialize db_name "email" and collection "email"
db = Table("email", "email")

logging.basicConfig(level=logging.DEBUG,
                    filename="test.log",
                    format="%(message)s")


def sendmail(array):
    """function for read data in db and send mail
    """
    username = '******'
    FROM = username
    TO = [array["to"]]
    SUBJECT = array["subject"]
    # check on correct data in optional
    if type(array["optional"]) == str and array["optional"]:
        TEXT = array["optional"]
    else:
        return "Error: missed argument"
    # make template
    message = """From: %s\nTo: %s\nSubject: %s\n\n%s""" % (FROM, ", ".join(TO),
                                                           SUBJECT, TEXT)
    try:
Exemplo n.º 49
0
def read_sales_by_genre():
    this_table = Table(connection, q.query_sales_by_movie)
    columns = ['Category', 'Total Sales']
    html_rep = this_table.get_html_rep(columns)
    return html_rep
def build_database():
    db.create_all()
    contraindications = []

    for vacc in vaccines_:
        for cont in vacc['contraindications']:
            contraindications.append(Contraindication(cont))
        vaccine = Vaccines(vacc['title'], 1, contraindications,
                           vacc['by_health'], vacc['periodicity'])
        vac_dict[vacc['title']] = vaccine
        contraindications = []
        db.session.add(vaccine)
    db.session.commit()

    data1 = Data(2, [
        vac_dict['Гепатит В'], vac_dict['АКДП'], vac_dict['Поліомієліт'],
        vac_dict['Хіб-інфекція']
    ])
    db.session.add(data1)
    data2 = Data(
        4,
        [vac_dict['АКДП'], vac_dict['Поліомієліт'], vac_dict['Хіб-інфекція']])
    db.session.add(data2)
    data3 = Data(
        6, [vac_dict['Гепатит В'], vac_dict['АКДП'], vac_dict['Поліомієліт']])
    db.session.add(data3)
    data4 = Data(12, [vac_dict['Хіб-інфекція'], vac_dict['КПК']])
    db.session.add(data4)
    data5 = Data(18, [vac_dict['АКДП'], vac_dict['Поліомієліт']])
    db.session.add(data5)
    data6 = Data(72,
                 [vac_dict['АДП'], vac_dict['Поліомієліт'], vac_dict['КПК']])
    db.session.add(data6)
    data7 = Data(168, [vac_dict['Поліомієліт']])
    db.session.add(data7)
    data8 = Data(192, [vac_dict['АДП']])
    db.session.add(data8)

    data9 = Data(6, [vac_dict['Грип']])
    db.session.add(data9)
    data10 = Data(0, [vac_dict['Пневмококова інфекція']])
    db.session.add(data10)
    data11 = Data(0, [vac_dict['Хіб-інфекції']])
    db.session.add(data11)
    data12 = Data(24, [vac_dict['Менінгококова інфекція']])
    db.session.add(data12)
    data13 = Data(12, [vac_dict['Гепатит А']])
    db.session.add(data13)

    table = Table("calendar of vaccination", [
        data1, data2, data3, data4, data5, data6, data7, data8, data9, data10,
        data11, data12, data13
    ])
    db.session.add(table)

    table.data = [
        data1, data2, data3, data4, data5, data6, data7, data8, data9, data10,
        data11, data12, data13
    ]

    db.session.commit()
    print()
    print()
    for data_item in Data.query.all():
        print(data_item.age_in_months, end=" = ")
        for vacine in data_item.vaccines:
            print(vacine.name, ":", vacine.dose, " by health: ",
                  vacine.by_health)
            for contraindication in vacine.contraindications:
                print(" [", contraindication.title, end="] ")

            print()
        print()
        print()