Check A-Record Status using Boto Route53 after creation - boto

i looking for a method to get the status of a record (A-NAME) just created with route53. This is the code:
changes = ResourceRecordSets(conn, "ZONEID")
change = changes.add_change("STRING FOR ADD NEW SUBDOMAIN")
change.add_value(MY_IP)
action = changes.commit()
j=json.loads(json.dumps(action))
status = j['ChangeResourceRecordSetsResponse']['ChangeInfo']['Status']
while status == 'PENDING':
time.sleep(5)
action.update() #THIS ACTION RETURN "NONE" and not update the previous state
Obviously if print the status variable it result always "PENDING"
Can anyone help me? Thanks in advance.

I went through the same problem and this is how I have solved.
Assuming that you have the ID of the A Record and it's C2T9LA0WQGXVUX in the us-west-1 region, then we have:
import boto.route53
record_id = 'C2T9LA0WQGXVUX'
REGION = 'us-west-1'
AWS_S3_ACCESS_KEY_ID = 'my aws key'
AWS_S3_SECRET_ACCESS_KEY = 'my secret key'
connection = boto.route53.connect_to_region(REGION,
aws_access_key_id=AWS_S3_ACCESS_KEY_ID,
aws_secret_access_key=AWS_S3_SECRET_ACCESS_KEY
)
record_status = connection.get_change(change_id=record_id)
The response will be something like:
{u'GetChangeResponse': {u'ChangeInfo': {u'Status': u'INSYNC', u'SubmittedAt': u'2017-07-10T13:05:29.350Z', u'Id': u'/change/C2T9LA0WQGXVUX'}}}
So, you can get the status with:
print record_status['GetChangeResponse']['ChangeInfo']['Status']

Related

How to have my template "load" for a second or two before refreshing after a POST

I'm having an issue where I have a MariaDB event combined with my Django Model. For context, here is my model code:
class PartGroup(models.Model):
GroupID = models.AutoField(primary_key=True, unique=True)
Label = models.CharField(max_length=40, blank=True)
SiteID = models.ForeignKey('Site', on_delete=models.CASCADE, null=True)
InspectionPeriod = models.IntegerField(blank=False, null=True)
LastInspected = models.DateField(blank=True, null=True)
InspectionDue = models.CharField(max_length=255, blank=True)
ConnectedTo = models.ManyToManyField('self', blank=True, null=True)
The fields I want to highlight here are InspectionPeriod, LastInspected, and InspectionDue. I have another model which adds Inspections related to the GroupID. This contains a date of the inspection:
class GroupInspection(models.Model):
InspectionID = models.AutoField(primary_key=True, unique=True)
GroupID = models.ForeignKey('PartGroup', on_delete=models.CASCADE, null=True, unique=True)
class GroupReport(models.Model):
ReportID = models.AutoField(primary_key=True, unique=True)
InspectionID = models.ForeignKey('GroupInspection', on_delete=models.CASCADE, null=True)
Date = models.DateField(auto_now=False, auto_now_add=False, null=True)
Comment = models.CharField(max_length=255, blank=True)
Signature = models.CharField(max_length=255, blank=True)
I have a MariaDB event to update the LastInspected field, and from there some code in my view checks that date against the inspection period to see if an inspection is due.
Here's where the problem occurs
I have to have my MariaDB Event updating every 1 second in order to make this work reasonably well. I'm not sure if that's absolutely horrendous performance wise or not, if anyone has another solution that works smoother that's welcome. But that's not the real issue. When I create an inspection, this redirects immediately to my Group template page. This takes less than a second to redirect, which leaves my users confused as they just created an inspection and it doesn't show on the redirect yet unless they immediately refresh after 1 second.
How can I get around this?
EDIT 1
I forgot to mention - the way this works at template level is that I have a page which shows a table view of all my groups and their attributes. I then have a few buttons that create an inspection depending on which button is pressed. This just redirects back to the same page which is why the one second thing is an issue as the redirect usually takes less than a second.
EDIT 2 Here's my view:
def groupList(request, site):
status = "default"
if request.method == "POST":
list = GroupInspection.objects.filter(GroupID = request.POST.get("group"))
if not list.exists():
insp = GroupInspection.create(PartGroup.objects.get(GroupID = request.POST.get("group")))
insp.save()
if 'pass' in request.POST:
groupReport = GroupReport.create(GroupInspection.objects.get(GroupID = request.POST.get("group")), date.today(), "Pass", request.user.username)
groupReport.save()
if 'fail' in request.POST:
groupReport = GroupReport.create(GroupInspection.objects.get(GroupID = request.POST.get("group")), date.today(), "Fail", request.user.username)
groupReport.save()
if 'checkSubmit' in request.POST:
groupReport = GroupReport.create(GroupInspection.objects.get(GroupID = request.POST.get("group")), date.today(), request.POST.get("comments"), request.user.username)
groupReport.save()
status = "changed"
siteselected = Site.objects.get(SiteID = site)
groupList = PartGroup.objects.filter(SiteID = siteselected)
warnings = 0
expired = 0
good = 0
for group in groupList:
if group.LastInspected == None:
group.InspectionDue = "Yes"
expired = expired + 1
else:
Deadline = group.LastInspected + timedelta(days=group.InspectionPeriod)
if datetime.now().date() > Deadline:
group.InspectionDue = "Yes"
expired = expired + 1
elif datetime.now().date() > (Deadline - timedelta(days=30)):
group.InspectionDue = "<30 Days"
warnings = warnings + 1
else:
group.InspectionDue = "No"
good = good + 1
group.save()
context = {
'status': status,
'SiteNo': siteselected.SiteID,
'SiteName':siteselected.SiteName,
'groupList': groupList,
'expired': expired,
'warnings': warnings,
'good': good,
}
template = loader.get_template('moorings/groupList.html')
return HttpResponse(template.render(context, request))
EDIT 3 Here's my SQL Event
CREATE EVENT updateLastInspected
ON SCHEDULE EVERY 1 SECOND
DO
UPDATE proj_partgroup g INNER JOIN ( SELECT i.GroupID_id, max(r.Date) Date FROM proj_groupinspection i INNER JOIN proj_groupreport r ON r.InspectionID_id = i.InspectionID GROUP BY i.GroupID_id ) t ON g.GroupID = t.GroupID_id SET g.LastInspected = t.Date;
You can replace your SQL Event with Django signal that runs after any GroupReport update, and in case it was new report created - updates corresponding PartGroup last updated date.
proj/signals.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.apps import apps
GroupReport = apps.get_model("proj", "GroupReport")
PartGroup = apps.get_model("proj", "PartGroup")
#receiver(post_save, sender=GroupReport)
def update_partgroup_lastinspection(sender, instance, created, **kwargs):
if created:
# cause FKs can be null - may need to add
# null checks or try / except
pg = instance.InspectionID.GroupID
if instance.Date > pg.LastInspected:
pg.LastInspected = instance.Date
pg.save(update_fields=['Date'])
# another option to perform same update
PartGroup.objects.filter(
LastInspected__lt=instance.Date,
group_inspection__group_report=instance
).update(
LastInspected=instance.Date
)
proj/apps.py
...
class ProjConfig(AppConfig):
name = "proj"
...
def ready(self):
import proj.signals
You can skip checking that value is greater and just update right away.
Or add logic in model's save() method instead (which generally is more preferred than signals).
Previous answer - is not the case here, groupList contains changes to instances.
You are returning groupList which contains old results.
The reason for this is that while being iterated over (for group in groupList) QuerySets are evaluated with the result being cached in this QuerySet instance and when later it is used in context - this evaluated result is passed, although instances were updated in the database. QuerySets need to be run and be evaluated again to fetch fresh results.
One simple solution to reuse the QuerySet and evaluate it again - is append .all() to previous QuerySet - this will make a copy of provided QuerySet and since it is new one - it is not yet evaluated.
context = {
...
'groupList': groupList.all(),
...
}

