PubsubMessage publish_time gets saved as DatetimeWithNanoseconds - python

I'm trying to instantiate the following PubsubMessage:
timestamp = Timestamp()
timestamp.GetCurrentTime()
message = pubsub_v1.types.PubsubMessage(
data=b'{"id": 123}',
attributes={"some_attribute": "abcd"},
message_id="1",
publish_time=timestamp,
)
When I inspect the timestamp variable, it is of type Timestamp with seconds and nanos attributes, just as expected. However when I inspect message.publish_time I get a DatetimeWithNanoseconds object instead which does not have the aforementioned attributes so I get an error later in my code (because of this line in google-pubsub)
I've checked google's docs but I can't seem to find anything like this. Any help is appreciated.

Ok, so it seems that when passing a PubsubMessage instance to the constructor of the Message class, you can actually do the following:
message=message._pb
I noticed this in this line of the google-pubsub repo
By passing the message as its ._pb attribute you don't get an exception when trying to access message.publish_time.seconds or message.publish_time.seconds. I'm not sure why this is the case but it solved my problem. I'll add an update if I find more info on this.

Related

Type error when accessing Django request.POST

I'm attempting to build an XML document out of request.POST data in a Django app:
ElementTree.Element("occasion", text=request.POST["occasion"])
PyCharm is giving me an error on the text parameter saying Expected type 'str', got 'Type[QueryDict]' instead. I only bring up PyCharm because I know its type checker can be overzealous sometimes. However, I haven't been able to find anything about this issue specifically.
Am I doing something wrong? Or should I try to silence this error?
Assuming you're not posting anything unusual, like json, request.POST['occasion'] should return a string, either the field 'occasion' or the last value of the list submitted with that name (or an error, if empty. Use request.POST.get('occasion') to avoid).
There are apparently some httprequest related issues with pycharm, but the way to doublecheck if this is happening here would be to print out and/or type check request.POST['occasion'] prior to that line to make sure of what it returns, eg:
occasion = request.POST['occasion']
print(type(occasion), occasion)
ElementTree.Element("occasion", text=occasion)
In the last line, using a variable assigned ahead of time might be a simple way to remove the pycharm error without turning off warnings, depending on your tolerance for extra code.

jira-python getting custom field's value from an issue-link

I'm trying to get the value of an issue link's custom field.
I know how to do it in a regular sub-task, but with issue-link, I can't get it.
This is how I get a custom field's value in a Sub Task:
getattr(issue.fields, name_map[fields[0]])
And when I try it with issue link, like this:
getattr(**issue_link**.fields, name_map[fields[0]])
I get: AttributeError: type object 'PropertyHolder' has no attribute 'customfield_18697'
What's interesting, I can update the custom field's value, like this:
issue_link.update(fields={name_map["Field1"]:"ABC"})
Why can I update but not get the value?
Thanks in advance
Found the answer in https://community.atlassian.com/t5/Jira-questions/Get-custom-fields-from-linked-issues-with-Jira-API/qaq-p/1148453
Needs to be done with a rest call, and not through the API

Python Library Reference/Usage

I'm trying to use a method from the BioPython package to calculate an isoelectric point for a list of given peptides. The class breakdown can be seen here:
http://biopython.org/DIST/docs/api/Bio.SeqUtils.ProtParam.ProteinAnalysis-class.html#isoelectric_point
In order to import this class to my environment, I'm using the following code (did I do this right?):
from Bio.SeqUtils.ProtParam import ProteinAnalysis
Then, to call the method, I do the following:
window_aas = "ditkdteneveadveveadveveadvseql";
ProteinAnalysis.isoelectric_point(window_aas);
However I'm getting the following error, and I'm not sure how to interpret it, despite several searches for similar errors:
File
"C:\Users\----\AppData\Local\Programs\Python\Python36-32\lib\site-packages\Bio\SeqUtils\ProtParam.py",
line 68, in count_amino_acids
if self.amino_acids_content is None: AttributeError: 'str' object has no attribute 'amino_acids_content'
Is anyone able to guide me in the right direction here? This other class is also called IsoElectricpoint but I don't see a method in it to use:
http://biopython.org/DIST/docs/api/Bio.SeqUtils.IsoelectricPoint-module.html
ProteinAnalysis is a class. What you're doing in your code is trying to call a method in that class directly. In Python, the first argument to such a function is the class object, but you're passing in a string (window_aas). The correct way to use this api is first create a class object:
protein_analysis = ProteinAnalysis(window_aas)
and then you can call
protein_analysis.isoelectric_point()
You can read up more on how this all works in the online docs.
It looks like isoelectric_point is an instance method, so you need to create an instance first:
analysis = ProteinAnalysis(window_aas)
analysis.isoelectric_point()

