using reservation identification number in python script - boto

When I initiate a new instance using boto, I get the reservation ID. But how do I use that reservation ID in the python script?
myreservation = conn.run_instances('ami-999c9999', placement='us-east-1a', key_name='nov15_key',instance_type='m1.xlarge',security_groups=['NuoDB-1-0-1-AutogenByAWSMP-'])
The next line does not work as expected:
myinstanceid = conn.get_all_instances(filters={'reservation-id':myreservation})[0].instances[0]
If I add the reservation ID in the code, it will work without any problem.
myinstanceid = conn.get_all_instances(filters={'reservation-id':'r-1e654a79'})[0].instances[0]
I will like to know what is the type of the reservation id and how to use it.

From the docs, run_instances returns this:
Returns:
The boto.ec2.instance.Reservation associated with the request for machines
Reservation has, also according to the docs, an instances slot which contains a list of boto.ec2.instance.Instance objects. It also has an "id" slot.
If you need the reservation id:
myreservation.id
And if you want the instance id:
myreservation.instances[0].id
So the Reservation object already has all the info you are looking for, no need to do a followup lookup call. But if you need to, you may want to try this:
myinstance = conn.get_all_instances(filters={'reservation-id':myreservation.id})[0]
Or better yet, this:
myinstanceid = conn.get_all_instances(filters={'reservation-id':myreservation.id})[0].id

Related

In testrail API how do I get project_id from case data?

I am trying to add a run with the add_run endpoint, but in my automation code I only have the test cases ids but not the project id (which according the the docs is mandatory).
Right now I am doing:
get all projects with /get_projects
get all cases /get_cases/{project_id}
Then I loop over the cases I get and add the project_id to the case so I could create an add_run with the proper project_id.
This seems like the wrong way to do it.
Anybody has a better solution?
Also is there a way to create a run without a project_id? for example if I have a sanity run that includes cases from many projects.
Any help is appreciated.
You can do the following to get the parent project ID:
get the case by ID and capture value of the suite_id field
get the parent suite by the value of the suite_id field and capture value of the project_id field <--- here you have your project ID and can use it for creating runs.

How to get records with last dates in Django ORM(MySQL)?

I have models:
class Reference(models.Model):
name = models.CharField(max_length=50)
class Search(models.Model):
reference = models.ForeignKey(Reference)
update_time = models.DateTimeField(auto_now_add=True)
I have an instance of Reference and i need to get all last searches for the reference. Now i am doing it in this way:
record = Search.objects.filter(reference=reference)\
.aggregate(max_date=Max('update_time'))
if record:
update_time = record['max_date']
searches = reference.search_set.filter(update_time=self.update_time)
It is not a big deal to use 2 queries except the one but what if i need to get last searches for each reference on a page? I would have got 2x(count of references) queries and it would not be good.
I was trying to use this solution https://stackoverflow.com/a/9838438/293962 but it didn't work with filter by reference
You probably want to use the latest method.
From the docs, "Returns the latest object in the table, by date, using the field_name provided as the date field."
https://docs.djangoproject.com/en/1.8/ref/models/querysets/#latest
so your query would be
Search.objects.filter(reference=reference).latest('update_time')
I implemented a snippet from someone in gist but I don't remember the user neither have the link.
A bit of context:
I have a model named Medicion that contains the register of mensuration of a machine, machines are created in a model instance of Equipo, Medicion instances have besides of a Foreign key to Equipo, a foreign key to Odometro, this model serves as a kind of clock or metre, that's why when I want to retrieve data (measurements aka instances of Medicion model) for a certain machine, I need to indicate the clock as well, otherwise it would retrieve me a lot of messy and unreadable data.
Here is my implementation:
First I retrieve the last dates:
ult_fechas_reg = Medicion.objects.values('odometro').annotate(max_fecha=Max('fecha')).order_by()
Then I instance an Q object:
mega_statement = Q() # This works as 'AND' Sql Statement
Then looping in every date retrieved in the queryset(annotation) and establishing the Q statement:
for r in ult_fechas_reg:
mega_statement |= (Q(odometro__exact=r['odometro']) & Q(fecha=r['max_fecha']))
Finally passed this mega statement to the queryset that pursues to retrieve the last record of a model filtered by two fields:
resultados = Medicion.objects.filter(mega_query).filter(
equipo=equipo,
odometro__in=lista_odometros).order_by('odometro', 'fecha') # lista_odometros is a python list containing pks of another model, don't worry about it.

magento table "sales_flat_order" field "protect_code" explanation