saving an instance of a model with auto_now_add in Django returns error message Column 'xxx' cannot be null

I must be doing something very wrong or this error doesn't make any sense to me. I have an object Location:
class Location(models.Model):
class Meta:
db_table = 'location'
location_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=200)
state = models.CharField(max_length=200)
country = models.CharField(max_length=200)
apt_number = models.CharField(max_length=200, null=True, blank=True)
street_address = models.CharField(max_length=200)
city = models.CharField(max_length=200)
zip_code = models.IntegerField()
created = DateTimeField(auto_now_add=True)
here this is my code for inserting a new or updating an existing location record:
class LocationList(generics.ListCreateAPIView):
queryset = Location.objects.all()
serializer_class = LocationSerializer
def post(self, request, *args, **kwargs):
location_dict = request.data
if 'location_id' not in location_dict:
okStatus = status.HTTP_201_CREATED
else:
okStatus = status.HTTP_200_OK
location = Location(**location_dict)
location.save()
return Response(LocationSerializer(location).data, status=okStatus)
Inserts work fine, but everytime an update happens, I get the error "Column 'created' cannot be null". My online research seems to point me to the fact that this was a bug which has been long fixed. I expect the update to pass since the 'created' field was set to auto_now_add, which means Django should set that field once upon insert and leave it on any subsequent update. I do not know why Django is trying to set that column to null or any other value on update, because I expect Django to not update the column at all. I am using MySQL as database.
I think that your problem is in the " created column " try this steps :-
1) add null=True inside the created column
2) run :$ python"select version" manage.py makemigrations "appName or keep it empty"
3) run :$ python"V" manage.py sqlmegrate "aapName" " file version" >
check the file version in the app directory type it like this "0001"
4) run :$ python"V" manage.py migrate "appName"
after these steps ur db should be updated, last step is to remove (null=True from created column ) and start project.

How is slug being created in Sylius?