How can I specify a default time for a ndb.TimeProperty()?

I find myself stuck on this problem, and repeated Googling, checking SO, and reading numerous docs has not helped me get the right answer, so I hope this isn't a bad question.
One entity I want to create is an event taking place during a convention. I'm giving it the property start_time = ndb.TimeProperty(). I also have a property date = messages.DateProperty(), and I'd like to keep the two discrete (in other words, not using DateTimeProperty).
When a user enters information to create an event, I want to specify defaults for any fields they do not enter at creation and I'd like to set the default time as midnight, but I can't seem to format it correctly so the service accepts it (constant 503 Service Unavailable response when I try it using the API explorer).
Right now I've set things up like this (some unnecessary details removed):
event_defaults = {...
...
"start_time": 0000,
...
}
and then I try looping over my default values to enter them into a dictionary which I'll use to .put() the info on the server.
data = {field.name: getattr(request, field.name) for field in request.all_fields()
for default in event_defaults:
if data[default] in (None, []):
data[default] = event_defaults[default]
setattr(request, default, event_defaults[default])
In the logs, I see the error Encountered unexpected error from ProtoRPC method implementation: BadValueError (Expected time, got 0). I have also tried using the time and datetime modules, but I must be using them incorrectly, because I still receive errors.
I suppose I could work around this problem by using ndb.StringProperty() instead, and just deal with strings, but then I'd feel like I would be missing out on a chance to learn more about how GAE and NDB work (all of this is for a project on udacity.com, so learning is certainly the point).
So, how can I structure my default time properly for midnight? Sorry for the wall of text.
Link to code on github. The conference.py file contains the code I'm having the trouble with, and models.py contains my definitions for the entities I'm working with.
Update: I'm a dummy. I had my model class using a TimeProperty() and the corresponding message class using a StringField(), but I was never making the proper conversion between expected types. That's why I could never seem to give it the right thing, but it expected two different things at different points in the code. Issue resolved.
TimeProperty expects a datetime.time value
import datetime
event_defaults = {...
...
"start_time": datetime.time(),
...
}
More in the docs: https://cloud.google.com/appengine/docs/python/ndb/entity-property-reference#Date_and_Time
Use the datetime() library to convert it into a valid ndb time property value
if data['time']:
data['time'] = datetime.strptime(data['time'][:10], "%H:%M").time()
else:
data['time'] = datetime.datetime.now().time()
ps: Don't forget to change data['time'] with your field name

When does .save() create an object?

I have the code:
name = MakesiteNameForm(datdict)
if name.is_valid:
name.save()
datsite = Makesite.objects.get(sitename=request.POST['sitename'])
datsite.ref_id.add(RefID.objects.create(url=request.POST['url'],description=request.POST['description']))
datsite.save()
So i have this bit of code what I want to use to create and save some manytomany items but when I try using this method is says that Makesite matching query does not exist. which i think means it hasn't saved but then later I call site = Makesite.objects.all() and I can clearly see the value of what request.POST['sitename'] is sitting inside the querydict. So is there anyway to query this better? or is there something about the save() i missing?
Edit: that form saves a value sitename values into the Makesite table
The save() call doesn't create objects, it just saves the object to the database, inserting a new row in case it's a new object, or updating it.
First, form.is_valid() is a method, but you're not calling it, so you're always trying to save name. That may or may not be related to your error, but it's wrong anyway, and maybe that's where the query error is coming from, not the get() call below. Fix it and see what happens.

Categories

Resources