We are working on magento database and tables. Magento seems to write a code in table sales_flat_order field protect_code to define if there is a invoice or a shipment done already. It would look something like
01b335 or
a0a243
But there is no key to understand what this protection code means. Is there an explanation of the meaning of these codes and how they are generated?
Where is it generated?
If you look in app/code/core/Mage/Sales/Model/Order.php on around line 2052, you will find the following:
$this->setData('protect_code', substr(md5(uniqid(mt_rand(), true) . ':' . microtime(true)), 5, 6));
This is where protect_code is generated for the order (using a combination of md5, uniqid, and random integer.
What is it used for?
If you look in app/code/core/Mage/Sales/Helper/Guest.php and find the loadValidOrder function. You will see protect_code used in some areas to ensure the order being loaded is the correct one for the guest's cookie value.
It's also used in other areas, such as tracking information comparisons. You can see several instances of the getProtectCode() method being called in the Shipment models to compare the order to the tracking information. An example of a function that uses it is:
public function getTrackingInfoByTrackId()
{
$track = Mage::getModel('sales/order_shipment_track')->load($this->getTrackId());
if ($track->getId() && $this->getProtectCode() == $track->getProtectCode()) {
$this->_trackingInfo = array(array($track->getNumberDetail()));
}
return $this->_trackingInfo;
}
As you can see with $this->getProtectCode() == $track->getProtectCode(), the tracking protect_code must match the Shipment protect_code.

Rails find_by with OR

I have a named scope set up in my rails application that is used to locate a record either by its ID (directly from the index view) or a UUID (from an email - basically only so that users can't enter in any ID and view a record)
scope :by_uuid, lambda { |id| where('id = ? OR uuid = ?', id, id) }
This is used in the show action, so the ID comes from the url, like
services/114
services/74c083c0-8c29-012f-1c87-005056b42f8a
This works great, until you get a UUID such as 74c083c0-8c29-012f-1c87-005056b42f8a
This, rails unfortunately converts to the int value and we get services/74 AS WELL AS the record with the correct UUID
Adding a .first to the scope will not help because the order could be different for each record, so that does not work.
Is there a way to prevent rails from converting the ID like this and taking the string literally? Obviously, there will not be a record with an ID that matches that, but if it goes willy-nilly with the integer values of the string passed to it, we could get anything back.
Using the dynamic finders, such as
Service.find_by_uuid
or
Service.find_by_id
work as intended, however we need to be able to retrieve a record using the UUID OR the ID in the same method (show).
Is there a way to do something like
Service.find_by_id_or_uuid
We fixed this issue with the following change to the scope:
scope :by_uuid, lambda { |id| where('binary id = ? OR uuid = ?', id, id) }
This ensures that the id string is taken by its binary value instead of being converted into an int. However, this will ONLY WORK WITH MYSQL BASED APPS

Confusion with Entity Framework context

I'm a bit confused in regards to how EF's dbContext works.
If I do something like _context.Persons.Add(_person) (assuming person is a valid entity), if I then (before calling _context.SaveChanges()) query Persons, will the person I just added be included in the results?
For example:
Person _person = new Person() {Firstname = "Bill", Lastname = "Snerdly"};
_context.Persons.Add(_person);
var _personList = _context.Persons.Where(p => p.Lastname.StartsWith("Sne"));
Whenever I try this, it seems as though the context loses track of the fact that I've added this new person to the context.
What confuses me is that if I edit an existing person and attach the person and set the state to modified, querying the context seems to keep track of the changes that were made and returns them in the results. For example:
//Assuming that Person 5 exists with the name William Snerdly
Person _person = new Person() {Id = 5, Firstname = "Bill", Lastname = "Snerdly"};
_context.Persons.Attach(_person);
_context.Entry(_person).State = System.Data.EntityState.Modified;
var _personList = _context.Persons.Where(p => p.Lastname.StartsWith("Sne"));
In this case, it seems like the person with the id of 5 will show up in the list with the name Bill instead of William. IOW, the context queried the data but retained the changes while in the first scenario, the context queried the data but ignored any added items. It just seems a bit inconsistant.
Am I understanding this correctly or am I missing something?
Thanks for your help with this.
No, as it does not yet exist in the database. It will, however, be accessible through the ObjectStateManager of the ObjectContext, or alternatively, if you're using the DbContext/DbSet wrappers, through the .Local property of the DbSet.
In the case of the edit, you're seeing the ORM's first level cache at work. The query is executed against the database (and so compares against the values in there - your example would get even weirder if you modified the Lastname in the context, but still get the result from the query looking for the unmodified Lastname), but when its results are processed, first the ID of the returned entity is checked, and since the entity with that ID is already present in the context, you get that instance back. This is the default "AppendOnly" mode of operation.
I don't know what you want to do, but I had to understand all that when I wanted to validate my changes according to rules that needed to use the values of both loaded and unread entities. I ended up starting a transaction, saving the changes with the "None" options, doing my validation queries againt the database (which then contained the "merged" view of the data), and the rolling back the transaction if the data was invalid, or accepting the changes and committing the transaction otherwise.