I want to create new product in Sylius. I just tested:
$user = $this->getUser();
$repository = $this->container->get('sylius.repository.product');
$manager = $this->container->get('sylius.manager.product'); // Alias for appropriate doctrine manager service.
$product = $repository->createNew();
$product
->setName('Test product')
->setDescription('Des Product 2')
->setPrice(90)
->setUser($user)
;
$manager->persist($product);
$manager->flush(); // Save changes in database.
But it trigger an exception of slug. When I try $product->getSlug(), that returns empty. I don't know how does slug created in Sylius and where is the code for that?
It's a gedmo:slug, check ProductBundle\Resources\config\doctrine\model\ProductTranslation.orm.xml
Make sure you have a default locale configured and add this to your code:
$product->setCurrentLocale($locale);
$product->setFallbackLocale($locale);
Products are translatable, and I think this is what you're missing.
Check how a product is created in Sylius\Bundle\FixturesBundle\DataFixtures\ORM\LoadProductsData line 404.

Flask-SQLAlchemy won't update or delete a row

I want to either update a row in the database, if it exists, or create it if it doesn't.
I have a class that first sets the instance variable user:
self.user = models.User.query.filter_by(entity=self.entityUrl).first()
# can be None if not found
Then, later on in another class method I do this:
if self.user is not None:
self.user.foo = bar # etc. Change the attributes of self.user
else:
self.user = models.User(bar, ... ) # create a new model
db.session.add(self.user)
db.session.commit()
Problem is, the corresponding row in the database doesn't get updated. I've also tried this approach:
if self.user is not None:
self.user.foo = bar
else:
self.user = models.User(bar, ... )
db.session.add(self.user) # add it to the session either way
db.session.commit()
Here, the db.session.add() call fails with sqlalchemy.exc.InvalidRequestError: Object '<User at 0x7f4918172890>' is already attached to session '1' (this is '2')
And the first thing I tried was to delete the existing model in all cases, then create a new one, i.e.:
if self.user is not None:
db.session.delete(self.user)
self.user = models.User(bar, ... )
db.session.add(self.user)
db.session.commit()
In this case the db.session.delete() call fails with the same already attached to session '1' message as above.
Why is the object attached to a different session and not the same one? How do I do this correctly?
Make sure the foo attribute in your class existes. Next, maybe there is something wrong in the way you use it. Because I see you use "self.user....". Try the simplest thing first. Then step by step.
The following code is wrong:
if self.user is not None:
self.user.foo = bar
else:
self.user = models.User(bar, ... )
db.session.add(self.user) # add it to the session either way
db.session.commit()
NO need to db.session.add, if you want to update the record.
To update existing record using Flask-SQLAlchemy, you do not need to re-create the entire User object and add it to the session. You just update the specific field (e.g. foo) and thats it. You can then do the db commit.
You can do your exact requirement as below:
Step 1: query the existing user object
user = models.User.query.filter_by(entity=self.entityUrl).first()
Step 2:
if user is not None:
user.foo = bar
else:
user = User(...)
db.session.add(user)
Step 3: commit the db session.
db.session.commit()

Django IntegrityError Duplicate entry on Foreignkey

I am having a subtle error with a duplicate key integrity error on django with a set of foreignkey relations.
I have the following function:
def update_relationship(actor, action, status, target):
existing = Relation.objects.filter(actor=actor, target=target)
# If this relation is 'on', turn it off
if Relation.objects.filter(actor=actor, target=target, status=status):
Relation.objects.filter(actor=actor, target=target).update(status="")
# If this relationship is not on, turn it on
else:
created = True
if existing:
existing.update(status=status)
else:
Relation.objects.create(actor=actor, target=target, status=status)
As you can see, I am testing to see if the relationship exists already in the database and then updating it if it does exist and creating a new row if it does not. However, it seems under some conditions that I can't reproduce, Django is giving me a duplicate key error, even for conditions where, as far as I can tell, there is only one instance of that.
For reference, here is the the model definition:
class Relation(models.Model):
Status = Choices(('L', 'Like', 'Like'),
('D', 'Dislike', 'Dislike'),
('S', 'Save', 'Save'))
actor = models.ForeignKey('members.Member', related_name='relations')
target = models.ForeignKey('members.Member', related_name='reverse_relations')
status = models.CharField(choices=Status, max_length=10)
created = models.DateTimeField('created', auto_now_add=True)
notified = models.BooleanField(default=False)
notified_mutual = models.BooleanField(default=False)
class Meta:
unique_together = (('actor', 'target'),)
ordering = ('created',)
verbose_name = 'Relation'
verbose_name_plural = 'Relations'
First of all, right expression to check for existence is:
existing = Relation.objects.filter(actor=actor, target=target).exists()
But the djano way to write your sentences is with get_or_create method, is that method that you are looking for:
Relation.objects.get_or_create(actor=actor, target=target,
defaults={ 'status':status }
)
Or, for your case, something like:
r, _ = Relation.objects.get_or_create(actor=actor, target=target )
r.status = '' if r.status == 'on' else status
r.save()