I am using QuickFix with Python. On the back of this question, I've explored the SessionID class a bit, but I am mystified by the behavior.
The SessionID class is described here. It is formed of a BeginString, SenderCompID and TargetCompID.
Say my SessionID in string form looks like this: FIX.4.2:LMXTS->TS68.
fix.SessionID().fromString() returns :->
Which if you look, are the three filler characters separating the BeginString, SenderCompID and TargetCompID.
fix.SessionID().getBeginString returns 8=☺ (i.e. the BeginString is nowhere). And the same thing applies to getSenderCompID and getTargetCompID, they return 49=☺ and 56=☺ respectively.
fix.SessionID().getTargetCompID().getValue() returns the empty string ''.
Trying another way, fix.SessionID().fromString('FIX.4.2:LMXTS->TS68') returns None.
I am trying to get these values after the session is created (which I can explicitly see happening when I pass fix.ScreenLogFactory(settings) to the initiator. So I am confused.
The method void onLogon( const SessionID& ) {} in Application.h is fired when the session is logged on, and gives you a reference to a SessionID. You could inspect the SessionID object inside onLogon to see how it behaves.
you can do it any of the quickfix methods after your session is created as the sesionId is one of the parameters.
The first method fired is onCreate so you can potentially store the sesionId in your class var and then reuse if if and when required to retrieve your settings. You can also use the onLogon method as suggested in one of the other answers.
Example below
def onCreate(self, sessionID):
self.session_id = sessionID
target = sessionID.getTargetCompID().getString()
sender = sessionID.getSenderCompID().getString()
It sounds like you're looking at the session directly after creating it, before logging on etc. So that means you're not using a breakpoint in, say, FromApp or ToApp to look at the session properties there. If you do, you get the properties directly i.e. SenderCompID, or TargetCompID.
I cannot find the method SessionID in the objects I use. How do you define your 'fix' object?
Related
I am trying to write a testing program for a python program that takes data, does calculations on it, then puts the output in a class instance object. This object contains several other objects, each with their own attributes. I'm trying to access all the attributes and sub-attributes dynamically with a one size fits all solution, corresponding to elements in a dictionary I wrote to cycle through and get all those attributes for printing onto a test output file.
Edit: this may not be clear from the above but I have a list of the attributes I want, so using something to actually get those attributes is not a problem, although I'm aware python has methods that accomplish this. What I need to do is to be able to get all of those attributes with the same function call, regardless of whether they are top level object attributes or attributes of object attributes.
Python is having some trouble with this - first I tried doing something like this:
for string in attr_dictionary:
...
outputFile.print(outputclass.string)
...
But Python did not like this, and returned an AttributeError
After checking SE, I learned that this is a supposed solution:
for string in attr_dictionary:
...
outputFile.print(getattr(outputclass, string))
...
The only problem is - I want to dynamically access the attributes of objects that are attributes of outputclass. So ideally it would be something like outputclass.objectAttribute.attribute, but this does not work in python. When I use getattr(outputclass, objectAttribute.string), python returns an AttributeError
Any good solution here?
One thing I have thought of trying is creating methods to return those sub-attributes, something like:
class outputObject:
...
def attributeIWant(self,...):
return self.subObject.attributeIWant
...
Even then, it seems like getattr() will return an error because attributeIWant() is supposed to be a function call, it's not actually an attribute. I'm not certain that this is even within the capabilities of Python to make this happen.
Thank you in advance for reading and/or responding, if anyone is familiar with a way to do this it would save me a bunch of refactoring or additional code.
edit: Additional Clarification
The class for example is outputData, and inside that class you could have and instance of the class furtherData, which has the attribute dataIWant:
class outputData:
example: furtherData
example = furtherData()
example.dataIWant = someData
...
with the python getattr I can't access both attributes directly in outputData and attributes of example unless I use separate calls, the attribute of example needs two calls to getattr.
Edit2: I have found a solution I think works for this, see below
I was able to figure this out - I just wrote a quick function that splits the attribute string (for example outputObj.subObj.propertyIWant) then proceeds down the resultant array, calling getattr on each subobject until it reaches the end of the array and returns the actual attribute.
Code:
def obtainAttribute(sample, attributeString: str):
baseObj = sample
attrArray = attributeString.split(".")
for string in attrArray:
if(attrArray.index(string) == (len(attrArray) - 1)):
return getattr(baseObj,string)
else:
baseObj = getattr(baseObj,string)
return "failed"
sample is the object and attributeString is, for example object.subObject.attributeYouWant
I want to access a property exist in the self.context using a variable. I have a variable name "prop" and it contains a value and it is already set in the self.context. I am using Flask Restplus framework.
prop = 'binding'
If I try to access this property like below then it gives me an error:
Object is not subscriptable
I want to know if there is any way to get the value? Like doing this:
print(self.context[prop])
I only get one solution don't know if its correct or not, I tried this :
self.context.__getattribute__(prop)
There are two ways to do this, the simplest is using getattr:
getattr(self.context, prop)
This function internally calls __getattribute__ so it's the same as your code, just a little neater.
However, you still have the problem that you probably only want to access some of the context, while not risking editing values set by different parts of your application. A much better way would be to store a dict in context:
self.context.attributes = {}
self.context.attributes["binding"] = False
print(self.context.attributes[prop])
This way, only certain context variables can be accessed and those that are meant to be dynamic don't mess with any used by your application code directly.
I am working on Django rest framework which specifies a set format for function prototype for detail_route in ModelViewSet. Some background: -
The function takes in request object and lookup_field which can be the primary key for a particular table.
#detail_route(methods=["get"], url_path="get-some-data")
def get_some_data(self, request, id=None):
return Response(get_some_data(id))
Now as you can see, I do not need request object here, So should I keep it like this? or change it to
#detail_route(methods=["get"], url_path="get-some-data")
def get_some_data(self, _, id=None):
return Response(get_some_data(id))
Here I changed request to _ to indicate that I do not need this value.
which approach should be followed? Should I let it remain as a request, or change it to an underscore?
For the method arguments I would always use the proper variable name so that in future whether I work on it or my peers if I provide this code to someone else they don't have to struggle to understand what it is.
For now you might think to ignore it but since it is a method argument it would be better to have a name it stands for.
Or, let's say you are adding a docstring where you are including and defining which parameter is what. You would yourself appreciate it if some one had:
#param request: HTTP request object
instead of:
#param _: HTTP request object
If you leave the parameter exist, then give it a meaningful name always do good, even you do not use it.
In addition, _ has special use in python, check it in the following url.
What is the purpose of the single underscore "_" variable in Python?
I'd leave it with a descriptive name. Changing it to underscore or any other non-descriptive name is not beneficial.
class ...
self.response.headers.add_header('Set-Cookie','user_id = %s'% id_and_hash)
self.redirect("/app/login")
class ThanksHandler(webapp2.RequestHandler):
def get(self):
if 'user_id' in self.request.cookies:
self.response.out.write('user_id')
else:
self.response.out.write("wrong") // what i am getting
and i have this cookie (I saw in a manager of cookies)
name: user_id
content: 30|a9bdc98e952c0e787aaf0e5466809eea71635d38446d30a9f71f2d15e99fa701
well, basically the problem is that i can't retrieve the cookie that has been initialized. Any reason for that?
When setting the cookie directly using the "Set-Cookie" HTTP-header you have to also take care of the cookie-attributes (depending on how you want to use the cookie).
In this case you set the cookie for example in the path /app/auth and then redirect to /app/login. If you don't explicit specify the cookie-path the browser assumes /app/auth and therefore the cookie is not sent when requesting /app/login. This behaviour is specified in the RFC 6265 (this is more recent than the one I cited in my comment but now the exact algorithm is included in section 5.1.4).
To set the path (or any other cookie-attribute) you can append a list of semicolon-delimited name=value pairs. In this case you want to set the path to / (it could be something different like /app):
self.response.headers.add_header('Set-Cookie','user_id=%s; Path=/'% id_and_hash)
Of course most libraries/frameworks already provide a wrapper for the "Set-Cookie" header. In the case of "webapp2" you can set the cookie with response.set_cookie:
self.response.set_cookie('user_id', id_and_hash)
It's automatically setting the path to / so you don't have to worry about it (it does escape the values properly too).
I need magic tool, that helps me to understand where one my problem variable is changed in the code.
I know about perfect tool:
pdb.set_trace()
and I need something similar format, but about only one variable changing history.
For example, my current problem is strange value of context['request'] variable inside Django's tag template definition method. The value is string '<<request>>' and I don't understand where it modified from Django's Request object. I can't debug it, because problem is appearing not so often, but permanently. I only see it in error emails and I can't call it specially. The perfect solution will be to create a log with variable's assignment and any modifications.
I'm not really familiar with django, so your mileage may vary. In general, you can override the __setitem__ method on objects to capture item assignment. However, this doesn't work on dictionaries, only on user-created classes, so first of all it depends on what this context object is.
As I get from a short look at the Django docs, it's indeed not a regular dict, so you can try something like this:
def log_setitem(obj):
class Logged(obj.__class__):
def __setitem__(self, item, val):
print "setting", item, "to", val, "on", self
super(Logged, self).__setitem__(item, val)
obj.__class__ = Logged
d = {}
try:
log_setitem(d) # throws an error
except:
print "doesn't work"
class Dict2(dict):
pass
d2 = Dict2()
log_setitem(d2) # this works
d2["hello"] = "world" # prints the log message before assigning
Even if this works, it of course only works if the assignment actually happens through the "standard" way, i.e. somewhere in the code there's a call like context['request'] = "something".
Might be worth a try, but I can't promise you anything.